diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..4ffbd908 --- /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 00000000..fd2792b6 --- /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 00000000..3e5f752b --- /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 00000000..3ee2f686 --- /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 00000000..e4c0be6b --- /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 d03cdb57..34ac7342 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,32 @@ -/* -!/src/ -!build.gradle \ No newline at end of file +.gradle +.settings +/.idea/ +/.vscode/ +/run/ +/build/ +/eclipse/ +.classpath +.project +/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/build.gradle b/build.gradle index 4398c028..3fa171e0 100644 --- a/build.gradle +++ b/build.gradle @@ -1,70 +1,1510 @@ +//version: 1683705740 +/* + DO NOT CHANGE THIS FILE! + Also, you may replace this file at any time if there is an update available. + Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/master/build.gradle for updates. + */ + + +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import com.gtnewhorizons.retrofuturagradle.ObfuscationAttribute +import com.gtnewhorizons.retrofuturagradle.mcp.ReobfuscatedJar +import com.gtnewhorizons.retrofuturagradle.minecraft.RunMinecraftTask +import com.gtnewhorizons.retrofuturagradle.util.Distribution +import com.matthewprenger.cursegradle.CurseArtifact +import com.matthewprenger.cursegradle.CurseRelation +import com.modrinth.minotaur.dependencies.ModDependency +import com.modrinth.minotaur.dependencies.VersionDependency +import org.gradle.internal.logging.text.StyledTextOutput.Style +import org.gradle.internal.logging.text.StyledTextOutputFactory +import org.gradle.internal.xml.XmlTransformer +import org.jetbrains.gradle.ext.Application +import org.jetbrains.gradle.ext.Gradle + +import javax.inject.Inject +import java.nio.file.Files +import java.nio.file.Paths +import java.util.concurrent.TimeUnit + buildscript { repositories { mavenCentral() + + maven { + name 'forge' + url 'https://maven.minecraftforge.net' + } maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" + // GTNH RetroFuturaGradle and ASM Fork + name "GTNH Maven" + url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + allowInsecureProtocol = true } maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" + name 'sonatype' + url 'https://oss.sonatype.org/content/repositories/snapshots/' + } + maven { + name 'Scala CI dependencies' + url 'https://repo1.maven.org/maven2/' + } + + mavenLocal() + } +} +plugins { + id 'java-library' + id "org.jetbrains.gradle.plugin.idea-ext" version "1.1.7" + id 'eclipse' + id 'scala' + id 'maven-publish' + id 'org.jetbrains.kotlin.jvm' version '1.8.0' apply false + id 'org.jetbrains.kotlin.kapt' version '1.8.0' apply false + id 'com.google.devtools.ksp' version '1.8.0-1.0.9' apply false + id 'org.ajoberstar.grgit' version '4.1.1' // 4.1.1 is the last jvm8 supporting version, unused, available for addon.gradle + id 'com.github.johnrengelman.shadow' version '8.1.1' apply false + id 'com.palantir.git-version' version '3.0.0' apply false + id 'de.undercouch.download' version '5.4.0' + id 'com.github.gmazzo.buildconfig' version '3.1.0' apply false // Unused, available for addon.gradle + id 'com.diffplug.spotless' version '6.13.0' apply false // 6.13.0 is the last jvm8 supporting version + id 'com.modrinth.minotaur' version '2.+' apply false + id 'com.matthewprenger.cursegradle' version '1.4.0' apply false + id 'com.gtnewhorizons.retrofuturagradle' version '1.3.11' +} + +print("You might want to check out './gradlew :faq' if your build fails.\n") + +boolean settingsupdated = verifySettingsGradle() +settingsupdated = verifyGitAttributes() || settingsupdated +if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") + +// In submodules, .git is a file pointing to the real git dir +if (project.file('.git/HEAD').isFile() || project.file('.git').isFile()) { + apply plugin: 'com.palantir.git-version' +} + +def out = services.get(StyledTextOutputFactory).create('an-output') + +def projectJavaVersion = JavaLanguageVersion.of(8) + +boolean disableSpotless = project.hasProperty("disableSpotless") ? project.disableSpotless.toBoolean() : false + +checkPropertyExists("modName") +checkPropertyExists("modId") +checkPropertyExists("modGroup") +checkPropertyExists("autoUpdateBuildScript") +checkPropertyExists("minecraftVersion") +checkPropertyExists("forgeVersion") +checkPropertyExists("replaceGradleTokenInFile") +checkPropertyExists("gradleTokenVersion") +checkPropertyExists("apiPackage") +checkPropertyExists("accessTransformersFile") +checkPropertyExists("usesMixins") +checkPropertyExists("mixinPlugin") +checkPropertyExists("mixinsPackage") +checkPropertyExists("coreModClass") +checkPropertyExists("containsMixinsAndOrCoreModOnly") +checkPropertyExists("usesShadowedDependencies") +checkPropertyExists("developmentEnvironmentUserName") + +propertyDefaultIfUnset("generateGradleTokenClass", "") +propertyDefaultIfUnset("includeWellKnownRepositories", true) +propertyDefaultIfUnset("noPublishedSources", false) +propertyDefaultIfUnset("usesMixinDebug", project.usesMixins) +propertyDefaultIfUnset("forceEnableMixins", false) +propertyDefaultIfUnset("channel", "stable") +propertyDefaultIfUnset("mappingsVersion", "12") +propertyDefaultIfUnset("modrinthProjectId", "") +propertyDefaultIfUnset("modrinthRelations", "") +propertyDefaultIfUnset("curseForgeProjectId", "") +propertyDefaultIfUnset("curseForgeRelations", "") +propertyDefaultIfUnset("minimizeShadowedDependencies", true) +propertyDefaultIfUnset("relocateShadowedDependencies", true) +// Deprecated properties (kept for backwards compat) +propertyDefaultIfUnset("gradleTokenModId", "") +propertyDefaultIfUnset("gradleTokenModName", "") +propertyDefaultIfUnset("gradleTokenGroupName", "") + +propertyDefaultIfUnset("enableModernJavaSyntax", false) // On by default for new projects only +propertyDefaultIfUnset("enableGenericInjection", false) // On by default for new projects only + +// this is meant to be set using the user wide property file. by default we do nothing. +propertyDefaultIfUnset("ideaOverrideBuildType", "") // Can be nothing, "gradle" or "idea" + +project.extensions.add(com.diffplug.blowdryer.Blowdryer, "Blowdryer", com.diffplug.blowdryer.Blowdryer) // Make blowdryer available in "apply from:" scripts +if (!disableSpotless) { + apply plugin: 'com.diffplug.spotless' + apply from: Blowdryer.file('spotless.gradle') +} + +String javaSourceDir = "src/main/java/" +String scalaSourceDir = "src/main/scala/" +String kotlinSourceDir = "src/main/kotlin/" + +if (usesShadowedDependencies.toBoolean()) { + apply plugin: "com.github.johnrengelman.shadow" +} + +java { + toolchain { + if (enableModernJavaSyntax.toBoolean()) { + languageVersion.set(JavaLanguageVersion.of(17)) + } else { + languageVersion.set(projectJavaVersion) } + vendor.set(JvmVendorSpec.AZUL) + } + if (!noPublishedSources) { + withSourcesJar() } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = "UTF-8" +} + +tasks.withType(ScalaCompile).configureEach { + options.encoding = "UTF-8" +} + +pluginManager.withPlugin('org.jetbrains.kotlin.jvm') { + // If Kotlin is enabled in the project + kotlin { + jvmToolchain(8) + } + // Kotlin hacks our source sets, so we hack Kotlin's tasks + def disabledKotlinTaskList = [ + "kaptGenerateStubsMcLauncherKotlin", + "kaptGenerateStubsPatchedMcKotlin", + "kaptGenerateStubsInjectedTagsKotlin", + "compileMcLauncherKotlin", + "compilePatchedMcKotlin", + "compileInjectedTagsKotlin", + "kaptMcLauncherKotlin", + "kaptPatchedMcKotlin", + "kaptInjectedTagsKotlin", + "kspMcLauncherKotlin", + "kspPatchedMcKotlin", + "kspInjectedTagsKotlin", + ] + tasks.configureEach { task -> + if (task.name in disabledKotlinTaskList) { + task.enabled = false + } + } +} + +configurations { + create("runtimeOnlyNonPublishable") { + description = "Runtime only dependencies that are not published alongside the jar" + canBeConsumed = false + canBeResolved = false + } + + create("devOnlyNonPublishable") { + description = "Runtime and compiletime dependencies that are not published alongside the jar (compileOnly + runtimeOnlyNonPublishable)" + canBeConsumed = false + canBeResolved = false + } + compileOnly.extendsFrom(devOnlyNonPublishable) + runtimeOnlyNonPublishable.extendsFrom(devOnlyNonPublishable) +} + +if (enableModernJavaSyntax.toBoolean()) { + repositories { + mavenCentral { + mavenContent { + includeGroup("me.eigenraven.java8unsupported") + } + } + } + dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + annotationProcessor 'com.github.bsideup.jabel:jabel-javac-plugin:1.0.0' + // workaround for https://github.com/bsideup/jabel/issues/174 + annotationProcessor 'net.java.dev.jna:jna-platform:5.13.0' + compileOnly('com.github.bsideup.jabel:jabel-javac-plugin:1.0.0') { + transitive = false // We only care about the 1 annotation class + } + // Allow using jdk.unsupported classes like sun.misc.Unsafe in the compiled code, working around JDK-8206937. + patchedMinecraft('me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0') + } + + tasks.withType(JavaCompile).configureEach { + if (it.name in ["compileMcLauncherJava", "compilePatchedMcJava"]) { + return + } + sourceCompatibility = 17 // for the IDE support + options.release.set(8) + + javaCompiler.set(javaToolchains.compilerFor { + languageVersion.set(JavaLanguageVersion.of(17)) + vendor.set(JvmVendorSpec.AZUL) + }) } } -apply plugin: 'forge' +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} + +final String modGroupPath = modGroup.toString().replace('.' as char, '/' as char) +final String apiPackagePath = apiPackage.toString().replace('.' as char, '/' as char) -version = "1.7.10-1.08.4" -group= "gollorum.signpost" -archivesBaseName = "signpost" +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) { + for (atFile in accessTransformersFile.split(",")) { + String targetFile = "src/main/resources/META-INF/" + atFile.trim() + if (!getFile(targetFile).exists()) { + throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) + } + tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(targetFile) + tasks.srgifyBinpatchedJar.accessTransformerFiles.from(targetFile) + } +} else { + boolean atsFound = false + for (File at : sourceSets.getByName("main").resources.files) { + if (at.name.toLowerCase().endsWith("_at.cfg")) { + atsFound = true + tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(at) + tasks.srgifyBinpatchedJar.accessTransformerFiles.from(at) + } + } + for (File at : sourceSets.getByName("api").resources.files) { + if (at.name.toLowerCase().endsWith("_at.cfg")) { + atsFound = true + tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(at) + tasks.srgifyBinpatchedJar.accessTransformerFiles.from(at) + } + } + if (atsFound) { + logger.warn("Found and added access transformers in the resources folder, please configure gradle.properties to explicitly mention them by name") + } +} + +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.configureEach { + 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 = 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 = "com.github.GTNewHorizons" +if (project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { + archivesBaseName = customArchiveBaseName +} else { + archivesBaseName = modId +} -sourceCompatibility = 1.8 -targetCompatibility = 1.8 minecraft { - version = "1.7.10-10.13.4.1558-1.7.10" - runDir = "run" + if (replaceGradleTokenInFile) { + for (f in replaceGradleTokenInFile.split(',')) { + tagReplacementFiles.add f + } + } + if (gradleTokenModId) { + injectedTags.put gradleTokenModId, modId + } + if (gradleTokenModName) { + injectedTags.put gradleTokenModName, modName + } + if (gradleTokenVersion) { + injectedTags.put gradleTokenVersion, modVersion + } + if (gradleTokenGroupName) { + injectedTags.put gradleTokenGroupName, modGroup + } + if (enableGenericInjection.toBoolean()) { + injectMissingGenerics.set(true) + } + + username = developmentEnvironmentUserName.toString() + + lwjgl3Version = "3.3.2" + + // Enable assertions in the current mod + extraRunJvmArguments.add("-ea:${modGroup}") + + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + if (usesMixinDebug.toBoolean()) { + extraRunJvmArguments.addAll([ + "-Dmixin.debug.countInjections=true", + "-Dmixin.debug.verbose=true", + "-Dmixin.debug.export=true" + ]) + } + } + + // Blowdryer is present in some old mod builds, do not propagate it further as a dependency + // IC2 has no reobf jars in its Maven + groupsToExcludeFromAutoReobfMapping.addAll(["com.diffplug", "com.diffplug.durian", "net.industrial-craft"]) +} + +if (generateGradleTokenClass) { + tasks.injectTags.outputClassName.set(generateGradleTokenClass) +} + +// Custom reobf auto-mappings +configurations.configureEach { + dependencies.configureEach { dep -> + if (dep instanceof org.gradle.api.artifacts.ExternalModuleDependency) { + if (dep.group == "net.industrial-craft" && dep.name == "industrialcraft-2") { + // https://www.curseforge.com/minecraft/mc-mods/industrial-craft/files/2353971 + project.dependencies.reobfJarConfiguration("curse.maven:ic2-242638:2353971") + } + } + } + def obfuscationAttr = it.attributes.getAttribute(ObfuscationAttribute.OBFUSCATION_ATTRIBUTE) + if (obfuscationAttr != null && obfuscationAttr.name == ObfuscationAttribute.SRG) { + resolutionStrategy.eachDependency { DependencyResolveDetails details -> + // Remap CoFH core cursemaven dev jar to the obfuscated version for runObfClient/Server + if (details.requested.group == 'curse.maven' && details.requested.name.endsWith('-69162') && details.requested.version == '2388751') { + details.useVersion '2388750' + details.because 'Pick obfuscated jar' + } + } + } +} + +// Ensure tests have access to minecraft classes +sourceSets { + test { + java { + compileClasspath += sourceSets.patchedMc.output + sourceSets.mcLauncher.output + runtimeClasspath += sourceSets.patchedMc.output + sourceSets.mcLauncher.output + } + } +} + +if (file('addon.gradle').exists()) { + apply from: 'addon.gradle' +} + +// Allow unsafe repos but warn +repositories.configureEach { repo -> + if (repo instanceof org.gradle.api.artifacts.repositories.UrlArtifactRepository) { + if (repo.getUrl() != null && repo.getUrl().getScheme() == "http" && !repo.allowInsecureProtocol) { + logger.warn("Deprecated: Allowing insecure connections for repo '${repo.name}' - add 'allowInsecureProtocol = true'") + repo.allowInsecureProtocol = true + } + } +} + +apply from: 'repositories.gradle' + +configurations { + runtimeClasspath.extendsFrom(runtimeOnlyNonPublishable) + testRuntimeClasspath.extendsFrom(runtimeOnlyNonPublishable) + for (config in [compileClasspath, runtimeClasspath, testCompileClasspath, testRuntimeClasspath]) { + if (usesShadowedDependencies.toBoolean()) { + config.extendsFrom(shadowImplementation) + // TODO: remove Compile after all uses are refactored to Implementation + config.extendsFrom(shadeCompile) + config.extendsFrom(shadowCompile) + } + } + // A "bag-of-dependencies"-style configuration for backwards compatibility, gets put in "api" + create("compile") { + description = "Deprecated: use api or implementation instead, gets put in api" + canBeConsumed = false + canBeResolved = false + visible = false + } + create("testCompile") { + description = "Deprecated: use testImplementation instead" + canBeConsumed = false + canBeResolved = false + visible = false + } + api.extendsFrom(compile) + testImplementation.extendsFrom(testCompile) +} + +afterEvaluate { + if (!configurations.compile.allDependencies.empty || !configurations.testCompile.allDependencies.empty) { + logger.warn("This project uses deprecated `compile` dependencies, please migrate to using `api` and `implementation`") + logger.warn("For more details, see https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/master/dependencies.gradle") + } +} + +repositories { + maven { + name 'Overmind forge repo mirror' + url 'https://gregtech.overminddl1.com/' + mavenContent { + excludeGroup("net.minecraftforge") // missing the `universal` artefact + } + } + maven { + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + allowInsecureProtocol = true + } + maven { + name 'sonatype' + url 'https://oss.sonatype.org/content/repositories/snapshots/' + content { + includeGroup "org.lwjgl" + } + } + if (includeWellKnownRepositories.toBoolean()) { + maven { + name "CurseMaven" + url "https://cursemaven.com" + content { + includeGroup "curse.maven" + } + } + maven { + name = "ic2" + url = "https://maven.ic2.player.to/" + metadataSources { + mavenPom() + artifact() + } + } + maven { + name = "ic2-mirror" + url = "https://maven2.ic2.player.to/" + metadataSources { + mavenPom() + artifact() + } + } + maven { + name "MMD Maven" + url "https://maven.mcmoddev.com/" + } + } } -dependencies {} +def mixinProviderGroup = "io.github.legacymoddingmc" +def mixinProviderModule = "unimixins" +def mixinProviderVersion = "0.1.7.1" +def mixinProviderSpecNoClassifer = "${mixinProviderGroup}:${mixinProviderModule}:${mixinProviderVersion}" +def mixinProviderSpec = "${mixinProviderSpecNoClassifer}:dev" +ext.mixinProviderSpec = mixinProviderSpec + +dependencies { + if (usesMixins.toBoolean()) { + annotationProcessor('org.ow2.asm:asm-debug-all:5.0.3') + annotationProcessor('com.google.guava:guava:24.1.1-jre') + annotationProcessor('com.google.code.gson:gson:2.8.6') + annotationProcessor(mixinProviderSpec) + if (usesMixinDebug.toBoolean()) { + runtimeOnlyNonPublishable('org.jetbrains:intellij-fernflower:1.2.1.16') + } + } + if (usesMixins.toBoolean()) { + implementation(mixinProviderSpec) + } else if (forceEnableMixins.toBoolean()) { + runtimeOnlyNonPublishable(mixinProviderSpec) + } +} -processResources { +pluginManager.withPlugin('org.jetbrains.kotlin.kapt') { + if (usesMixins.toBoolean()) { + dependencies { + kapt(mixinProviderSpec) + } + } +} + +// Replace old mixin mods with unimixins +// https://docs.gradle.org/8.0.2/userguide/resolution_rules.html#sec:substitution_with_classifier +configurations.all { + resolutionStrategy.dependencySubstitution { + substitute module('com.gtnewhorizon:gtnhmixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('com.github.GTNewHorizons:Mixingasm') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('com.github.GTNewHorizons:SpongePoweredMixin') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('com.github.GTNewHorizons:SpongeMixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Unimixins replaces other mixin mods") + substitute module('io.github.legacymoddingmc:unimixins') using module(mixinProviderSpecNoClassifer) withClassifier("dev") because("Our previous unimixins upload was missing the dev classifier") + } +} + +apply from: 'dependencies.gradle' + +def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' +def mixinTmpDir = buildDir.path + File.separator + 'tmp' + File.separator + 'mixins' +def refMap = "${mixinTmpDir}" + File.separator + mixingConfigRefMap +def mixinSrg = "${mixinTmpDir}" + File.separator + "mixins.srg" + +tasks.register('generateAssets') { + group = "GTNH Buildscript" + description = "Generates a mixin config file at /src/main/resources/mixins.modid.json if needed" + onlyIf { usesMixins.toBoolean() } + doLast { + def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json") + if (!mixinConfigFile.exists()) { + def mixinPluginLine = "" + if (!mixinPlugin.isEmpty()) { + // 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": [] +} +""" + } + } +} + +if (usesMixins.toBoolean()) { + tasks.named("reobfJar", ReobfuscatedJar).configure { + extraSrgFiles.from(mixinSrg) + } + + tasks.named("processResources").configure { + dependsOn("generateAssets") + } + + tasks.named("compileJava", JavaCompile).configure { + doFirst { + new File(mixinTmpDir).mkdirs() + } + options.compilerArgs += [ + "-AreobfSrgFile=${tasks.reobfJar.srg.get().asFile}", + "-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" + ] + } + + pluginManager.withPlugin('org.jetbrains.kotlin.kapt') { + kapt { + correctErrorTypes = true + javacOptions { + option("-AreobfSrgFile=${tasks.reobfJar.srg.get().asFile}") + option("-AoutSrgFile=$mixinSrg") + option("-AoutRefMapFile=$refMap") + } + } + tasks.configureEach { task -> + if (task.name == "kaptKotlin") { + task.doFirst { + new File(mixinTmpDir).mkdirs() + } + } + } + } + +} + +tasks.named("processResources", ProcessResources).configure { + // this will ensure that this task is redone when the versions change. inputs.property "version", project.version - inputs.property "mcversion", project.minecraft.version + inputs.property "mcversion", project.minecraft.mcVersion + exclude("spotless.gradle") - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - - expand 'version':project.version, 'mcversion':project.minecraft.version + // replace stuff in mcmod.info, nothing else. replaces ${key} with value in text + filesMatching("mcmod.info") { + expand "minecraftVersion": project.minecraft.mcVersion, + "modVersion": modVersion, + "modId": modId, + "modName": modName } - - from(sourceSets.main.resources.srcDirs) { - exclude 'mcmod.info' + + if (usesMixins.toBoolean()) { + from refMap + dependsOn("compileJava", "compileScala") } } -task deobfJar(type: Jar) { - from sourceSets.main.output - classifier = 'deobf' +ext.java17Toolchain = (JavaToolchainSpec spec) -> { + spec.languageVersion.set(JavaLanguageVersion.of(17)) + spec.vendor.set(JvmVendorSpec.matching("jetbrains")) } -task sourceJar(type: Jar) { - from sourceSets.main.allSource - classifier = 'sources' +ext.java17DependenciesCfg = configurations.create("java17Dependencies") { + extendsFrom(configurations.getByName("runtimeClasspath")) // Ensure consistent transitive dependency resolution + canBeConsumed = false +} +ext.java17PatchDependenciesCfg = configurations.create("java17PatchDependencies") { + canBeConsumed = false } -tasks.build.dependsOn('sourceJar', 'deobfJar') +dependencies { + def lwjgl3ifyVersion = '1.3.5' + def asmVersion = '9.4' + if (modId != 'lwjgl3ify') { + java17Dependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}") + } + if (modId != 'hodgepodge') { + java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.2.8') + } + + java17PatchDependencies('net.minecraft:launchwrapper:1.15') {transitive = false} + java17PatchDependencies("org.ow2.asm:asm:${asmVersion}") + java17PatchDependencies("org.ow2.asm:asm-commons:${asmVersion}") + java17PatchDependencies("org.ow2.asm:asm-tree:${asmVersion}") + java17PatchDependencies("org.ow2.asm:asm-analysis:${asmVersion}") + java17PatchDependencies("org.ow2.asm:asm-util:${asmVersion}") + java17PatchDependencies('org.ow2.asm:asm-deprecated:7.1') + java17PatchDependencies("org.apache.commons:commons-lang3:3.12.0") + java17PatchDependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}:forgePatches") {transitive = false} +} + +ext.java17JvmArgs = [ + // Java 9+ support + "--illegal-access=warn", + "-Djava.security.manager=allow", + "-Dfile.encoding=UTF-8", + "--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED", + "--add-opens", "java.base/java.net=ALL-UNNAMED", + "--add-opens", "java.base/java.nio=ALL-UNNAMED", + "--add-opens", "java.base/java.io=ALL-UNNAMED", + "--add-opens", "java.base/java.lang=ALL-UNNAMED", + "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED", + "--add-opens", "java.base/java.text=ALL-UNNAMED", + "--add-opens", "java.base/java.util=ALL-UNNAMED", + "--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED", + "--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", + "--add-opens", "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming", + "--add-opens", "java.desktop/sun.awt.image=ALL-UNNAMED", + "--add-modules", "jdk.dynalink", + "--add-opens", "jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED", + "--add-modules", "java.sql.rowset", + "--add-opens", "java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED" +] + +ext.hotswapJvmArgs = [ + // DCEVM advanced hot reload + "-XX:+AllowEnhancedClassRedefinition", + "-XX:HotswapAgent=fatjar" +] + +ext.setupHotswapAgentTask = tasks.register("setupHotswapAgent") { + group = "GTNH Buildscript" + description = "Installs a recent version of HotSwapAgent into the Java 17 JetBrains runtime directory" + def hsaUrl = 'https://github.com/HotswapProjects/HotswapAgent/releases/download/1.4.2-SNAPSHOT/hotswap-agent-1.4.2-SNAPSHOT.jar' + def targetFolderProvider = javaToolchains.launcherFor(java17Toolchain).map {it.metadata.installationPath.dir("lib/hotswap")} + def targetFilename = "hotswap-agent.jar" + onlyIf { + !targetFolderProvider.get().file(targetFilename).asFile.exists() + } + doLast { + def targetFolder = targetFolderProvider.get() + targetFolder.asFile.mkdirs() + download.run { + src hsaUrl + dest targetFolder.file(targetFilename).asFile + overwrite false + tempAndMove true + } + } +} + +public abstract class RunHotswappableMinecraftTask extends RunMinecraftTask { + // IntelliJ doesn't seem to allow commandline arguments so we also support an env variable + private boolean enableHotswap = Boolean.valueOf(System.getenv("HOTSWAP")); + + @Input + public boolean getEnableHotswap() { return enableHotswap } + @Option(option = "hotswap", description = "Enables HotSwapAgent for enhanced class reloading under a debugger") + public boolean setEnableHotswap(boolean enable) { enableHotswap = enable } + + @Inject + public RunHotswappableMinecraftTask(Distribution side, String superTask, org.gradle.api.invocation.Gradle gradle) { + super(side, gradle) + + this.lwjglVersion = 3 + this.javaLauncher = project.javaToolchains.launcherFor(project.java17Toolchain) + this.extraJvmArgs.addAll(project.java17JvmArgs) + this.extraJvmArgs.addAll(project.provider(() -> enableHotswap ? project.hotswapJvmArgs : [])) + + this.classpath(project.java17PatchDependenciesCfg) + if (side == Distribution.CLIENT) { + this.classpath(project.minecraftTasks.lwjgl3Configuration) + } + // Use a raw provider instead of map to not create a dependency on the task + this.classpath(project.provider(() -> project.tasks.named(superTask, RunMinecraftTask).get().classpath)) + this.classpath.filter { file -> + !file.path.contains("2.9.4-nightly-20150209") // Remove lwjgl2 + } + this.classpath(project.java17DependenciesCfg) + } + + public void setup(Project project) { + super.setup(project) + if (project.usesMixins.toBoolean()) { + this.extraJvmArgs.addAll(project.provider(() -> { + def mixinCfg = project.configurations.detachedConfiguration(project.dependencies.create(project.mixinProviderSpec)) + mixinCfg.canBeConsumed = false + mixinCfg.transitive = false + enableHotswap ? ["-javaagent:" + mixinCfg.singleFile.absolutePath] : [] + })) + } + } +} + +def runClient17Task = tasks.register("runClient17", RunHotswappableMinecraftTask, Distribution.CLIENT, "runClient") +runClient17Task.configure { + setup(project) + group = "Modded Minecraft" + description = "Runs the modded client using Java 17, lwjgl3ify and Hodgepodge" + dependsOn(setupHotswapAgentTask, mcpTasks.launcherSources.classesTaskName, minecraftTasks.taskDownloadVanillaAssets, mcpTasks.taskPackagePatchedMc, 'jar') + mainClass = "GradleStart" + username = minecraft.username + userUUID = minecraft.userUUID +} + +def runServer17Task = tasks.register("runServer17", RunHotswappableMinecraftTask, Distribution.DEDICATED_SERVER, "runServer") +runServer17Task.configure { + setup(project) + group = "Modded Minecraft" + description = "Runs the modded server using Java 17, lwjgl3ify and Hodgepodge" + dependsOn(setupHotswapAgentTask, mcpTasks.launcherSources.classesTaskName, minecraftTasks.taskDownloadVanillaAssets, mcpTasks.taskPackagePatchedMc, 'jar') + mainClass = "GradleStartServer" + extraArgs.add("nogui") +} + +def getManifestAttributes() { + 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 +} + +tasks.named("jar", Jar).configure { + manifest { + attributes(getManifestAttributes()) + } +} + +if (usesShadowedDependencies.toBoolean()) { + tasks.named("shadowJar", ShadowJar).configure { + manifest { + attributes(getManifestAttributes()) + } + + if (minimizeShadowedDependencies.toBoolean()) { + minimize() // This will only allow shading for actually used classes + } + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile, + project.configurations.shadeCompile + ] + archiveClassifier.set('dev') + if (relocateShadowedDependencies.toBoolean()) { + relocationPrefix = modGroup + ".shadow" + enableRelocation = true + } + } + configurations.runtimeElements.outgoing.artifacts.clear() + configurations.apiElements.outgoing.artifacts.clear() + configurations.runtimeElements.outgoing.artifact(tasks.named("shadowJar", ShadowJar)) + configurations.apiElements.outgoing.artifact(tasks.named("shadowJar", ShadowJar)) + tasks.named("jar", Jar) { + enabled = false + finalizedBy(tasks.shadowJar) + } + tasks.named("reobfJar", ReobfuscatedJar) { + inputJar.set(tasks.named("shadowJar", ShadowJar).flatMap({it.archiveFile})) + } + AdhocComponentWithVariants javaComponent = (AdhocComponentWithVariants) project.components.findByName("java") + javaComponent.withVariantsFromConfiguration(configurations.shadowRuntimeElements) { + skip() + } + for (runTask in ["runClient", "runServer", "runClient17", "runServer17"]) { + tasks.named(runTask).configure { + dependsOn("shadowJar") + } + } +} +ext.publishableDevJar = usesShadowedDependencies.toBoolean() ? tasks.shadowJar : tasks.jar +ext.publishableObfJar = tasks.reobfJar + +tasks.register('apiJar', 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 { - archives deobfJar - archives sourceJar + if (!noPublishedSources) { + archives tasks.named("sourcesJar") + } + if (apiPackage) { + archives tasks.named("apiJar") + } } idea { - module { - inheritOutputDirs = true - } -} \ No newline at end of file + module { + downloadJavadoc = true + downloadSources = true + inheritOutputDirs = true + } + project { + settings { + if (ideaOverrideBuildType != "") { + delegateActions { + if ("gradle".equalsIgnoreCase(ideaOverrideBuildType)) { + delegateBuildRunToGradle = true + testRunner = org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.GRADLE + } else if ("idea".equalsIgnoreCase(ideaOverrideBuildType)) { + delegateBuildRunToGradle = false + testRunner = org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.PLATFORM + } else { + throw GradleScriptException('Accepted value for ideaOverrideBuildType is one of gradle or idea.') + } + } + } + runConfigurations { + "1. Run Client"(Gradle) { + taskNames = ["runClient"] + } + "2. Run Server"(Gradle) { + taskNames = ["runServer"] + } + "1a. Run Client (Java 17)"(Gradle) { + taskNames = ["runClient17"] + } + "2a. Run Server (Java 17)"(Gradle) { + taskNames = ["runServer17"] + } + "1b. Run Client (Java 17, Hotswap)"(Gradle) { + taskNames = ["runClient17"] + envs = ["HOTSWAP": "true"] + } + "2b. Run Server (Java 17, Hotswap)"(Gradle) { + taskNames = ["runServer17"] + envs = ["HOTSWAP": "true"] + } + "3. Run Obfuscated Client"(Gradle) { + taskNames = ["runObfClient"] + } + "4. Run Obfuscated Server"(Gradle) { + taskNames = ["runObfServer"] + } + if (!disableSpotless) { + "5. Apply spotless"(Gradle) { + taskNames = ["spotlessApply"] + } + } + def coreModArgs = "" + if (coreModClass) { + coreModArgs = ' "-Dfml.coreMods.load=' + modGroup + '.' + coreModClass + '"' + } + "Run Client (IJ Native)"(Application) { + mainClass = "GradleStart" + moduleName = project.name + ".ideVirtualMain" + afterEvaluate { + workingDirectory = tasks.runClient.workingDir.absolutePath + programParameters = tasks.runClient.calculateArgs(project).collect { '"' + it + '"' }.join(' ') + jvmArgs = tasks.runClient.calculateJvmArgs(project).collect { '"' + it + '"' }.join(' ') + + ' ' + tasks.runClient.systemProperties.collect { '"-D' + it.key + '=' + it.value.toString() + '"' }.join(' ') + + coreModArgs + } + } + "Run Server (IJ Native)"(Application) { + mainClass = "GradleStartServer" + moduleName = project.name + ".ideVirtualMain" + afterEvaluate { + workingDirectory = tasks.runServer.workingDir.absolutePath + programParameters = tasks.runServer.calculateArgs(project).collect { '"' + it + '"' }.join(' ') + jvmArgs = tasks.runServer.calculateJvmArgs(project).collect { '"' + it + '"' }.join(' ') + + ' ' + tasks.runServer.systemProperties.collect { '"-D' + it.key + '=' + it.value.toString() + '"' }.join(' ') + + coreModArgs + } + } + } + compiler.javac { + afterEvaluate { + javacAdditionalOptions = "-encoding utf8" + moduleJavacAdditionalOptions = [ + (project.name + ".main"): tasks.compileJava.options.compilerArgs.collect { '"' + it + '"' }.join(' ') + ] + } + } + withIDEADir { File ideaDir -> + if (!ideaDir.path.contains(".idea")) { + // If an .ipr file exists, the project root directory is passed here instead of the .idea subdirectory + ideaDir = new File(ideaDir, ".idea") + } + if (ideaDir.isDirectory()) { + def miscFile = new File(ideaDir, "misc.xml") + if (miscFile.isFile()) { + boolean dirty = false + def miscTransformer = new XmlTransformer() + miscTransformer.addAction { root -> + Node rootNode = root.asNode() + def rootManager = rootNode + .component.find { it.@name == 'ProjectRootManager' } + if (!rootManager) { + rootManager = rootNode.appendNode('component', ['name': 'ProjectRootManager', 'version': '2']) + dirty = true + } + def output = rootManager.output + if (!output) { + output = rootManager.appendNode('output') + dirty = true + } + if (!output.@url) { + // Only modify the output url if it doesn't yet have one, or if the existing one is blank somehow. + // This is a sensible default for most setups + output.@url = 'file://$PROJECT_DIR$/build/ideaBuild' + dirty = true + } + } + def result = miscTransformer.transform(miscFile.text) + if (dirty) { + miscFile.write(result) + } + } else { + miscFile.text = """ + + + + + +""" + } + } + } + } + } +} + +tasks.named("processIdeaSettings").configure { + dependsOn("injectTags") +} + +// workaround variable hiding in pom processing +def projectConfigs = project.configurations + +publishing { + publications { + create("maven", MavenPublication) { + from components.java + + if (apiPackage) { + artifact apiJar + } + + groupId = System.getenv("ARTIFACT_GROUP_ID") ?: project.group + artifactId = System.getenv("ARTIFACT_ID") ?: project.name + // Using the identified version, not project.version as it has the prepended 1.7.10 + version = System.getenv("RELEASE_VERSION") ?: identifiedVersion + } + } + + repositories { + maven { + url = "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases" + allowInsecureProtocol = true + 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 = publishableObfJar + additionalFiles = getSecondaryArtifacts() + gameVersions = [minecraftVersion] + loaders = ["forge"] + debugMode = false + } + + if (modrinthRelations.size() != 0) { + String[] deps = modrinthRelations.split(";") + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(":") + String[] qual = parts[0].split("-") + addModrinthDep(qual[0], qual[1], parts[1]) + } + } + if (usesMixins.toBoolean()) { + addModrinthDep("required", "project", "unimixins") + } + 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 publishableObfJar + 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", "unimixins") + } + tasks.curseforge.dependsOn(build) + tasks.publish.dependsOn(tasks.curseforge) +} + +def addModrinthDep(String scope, String type, String name) { + com.modrinth.minotaur.dependencies.Dependency dep; + if (!(scope in ["required", "optional", "incompatible", "embedded"])) { + throw new Exception("Invalid modrinth dependency scope: " + scope) + } + 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(String type, String 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 + +def buildscriptGradleVersion = "8.1.1" + +tasks.named('wrapper', Wrapper).configure { + gradleVersion = buildscriptGradleVersion +} + +tasks.register('updateBuildScript') { + group = 'GTNH Buildscript' + description = 'Updates the build script to the latest version' + + if (gradle.gradleVersion != buildscriptGradleVersion && !Boolean.getBoolean('DISABLE_BUILDSCRIPT_GRADLE_UPDATE')) { + dependsOn('wrapper') + } + + doLast { + if (performBuildScriptUpdate()) return + + print("Build script already up-to-date!") + } +} + +if (!project.getGradle().startParameter.isOffline() && !Boolean.getBoolean('DISABLE_BUILDSCRIPT_UPDATE_CHECK') && isNewBuildScriptVersionAvailable()) { + if (autoUpdateBuildScript.toBoolean()) { + performBuildScriptUpdate() + } else { + out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'") + if (gradle.gradleVersion != buildscriptGradleVersion) { + out.style(Style.SuccessHeader).println("updateBuildScript can update gradle from ${gradle.gradleVersion} to ${buildscriptGradleVersion}\n") + } + } +} + +// If you want to add more cases to this task, implement them as arguments if total amount to print gets too large +tasks.register('faq') { + group = 'GTNH Buildscript' + description = 'Prints frequently asked questions about building a project' + + doLast { + print("If your build fails to fetch dependencies, they might have been deleted and replaced by newer " + + "versions.\nCheck if the versions you try to fetch are still on the distributing sites.\n" + + "The links can be found in repositories.gradle and build.gradle:repositories, " + + "not build.gradle:buildscript.repositories - this one is for gradle plugin metadata.\n\n" + + "If your build fails to recognize the syntax of new Java versions, enable Jabel in your " + + "gradle.properties. See how it's done in GTNH ExampleMod/gradle.properties.") + } +} + +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() { + if (isNewBuildScriptVersionAvailable()) { + def buildscriptFile = getFile("build.gradle") + availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } + def out = services.get(StyledTextOutputFactory).create('buildscript-update-output') + out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + boolean settingsupdated = verifySettingsGradle() + settingsupdated = verifyGitAttributes() || settingsupdated + if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") + return true + } + return false +} + +boolean isNewBuildScriptVersionAvailable() { + Map parameters = ["connectTimeout": 2000, "readTimeout": 2000] + + String currentBuildScript = getFile("build.gradle").getText() + String currentBuildScriptHash = getVersionHash(currentBuildScript) + String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText() + String availableBuildScriptHash = getVersionHash(availableBuildScript) + + 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 "" +} + +// Parameter Deobfuscation + +tasks.register('deobfParams') { + group = 'GTNH Buildscript' + description = 'Rename all obfuscated parameter names inherited from Minecraft classes' + doLast { // TODO + + String mcpDir = "$project.gradle.gradleUserHomeDir/caches/minecraft/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion" + String mcpZIP = "$mcpDir/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + 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 ...") + copy { + from(zipTree(mcpZIP)) + into(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 +} + +// Dependency Deobfuscation (Deprecated, use the new RFG API documented in dependencies.gradle) + +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 ignored) { + return deobf(sourceURL, "deobf/${sourceURL.hashCode()}") + } +} + +def deobfMaven(String repoURL, String mavenDep) { + if (!repoURL.endsWith("/")) { + repoURL += "/" + } + String[] parts = mavenDep.split(":") + parts[0] = parts[0].replace('.', '/') + def jarURL = repoURL + parts[0] + "/" + parts[1] + "/" + parts[2] + "/" + parts[1] + "-" + parts[2] + ".jar" + return deobf(jarURL) +} + +def deobfCurse(String curseDep) { + return dependencies.rfg.deobf("curse.maven:$curseDep") +} + +// The method above is to be preferred. Use this method if the filename is not at the end of the URL. +def deobf(String sourceURL, String rawFileName) { + String bon2Version = "2.5.1" + String fileName = URLDecoder.decode(rawFileName, "UTF-8") + String cacheDir = "$project.gradle.gradleUserHomeDir/caches" + String obfFile = "$cacheDir/modules-2/files-2.1/${fileName}.jar" + + download.run { + src sourceURL + dest obfFile + quiet true + overwrite false + } + return dependencies.rfg.deobf(files(obfFile)) +} +// 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 = [publishableDevJar] + if (!noPublishedSources) secondaryArtifacts += [sourcesJar] + if (apiPackage) secondaryArtifacts += [apiJar] + return secondaryArtifacts +} diff --git a/dependencies.gradle b/dependencies.gradle new file mode 100644 index 00000000..ce8ebf3c --- /dev/null +++ b/dependencies.gradle @@ -0,0 +1,38 @@ +/* + * Add your dependencies here. Supported configurations: + * - api("group:name:version:classifier"): if you use the types from this dependency in the public API of this mod + * Available at runtime and compiletime for mods depending on this mod + * - implementation("g:n:v:c"): if you need this for internal implementation details of the mod, but none of it is visible via the public API + * Available at runtime but not compiletime for mods depending on this mod + * - compileOnly("g:n:v:c"): if the mod you're building doesn't need this dependency during runtime at all, e.g. for optional mods + * Not available at all for mods depending on this mod, only visible at compiletime for this mod + * - compileOnlyApi("g:n:v:c"): like compileOnly, but also visible at compiletime for mods depending on this mod + * Available at compiletime but not runtime for mods depending on this mod + * - runtimeOnlyNonPublishable("g:n:v:c"): if you want to include a mod in this mod's runClient/runServer runs, but not publish it as a dependency + * Not available at all for mods depending on this mod, only visible at runtime for this mod + * - devOnlyNonPublishable("g:n:v:c"): a combination of runtimeOnlyNonPublishable and compileOnly for dependencies present at both compiletime and runtime, + * but not published as Maven dependencies - useful for RFG-deobfuscated dependencies or local testing + * - runtimeOnly("g:n:v:c"): if you don't need this at compile time, but want it to be present at runtime + * Available at runtime for mods depending on this mod + * - annotationProcessor("g:n:v:c"): mostly for java compiler plugins, if you know you need this, use it, otherwise don't worry + * - testCONFIG("g:n:v:c") - replace CONFIG by one of the above (except api), same as above but for the test sources instead of main + * + * - shadowImplementation("g:n:v:c"): effectively the same as API, but the dependency is included in your jar under a renamed package name + * Requires you to enable usesShadowedDependencies in gradle.properties + * + * - compile("g:n:v:c"): deprecated, replace with "api" (works like the old "compile") or "implementation" (can be more efficient) + * + * You can exclude transitive dependencies (dependencies of the chosen dependency) by appending { transitive = false } if needed, + * but use this sparingly as it can break using your mod as another mod's dependency if you're not careful. + * + * To depend on obfuscated jars you can use `devOnlyNonPublishable(rfg.deobf("dep:spec:1.2.3"))` to fetch an obfuscated jar from maven, + * or `devOnlyNonPublishable(rfg.deobf(project.files("libs/my-mod-jar.jar")))` to use a file. + * + * Gradle names for some of the configuration can be misleading, compileOnlyApi and runtimeOnly both get published as dependencies in Maven, but compileOnly does not. + * The buildscript adds runtimeOnlyNonPublishable to also have a runtime dependency that's not published. + * + * For more details, see https://docs.gradle.org/8.0.1/userguide/java_library_plugin.html#sec:java_library_configurations_graph + */ +dependencies { + compileOnly(deobf("https://www.curseforge.com/api/v1/mods/245755/files/2559125/download")) +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..60a48176 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,143 @@ +modName = SignPost + +# This is a case-sensitive string to identify your mod. Convention is to use lower case. +modId = signpost + +modGroup = gollorum.signpost + +# 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 + +# Enables using modern java syntax (up to version 17) via Jabel, while still targetting JVM 8. +# See https://github.com/bsideup/jabel for details on how this works. +enableModernJavaSyntax = true + +# Enables injecting missing generics into the decompiled source code for a better coding experience +# Turns most publically visible List, Map, etc. into proper List, Map types +enableGenericInjection = false + +# Generate a class with String fields for the mod id, name, version and group name named with the fields below +generateGradleTokenClass = gollorum.signpost.Tags +gradleTokenModId = MODID +gradleTokenModName = MODNAME +gradleTokenVersion = VERSION +gradleTokenGroupName = GROUPNAME +# [DEPRECATED] +# Multiple source files can be defined here by providing a comma-seperated list: Class1.java,Class2.java,Class3.java +# public static final String VERSION = "GRADLETOKEN_VERSION"; +# The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's +# version in @Mod([...], version = VERSION, [...]) +# Leave these properties empty to skip individual token replacements +replaceGradleTokenInFile = + +# 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/ +# There can be multiple files in a comma-separated list. +# Example value: mymodid_at.cfg,nei_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 +# If disabled, won't remove unused classes from shaded dependencies. Some libraries use reflection to access +# their own classes, making the minimization unreliable. +minimizeShadowedDependencies = true +# If disabled, won't rename the shadowed classes. +relocateShadowedDependencies = true + +# Adds the GTNH maven, CurseMaven, IC2/Player maven, and some more well-known 1.7.10 repositories +includeWellKnownRepositories = true + +# 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 + +# Override the IDEA build type. Valid value is "" (leave blank, do not override), "idea" (force use native IDEA build), "gradle" +# (force use delegated build). +# This is meant to be set in $HOME/.gradle/gradle.properties. +# e.g. add "systemProp.org.gradle.project.ideaOverrideBuildType=idea" will override the build type to be always native build. +# WARNING: If you do use this option, it will overwrite whatever you have in your existing projects. This might not be what you want! +# Usually there is no need to uncomment this here as other developers do not necessarily use the same build type as you. +# ideaOverrideBuildType = idea diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..ccebba77 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..37aef8d3 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..79a61d42 --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# 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 "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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 +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 00000000..09bbb514 --- /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 00000000..c8843905 --- /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 00000000..e3343972 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,28 @@ + +pluginManagement { + repositories { + maven { + // RetroFuturaGradle + name "GTNH Maven" + url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + allowInsecureProtocol = true + mavenContent { + includeGroup("com.gtnewhorizons.retrofuturagradle") + } + } + gradlePluginPortal() + mavenCentral() + mavenLocal() + } +} + +plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' // Provides java toolchains +} + +blowdryerSetup { + repoSubfolder 'gtnhShared' + github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.2') + //devLocal '.' // Use this when testing config updates locally +} diff --git a/src/main/java/gollorum/signpost/BlockHandler.java b/src/main/java/gollorum/signpost/BlockHandler.java index e08e8fc0..8653389e 100644 --- a/src/main/java/gollorum/signpost/BlockHandler.java +++ b/src/main/java/gollorum/signpost/BlockHandler.java @@ -1,11 +1,10 @@ package gollorum.signpost; -import cpw.mods.fml.common.registry.GameRegistry; -import gollorum.signpost.blocks.*; -import gollorum.signpost.blocks.BigPostPost.BigPostType; -import gollorum.signpost.blocks.PostPost.PostType; -import gollorum.signpost.management.ClientConfigStorage; -import gollorum.signpost.util.collections.CollectionUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; @@ -13,10 +12,16 @@ import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; +import cpw.mods.fml.common.registry.GameRegistry; +import gollorum.signpost.blocks.BaseModelPost; +import gollorum.signpost.blocks.BasePost; +import gollorum.signpost.blocks.BigPostPost; +import gollorum.signpost.blocks.BigPostPost.BigPostType; +import gollorum.signpost.blocks.ItemBlockWithMetaFacing; +import gollorum.signpost.blocks.PostPost; +import gollorum.signpost.blocks.PostPost.PostType; +import gollorum.signpost.management.ClientConfigStorage; +import gollorum.signpost.util.collections.CollectionUtils; public class BlockHandler { @@ -31,7 +36,8 @@ public class BlockHandler { public PostPost post_big_oak = new PostPost(PostType.BIGOAK); public PostPost post_iron = new PostPost(PostType.IRON); public PostPost post_stone = new PostPost(PostType.STONE); - public PostPost[] posts = {post_oak, post_spruce, post_birch, post_jungle, post_acacia, post_big_oak, post_iron, post_stone}; + public PostPost[] posts = { post_oak, post_spruce, post_birch, post_jungle, post_acacia, post_big_oak, post_iron, + post_stone }; public BigPostPost bigpost_oak = new BigPostPost(BigPostType.OAK); public BigPostPost bigpost_spruce = new BigPostPost(BigPostType.SPRUCE); @@ -41,24 +47,25 @@ public class BlockHandler { public BigPostPost bigpost_big_oak = new BigPostPost(BigPostType.BIGOAK); public BigPostPost bigpost_iron = new BigPostPost(BigPostType.IRON); public BigPostPost bigpost_stone = new BigPostPost(BigPostType.STONE); - public BigPostPost[] bigposts = {bigpost_oak, bigpost_spruce, bigpost_birch, bigpost_jungle, bigpost_acacia, bigpost_big_oak, bigpost_iron, bigpost_stone}; + public BigPostPost[] bigposts = { bigpost_oak, bigpost_spruce, bigpost_birch, bigpost_jungle, bigpost_acacia, + bigpost_big_oak, bigpost_iron, bigpost_stone }; - public List baseModelsForCrafting(){ + public List baseModelsForCrafting() { List allModels = Arrays.asList(basemodels); ArrayList allowedModels = new ArrayList<>(); - for (final String model : ClientConfigStorage.INSTANCE.getAllowedCraftingModels()){ + for (final String model : ClientConfigStorage.INSTANCE.getAllowedCraftingModels()) { BaseModelPost block = CollectionUtils.find(allModels, m -> m.type.name.equals(model)); - if(block != null) allowedModels.add(block); + if (block != null) allowedModels.add(block); } return allowedModels; } - public List baseModelsForVillages(){ + public List baseModelsForVillages() { List allModels = Arrays.asList(basemodels); ArrayList allowedModels = new ArrayList<>(); - for (final String model : ClientConfigStorage.INSTANCE.getAllowedVillageModels()){ + for (final String model : ClientConfigStorage.INSTANCE.getAllowedVillageModels()) { BaseModelPost block = CollectionUtils.find(allModels, m -> m.type.name.equals(model)); - if(block != null) allowedModels.add(block); + if (block != null) allowedModels.add(block); } return allowedModels; } @@ -66,7 +73,8 @@ public List baseModelsForVillages(){ public void registerBlocks() { GameRegistry.registerBlock(base, "SignpostBase"); for (BaseModelPost basemodel : basemodels) { - GameRegistry.registerBlock(basemodel, ItemBlockWithMetaFacing.class, "blockbasemodel" + basemodel.type.getID()); + GameRegistry + .registerBlock(basemodel, ItemBlockWithMetaFacing.class, "blockbasemodel" + basemodel.type.getID()); } for (PostPost now : posts) { GameRegistry.registerBlock(now, "SignpostPost" + now.type.name()); @@ -91,21 +99,26 @@ private void waystoneRecipe() { Item[] outputsToRemove = new Item[basemodels.length + 1]; for (int i = 0; i < basemodels.length; i++) outputsToRemove[i] = Item.getItemFromBlock(basemodels[i]); outputsToRemove[outputsToRemove.length - 1] = Item.getItemFromBlock(base); - for (Object now : CraftingManager.getInstance().getRecipeList()) { + for (Object now : CraftingManager.getInstance() + .getRecipeList()) { if (!(now instanceof IRecipe)) continue; ItemStack output = ((IRecipe) now).getRecipeOutput(); if (output == null) continue; Item item = output.getItem(); if (item == null) continue; - for (Item item2 : outputsToRemove) - if (item.equals(item2)) { - toDelete.add(now); - break; - } + for (Item item2 : outputsToRemove) if (item.equals(item2)) { + toDelete.add(now); + break; + } } - CraftingManager.getInstance().getRecipeList().removeAll(toDelete); + CraftingManager.getInstance() + .getRecipeList() + .removeAll(toDelete); - if (ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canCraft && !ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + if (ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canCraft + && !ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + // spotless:off + switch (ClientConfigStorage.INSTANCE.getWaysRec()) { case EXPENSIVE: GameRegistry.addRecipe(new ItemStack(base, 1), @@ -134,6 +147,9 @@ private void waystoneRecipe() { 'P', Items.ender_pearl); break; } + + // spotless:on + List allowedModels = baseModelsForCrafting(); if (allowedModels.size() > 0) { GameRegistry.addShapelessRecipe(new ItemStack(allowedModels.get(0), 1), base); @@ -147,16 +163,26 @@ private void waystoneRecipe() { private void postRecipe(PostPost post) { Object toDelete = null; - for (Object now : CraftingManager.getInstance().getRecipeList()) { - if (now == null || !(now instanceof IRecipe) || ((IRecipe) now).getRecipeOutput() == null || ((IRecipe) now).getRecipeOutput().getItem() == null) { + for (Object now : CraftingManager.getInstance() + .getRecipeList()) { + if (now == null || !(now instanceof IRecipe) + || ((IRecipe) now).getRecipeOutput() == null + || ((IRecipe) now).getRecipeOutput() + .getItem() == null) { continue; } - if (((IRecipe) now).getRecipeOutput().getItem().equals(Item.getItemFromBlock(post))) { + if (((IRecipe) now).getRecipeOutput() + .getItem() + .equals(Item.getItemFromBlock(post))) { toDelete = now; break; } } - CraftingManager.getInstance().getRecipeList().remove(toDelete); + CraftingManager.getInstance() + .getRecipeList() + .remove(toDelete); + + // spotless:off if (ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().canCraft) { switch (ClientConfigStorage.INSTANCE.getSignRec()) { @@ -190,20 +216,32 @@ private void postRecipe(PostPost post) { break; } } + + // spotless:on } private void bigPostRecipe(BigPostPost post) { Object toDelete = null; - for (Object now : CraftingManager.getInstance().getRecipeList()) { - if (now == null || !(now instanceof IRecipe) || ((IRecipe) now).getRecipeOutput() == null || ((IRecipe) now).getRecipeOutput().getItem() == null) { + for (Object now : CraftingManager.getInstance() + .getRecipeList()) { + if (now == null || !(now instanceof IRecipe) + || ((IRecipe) now).getRecipeOutput() == null + || ((IRecipe) now).getRecipeOutput() + .getItem() == null) { continue; } - if (((IRecipe) now).getRecipeOutput().getItem().equals(Item.getItemFromBlock(post))) { + if (((IRecipe) now).getRecipeOutput() + .getItem() + .equals(Item.getItemFromBlock(post))) { toDelete = now; break; } } - CraftingManager.getInstance().getRecipeList().remove(toDelete); + CraftingManager.getInstance() + .getRecipeList() + .remove(toDelete); + + // spotless:off if (ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().canCraft) { switch (ClientConfigStorage.INSTANCE.getSignRec()) { @@ -237,5 +275,7 @@ private void bigPostRecipe(BigPostPost post) { break; } } + + // spotless:on } } diff --git a/src/main/java/gollorum/signpost/BlockHandlerClient.java b/src/main/java/gollorum/signpost/BlockHandlerClient.java index f2350b87..8ae1406a 100644 --- a/src/main/java/gollorum/signpost/BlockHandlerClient.java +++ b/src/main/java/gollorum/signpost/BlockHandlerClient.java @@ -1,5 +1,8 @@ package gollorum.signpost; +import net.minecraft.item.Item; +import net.minecraftforge.client.MinecraftForgeClient; + import cpw.mods.fml.client.registry.ClientRegistry; import gollorum.signpost.blocks.BaseModelPost; import gollorum.signpost.blocks.BigPostPost; @@ -11,32 +14,33 @@ import gollorum.signpost.render.BlockItemRenderer; import gollorum.signpost.render.PostRenderer; import gollorum.signpost.util.render.ModelRenderer; -import net.minecraft.item.Item; -import net.minecraftforge.client.MinecraftForgeClient; public class BlockHandlerClient extends BlockHandler { - public void registerRenders(){ - ClientRegistry.bindTileEntitySpecialRenderer(PostPostTile.class, new PostRenderer()); - for(PostPost now: posts){ - PostPostTile tile = new PostPostTile(now.type); - tile.isItem = true; - tile.blockType = now; - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(now), new BlockItemRenderer(tile, new PostRenderer())); - } + public void registerRenders() { + ClientRegistry.bindTileEntitySpecialRenderer(PostPostTile.class, new PostRenderer()); + for (PostPost now : posts) { + PostPostTile tile = new PostPostTile(now.type); + tile.isItem = true; + tile.blockType = now; + MinecraftForgeClient + .registerItemRenderer(Item.getItemFromBlock(now), new BlockItemRenderer(tile, new PostRenderer())); + } + + ClientRegistry.bindTileEntitySpecialRenderer(BigPostPostTile.class, new BigPostRenderer()); + for (BigPostPost now : bigposts) { + BigPostPostTile tile = new BigPostPostTile(now.type); + tile.isItem = true; + tile.blockType = now; + MinecraftForgeClient + .registerItemRenderer(Item.getItemFromBlock(now), new BlockItemRenderer(tile, new PostRenderer())); + } - ClientRegistry.bindTileEntitySpecialRenderer(BigPostPostTile.class, new BigPostRenderer()); - for(BigPostPost now: bigposts){ - BigPostPostTile tile = new BigPostPostTile(now.type); - tile.isItem = true; - tile.blockType = now; - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(now), new BlockItemRenderer(tile, new PostRenderer())); - } - - ClientRegistry.bindTileEntitySpecialRenderer(BaseModelPostTile.class, new ModelRenderer()); - for(BaseModelPost now: basemodels){ - BaseModelPostTile tile = new BaseModelPostTile(now.type); - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(now), new BlockItemRenderer(tile, new ModelRenderer())); - } - } + ClientRegistry.bindTileEntitySpecialRenderer(BaseModelPostTile.class, new ModelRenderer()); + for (BaseModelPost now : basemodels) { + BaseModelPostTile tile = new BaseModelPostTile(now.type); + MinecraftForgeClient + .registerItemRenderer(Item.getItemFromBlock(now), new BlockItemRenderer(tile, new ModelRenderer())); + } + } } diff --git a/src/main/java/gollorum/signpost/ClientProxy.java b/src/main/java/gollorum/signpost/ClientProxy.java index 08349d08..4981578b 100644 --- a/src/main/java/gollorum/signpost/ClientProxy.java +++ b/src/main/java/gollorum/signpost/ClientProxy.java @@ -5,64 +5,76 @@ import java.util.Collection; import java.util.LinkedList; -import cpw.mods.fml.client.FMLClientHandler; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.network.simpleimpl.MessageContext; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import cpw.mods.fml.client.FMLClientHandler; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; + public class ClientProxy extends CommonProxy { - public ClientProxy() { - blockHandler = new BlockHandlerClient(); - } + public ClientProxy() { + blockHandler = new BlockHandlerClient(); + } - @Override - public void init() { - super.init(); - registerRenderers(); - } + @Override + public void init() { + super.init(); + registerRenderers(); + } - private void registerRenderers() { - ((BlockHandlerClient) blockHandler).registerRenders(); - } + private void registerRenderers() { + ((BlockHandlerClient) blockHandler).registerRenders(); + } - @Override - public World getWorld(MessageContext ctx) { - return FMLClientHandler.instance().getWorldClient(); - } + @Override + public World getWorld(MessageContext ctx) { + return FMLClientHandler.instance() + .getWorldClient(); + } - @Override - public World getWorld(int dim) { - if (FMLCommonHandler.instance() != null && FMLCommonHandler.instance().getMinecraftServerInstance() != null - && FMLCommonHandler.instance().getMinecraftServerInstance().isSinglePlayer()) { - return super.getWorld(dim); - } else { - return FMLClientHandler.instance().getWorldClient(); - } - } + @Override + public World getWorld(int dim) { + if (FMLCommonHandler.instance() != null && FMLCommonHandler.instance() + .getMinecraftServerInstance() != null + && FMLCommonHandler.instance() + .getMinecraftServerInstance() + .isSinglePlayer()) { + return super.getWorld(dim); + } else { + return FMLClientHandler.instance() + .getWorldClient(); + } + } - @Override - public World[] getWorlds() { - return new World[] { FMLClientHandler.instance().getWorldClient() }; - } + @Override + public World[] getWorlds() { + return new World[] { FMLClientHandler.instance() + .getWorldClient() }; + } - @Override - public Collection getAllPlayers() { - LinkedList ret = new LinkedList(); - ret.add(FMLClientHandler.instance().getClientPlayerEntity()); - return ret; - } + @Override + public Collection getAllPlayers() { + LinkedList ret = new LinkedList(); + ret.add( + FMLClientHandler.instance() + .getClientPlayerEntity()); + return ret; + } - public InputStream getResourceInputStream(String location) { - try { - InputStream ret = FMLClientHandler.instance().getClient().getResourceManager() - .getResource(new ResourceLocation(location)).getInputStream(); - if (ret != null) { - return ret; - } - } catch (IOException e) {} - return super.getResourceInputStream(location); - } + public InputStream getResourceInputStream(String location) { + try { + InputStream ret = FMLClientHandler.instance() + .getClient() + .getResourceManager() + .getResource(new ResourceLocation(location)) + .getInputStream(); + if (ret != null) { + return ret; + } + } catch (IOException e) {} + return super.getResourceInputStream(location); + } } diff --git a/src/main/java/gollorum/signpost/CommonProxy.java b/src/main/java/gollorum/signpost/CommonProxy.java index 276ce0d2..e99533f0 100644 --- a/src/main/java/gollorum/signpost/CommonProxy.java +++ b/src/main/java/gollorum/signpost/CommonProxy.java @@ -1,5 +1,13 @@ package gollorum.signpost; +import java.io.InputStream; +import java.util.Collection; +import java.util.LinkedList; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; + import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.registry.GameRegistry; @@ -9,86 +17,85 @@ import gollorum.signpost.blocks.tiles.PostPostTile; import gollorum.signpost.network.NetworkHandler; import gollorum.signpost.worldGen.villages.VillageHandler; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; - -import java.io.InputStream; -import java.util.Collection; -import java.util.LinkedList; public class CommonProxy { - public BlockHandler blockHandler; - ItemHandler itemHandler = new ItemHandler(); - - public CommonProxy() { - blockHandler = new BlockHandler(); - } - - void preInit() { - } - - public void init() { - registerBlocksAndItems(); - registerHandlers(); - registerVillageCreation(); - } - - private void registerVillageCreation() { - VillageHandler.getInstance().register(); - } - - private void registerHandlers() { - NetworkHandler.register(); - SPEventHandler handler = SPEventHandler.INSTANCE; - MinecraftForge.EVENT_BUS.register(handler); - FMLCommonHandler.instance().bus().register(handler); - } - - private void registerBlocksAndItems() { - blockHandler.registerBlocks(); - registerTiles(); - itemHandler.registerItems(); - registerRecipes(); - } - - protected void registerTiles() { - GameRegistry.registerTileEntity(BasePostTile.class, "SignpostBaseTile"); - GameRegistry.registerTileEntity(PostPostTile.class, "SignpostPostTile"); - GameRegistry.registerTileEntity(BigPostPostTile.class, "SignpostBigPostTile"); - GameRegistry.registerTileEntity(BaseModelPostTile.class, "SignpostBaseModelPostTile"); - } - - protected void registerRecipes() { - blockHandler.registerRecipes(); - itemHandler.registerRecipes(); - } - - public World getWorld(MessageContext ctx) { - return ctx.getServerHandler().playerEntity.worldObj; - } - - public World getWorld(int dim) { - return FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(dim); - } - - public World[] getWorlds() { - return FMLCommonHandler.instance().getMinecraftServerInstance().worldServers; - } - - public Collection getAllPlayers() { - LinkedList ret = new LinkedList(); - for (Object now : FMLCommonHandler.instance().getMinecraftServerInstance() - .getConfigurationManager().playerEntityList) { - if (now instanceof EntityPlayer) { - ret.add((EntityPlayer) now); - } - } - return ret; - } - - public InputStream getResourceInputStream(String location) { - return getClass().getResourceAsStream(location); - } + public BlockHandler blockHandler; + ItemHandler itemHandler = new ItemHandler(); + + public CommonProxy() { + blockHandler = new BlockHandler(); + } + + void preInit() {} + + public void init() { + registerBlocksAndItems(); + registerHandlers(); + registerVillageCreation(); + } + + private void registerVillageCreation() { + VillageHandler.getInstance() + .register(); + } + + private void registerHandlers() { + NetworkHandler.register(); + SPEventHandler handler = SPEventHandler.INSTANCE; + MinecraftForge.EVENT_BUS.register(handler); + FMLCommonHandler.instance() + .bus() + .register(handler); + } + + private void registerBlocksAndItems() { + blockHandler.registerBlocks(); + registerTiles(); + itemHandler.registerItems(); + registerRecipes(); + } + + protected void registerTiles() { + GameRegistry.registerTileEntity(BasePostTile.class, "SignpostBaseTile"); + GameRegistry.registerTileEntity(PostPostTile.class, "SignpostPostTile"); + GameRegistry.registerTileEntity(BigPostPostTile.class, "SignpostBigPostTile"); + GameRegistry.registerTileEntity(BaseModelPostTile.class, "SignpostBaseModelPostTile"); + } + + protected void registerRecipes() { + blockHandler.registerRecipes(); + itemHandler.registerRecipes(); + } + + public World getWorld(MessageContext ctx) { + return ctx.getServerHandler().playerEntity.worldObj; + } + + public World getWorld(int dim) { + return FMLCommonHandler.instance() + .getMinecraftServerInstance() + .worldServerForDimension(dim); + } + + public World[] getWorlds() { + return FMLCommonHandler.instance() + .getMinecraftServerInstance().worldServers; + } + + public Collection getAllPlayers() { + LinkedList ret = new LinkedList(); + for (Object now : FMLCommonHandler.instance() + .getMinecraftServerInstance() + .getConfigurationManager().playerEntityList) { + if (now instanceof EntityPlayer) { + ret.add((EntityPlayer) now); + } + } + return ret; + } + + public InputStream getResourceInputStream(String location) { + return getClass().getResourceAsStream(location); + } } diff --git a/src/main/java/gollorum/signpost/ItemHandler.java b/src/main/java/gollorum/signpost/ItemHandler.java index 96c3d6a2..b0c8741f 100644 --- a/src/main/java/gollorum/signpost/ItemHandler.java +++ b/src/main/java/gollorum/signpost/ItemHandler.java @@ -1,52 +1,53 @@ package gollorum.signpost; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + import cpw.mods.fml.common.registry.GameRegistry; import gollorum.signpost.items.CalibratedPostWrench; import gollorum.signpost.items.PostBrush; import gollorum.signpost.items.PostWrench; import gollorum.signpost.management.ClientConfigStorage; import gollorum.signpost.management.ConfigHandler; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; public class ItemHandler { - public static PostWrench tool = new PostWrench(); - public static CalibratedPostWrench calibratedTool = new CalibratedPostWrench(); - public static PostBrush brush = new PostBrush(); - - public static void init(){ - tool = new PostWrench(); - } - - public static void registerItems(){ - GameRegistry.registerItem(tool, "SignpostTool"); - GameRegistry.registerItem(calibratedTool, "SignpostCalibratedTool"); - GameRegistry.registerItem(brush, "SignpostBrush"); - registerRecipes(); - } - - protected static void registerRecipes() { - if(ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().equals(ConfigHandler.SecurityLevel.ALL) || ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().equals(ConfigHandler.SecurityLevel.OWNERS)){ - GameRegistry.addRecipe(new ItemStack(tool), - "II", - "IS", - "S ", - 'I', Items.iron_ingot, - 'S', Items.stick); - GameRegistry.addShapelessRecipe(new ItemStack(calibratedTool), - tool, - Items.compass); - GameRegistry.addRecipe(new ItemStack(brush), - "W", - "I", - "S", - 'W', Item.getItemFromBlock(Blocks.wool), - 'I', Items.iron_ingot, - 'S', Items.stick); - } - } + public static PostWrench tool = new PostWrench(); + public static CalibratedPostWrench calibratedTool = new CalibratedPostWrench(); + public static PostBrush brush = new PostBrush(); + + public static void init() { + tool = new PostWrench(); + } + + public static void registerItems() { + GameRegistry.registerItem(tool, "SignpostTool"); + GameRegistry.registerItem(calibratedTool, "SignpostCalibratedTool"); + GameRegistry.registerItem(brush, "SignpostBrush"); + registerRecipes(); + } + + protected static void registerRecipes() { + if (ClientConfigStorage.INSTANCE.getSecurityLevelSignpost() + .equals(ConfigHandler.SecurityLevel.ALL) + || ClientConfigStorage.INSTANCE.getSecurityLevelSignpost() + .equals(ConfigHandler.SecurityLevel.OWNERS)) { + GameRegistry.addRecipe(new ItemStack(tool), "II", "IS", "S ", 'I', Items.iron_ingot, 'S', Items.stick); + GameRegistry.addShapelessRecipe(new ItemStack(calibratedTool), tool, Items.compass); + GameRegistry.addRecipe( + new ItemStack(brush), + "W", + "I", + "S", + 'W', + Item.getItemFromBlock(Blocks.wool), + 'I', + Items.iron_ingot, + 'S', + Items.stick); + } + } } diff --git a/src/main/java/gollorum/signpost/SPEventHandler.java b/src/main/java/gollorum/signpost/SPEventHandler.java index 9a2d3928..7a9b310a 100644 --- a/src/main/java/gollorum/signpost/SPEventHandler.java +++ b/src/main/java/gollorum/signpost/SPEventHandler.java @@ -1,5 +1,18 @@ package gollorum.signpost; +import java.util.*; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatComponentText; +import net.minecraftforge.event.entity.EntityEvent; +import net.minecraftforge.event.world.BlockEvent.BreakEvent; +import net.minecraftforge.event.world.BlockEvent.PlaceEvent; +import net.minecraftforge.event.world.WorldEvent; + import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; @@ -21,263 +34,280 @@ import gollorum.signpost.util.BoolRun; import gollorum.signpost.util.MyBlockPos; import gollorum.signpost.util.collections.CollectionUtils; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChatComponentText; -import net.minecraftforge.event.entity.EntityEvent; -import net.minecraftforge.event.world.BlockEvent.BreakEvent; -import net.minecraftforge.event.world.BlockEvent.PlaceEvent; -import net.minecraftforge.event.world.WorldEvent; - -import java.util.*; public class SPEventHandler { - private static Map serverTasks = new HashMap<>(); - private static Collection serverPredicatedTasks = new ArrayList<>(); + private static Map serverTasks = new HashMap<>(); + private static Collection serverPredicatedTasks = new ArrayList<>(); + + private static Map clientTasks = new HashMap<>(); + private static Collection clientPredicatedTasks = new ArrayList<>(); + + public static final SPEventHandler INSTANCE = new SPEventHandler(); + + private SPEventHandler() {} + + /** + * Schedules a task + * + * @param task + * The task to execute + * @param delay + * The delay in ticks (1s/20) + */ + public static void scheduleTask(Runnable task, int delay) { + if (FMLCommonHandler.instance() + .getEffectiveSide() + .equals(Side.SERVER)) { + serverTasks.put(task, delay); + } else { + clientTasks.put(task, delay); + } + } + + /** + * return true when done + */ + public static void scheduleTask(BoolRun task) { + if (FMLCommonHandler.instance() + .getEffectiveSide() + .equals(Side.SERVER)) { + serverPredicatedTasks.add(task); + } else { + clientPredicatedTasks.add(task); + } + } + + public static boolean cancelTask(BoolRun task) { + if (FMLCommonHandler.instance() + .getEffectiveSide() + .equals(Side.SERVER)) { + return serverPredicatedTasks.remove(task); + } else { + return clientPredicatedTasks.remove(task); + } + } + + @SubscribeEvent + public void onServerTick(TickEvent event) { + if (!(event instanceof TickEvent.ServerTickEvent)) { + return; + } + Map oldTasks = serverTasks; + serverTasks = new HashMap<>(); + serverTasks.putAll( + CollectionUtils.mutateOr( + oldTasks, + (task, delay) -> delay > 1, // condition + (task, delay) -> delay - 1, // mutation + (task, delay) -> task.run() // elseAction + )); + Collection oldPredicateTasks = serverPredicatedTasks; + serverPredicatedTasks = new HashSet<>(); + serverPredicatedTasks.addAll(CollectionUtils.where(oldPredicateTasks, boolRun -> !boolRun.run())); + } + + @SubscribeEvent + public void onClientTick(TickEvent event) { + if (!(event instanceof TickEvent.ClientTickEvent)) { + return; + } + Map oldTasks = clientTasks; + clientTasks = new HashMap<>(); + clientTasks.putAll( + CollectionUtils.mutateOr( + oldTasks, + (task, delay) -> delay > 1, // condition + (task, delay) -> delay - 1, // mutation + (task, delay) -> task.run() // elseAction + )); + Collection oldPredicateTasks = clientPredicatedTasks; + clientPredicatedTasks = new HashSet<>(); + clientPredicatedTasks.addAll(CollectionUtils.where(oldPredicateTasks, boolRun -> !boolRun.run())); + } - private static Map clientTasks = new HashMap<>(); - private static Collection clientPredicatedTasks = new ArrayList<>(); - - public static final SPEventHandler INSTANCE = new SPEventHandler(); - private SPEventHandler(){} + // ServerSide + @SubscribeEvent + public void loggedIn(PlayerLoggedInEvent event) { + if (event.player instanceof EntityPlayerMP) { + NetworkHandler.netWrap.sendTo(new InitPlayerResponseMessage(), (EntityPlayerMP) event.player); + NetworkHandler.netWrap.sendTo(new SendAllPostBasesMessage(), (EntityPlayerMP) event.player); + NetworkHandler.netWrap.sendTo(new SendAllBigPostBasesMessage(), (EntityPlayerMP) event.player); + } + } - /** - * Schedules a task - * - * @param task - * The task to execute - * @param delay - * The delay in ticks (1s/20) - */ - public static void scheduleTask(Runnable task, int delay) { - if(FMLCommonHandler.instance().getEffectiveSide().equals(Side.SERVER)){ - serverTasks.put(task, delay); - }else{ - clientTasks.put(task, delay); - } - } + @SubscribeEvent + public void entConst(EntityEvent.EntityConstructing event) { + if (event.entity instanceof EntityPlayerMP) { + event.entity.registerExtendedProperties("KnownWaystones", new PlayerStore()); + } + } - /** - * return true when done - */ - public static void scheduleTask(BoolRun task){ - if(FMLCommonHandler.instance().getEffectiveSide().equals(Side.SERVER)){ - serverPredicatedTasks.add(task); - }else{ - clientPredicatedTasks.add(task); - } - } - - public static boolean cancelTask(BoolRun task){ - if(FMLCommonHandler.instance().getEffectiveSide().equals(Side.SERVER)){ - return serverPredicatedTasks.remove(task); - }else{ - return clientPredicatedTasks.remove(task); - } - } - - @SubscribeEvent - public void onServerTick(TickEvent event) { - if (!(event instanceof TickEvent.ServerTickEvent)) { - return; - } - Map oldTasks = serverTasks; - serverTasks = new HashMap<>(); - serverTasks.putAll(CollectionUtils.mutateOr( - oldTasks, - (task, delay) -> delay > 1, // condition - (task, delay) -> delay - 1, // mutation - (task, delay) -> task.run() // elseAction - )); - Collection oldPredicateTasks = serverPredicatedTasks; - serverPredicatedTasks = new HashSet<>(); - serverPredicatedTasks.addAll(CollectionUtils.where(oldPredicateTasks, boolRun -> !boolRun.run())); - } + @SubscribeEvent + public void onLoad(WorldEvent.Load event) { + if (!event.world.isRemote) { + WorldSigns.worldSigns(event.world); + } + } - @SubscribeEvent - public void onClientTick(TickEvent event) { - if (!(event instanceof TickEvent.ClientTickEvent)) { - return; - } - Map oldTasks = clientTasks; - clientTasks = new HashMap<>(); - clientTasks.putAll(CollectionUtils.mutateOr( - oldTasks, - (task, delay) -> delay > 1, // condition - (task, delay) -> delay - 1, // mutation - (task, delay) -> task.run() // elseAction - )); - Collection oldPredicateTasks = clientPredicatedTasks; - clientPredicatedTasks = new HashSet<>(); - clientPredicatedTasks.addAll(CollectionUtils.where(oldPredicateTasks, boolRun -> !boolRun.run())); - } + @SubscribeEvent + public void onSave(WorldEvent.Save event) { + if (!event.world.isRemote) { + WorldSigns.worldSigns(event.world); + } + } - // ServerSide - @SubscribeEvent - public void loggedIn(PlayerLoggedInEvent event) { - if (event.player instanceof EntityPlayerMP) { - NetworkHandler.netWrap.sendTo(new InitPlayerResponseMessage(), (EntityPlayerMP) event.player); - NetworkHandler.netWrap.sendTo(new SendAllPostBasesMessage(), (EntityPlayerMP) event.player); - NetworkHandler.netWrap.sendTo(new SendAllBigPostBasesMessage(), (EntityPlayerMP) event.player); - } - } + @SubscribeEvent + public void oBlockPlace(PlaceEvent event) { + MyBlockPos blockPos = new MyBlockPos(event.x, event.y, event.z, event.player.dimension); + if (!(event.player instanceof EntityPlayerMP)) { + if (event.block instanceof BasePost) { + BasePost.placeClient(event.world, blockPos, event.player); + } else if (event.block instanceof BaseModelPost) { + BaseModelPost.placeClient(event.world, blockPos, event.player); + } else if (event.block instanceof SuperPostPost) { + SuperPostPost.placeClient(event.world, blockPos, event.player); + } + return; + } + EntityPlayerMP player = (EntityPlayerMP) event.player; + if (event.block instanceof BasePost) { + BasePostTile tile = BasePost.getWaystoneRootTile(event.world, event.x, event.y, event.z); + if (!(ClientConfigStorage.INSTANCE.getSecurityLevelWaystone() + .canPlace(player) && checkWaystoneCount(player))) { + tile.onBlockDestroy(blockPos); + event.setCanceled(true); + } else { + BasePost.placeServer(event.world, blockPos, (EntityPlayerMP) event.player); + } + } else if (event.block instanceof BaseModelPost) { + BasePostTile tile = BaseModelPost.getWaystoneRootTile(event.world, event.x, event.y, event.z); + if (!(ClientConfigStorage.INSTANCE.getSecurityLevelWaystone() + .canPlace(player) && checkWaystoneCount(player))) { + tile.onBlockDestroy(blockPos); + event.setCanceled(true); + } else { + BaseModelPost.placeServer(event.world, blockPos, (EntityPlayerMP) event.player); + } + } else if (event.block instanceof SuperPostPost) { + SuperPostPostTile tile = SuperPostPost.getSuperTile(event.world, event.x, event.y, event.z); + if (!(ClientConfigStorage.INSTANCE.getSecurityLevelSignpost() + .canPlace(player) && checkSignpostCount(player))) { + tile.onBlockDestroy(blockPos); + event.setCanceled(true); + } else { + SuperPostPost.placeServer(event.world, blockPos, (EntityPlayerMP) event.player); + } + } + } - @SubscribeEvent - public void entConst(EntityEvent.EntityConstructing event) { - if (event.entity instanceof EntityPlayerMP) { - event.entity.registerExtendedProperties("KnownWaystones", new PlayerStore()); - } - } - - @SubscribeEvent - public void onLoad(WorldEvent.Load event) { - if(!event.world.isRemote) { - WorldSigns.worldSigns(event.world); - } - } + public boolean checkWaystoneCount(EntityPlayerMP player) { + PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()); + int remaining = restrictions.remainingWaystones; + if (remaining == 0) { + player.addChatMessage(new ChatComponentText("You are not allowed to place more waystones")); + return false; + } + if (remaining > 0) restrictions.remainingWaystones--; + return true; + } - @SubscribeEvent - public void onSave(WorldEvent.Save event) { - if(!event.world.isRemote) { - WorldSigns.worldSigns(event.world); - } - } - - @SubscribeEvent - public void oBlockPlace(PlaceEvent event){ - MyBlockPos blockPos = new MyBlockPos(event.x, event.y, event.z, event.player.dimension); - if(!(event.player instanceof EntityPlayerMP)){ - if(event.block instanceof BasePost){ - BasePost.placeClient(event.world, blockPos, event.player); - }else if(event.block instanceof BaseModelPost){ - BaseModelPost.placeClient(event.world, blockPos, event.player); - }else if(event.block instanceof SuperPostPost){ - SuperPostPost.placeClient(event.world, blockPos, event.player); - } - return; - } - EntityPlayerMP player = (EntityPlayerMP)event.player; - if(event.block instanceof BasePost){ - BasePostTile tile = BasePost.getWaystoneRootTile(event.world, event.x, event.y, event.z); - if(!(ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canPlace(player) && checkWaystoneCount(player))){ - tile.onBlockDestroy(blockPos); - event.setCanceled(true); - }else{ - BasePost.placeServer(event.world, blockPos, (EntityPlayerMP) event.player); - } - }else if(event.block instanceof BaseModelPost){ - BasePostTile tile = BaseModelPost.getWaystoneRootTile(event.world, event.x, event.y, event.z); - if(!(ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canPlace(player) && checkWaystoneCount(player))){ - tile.onBlockDestroy(blockPos); - event.setCanceled(true); - }else{ - BaseModelPost.placeServer(event.world, blockPos, (EntityPlayerMP) event.player); - } - }else if(event.block instanceof SuperPostPost){ - SuperPostPostTile tile = SuperPostPost.getSuperTile(event.world, event.x, event.y, event.z); - if(!(ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().canPlace(player) && checkSignpostCount(player))){ - tile.onBlockDestroy(blockPos); - event.setCanceled(true); - }else{ - SuperPostPost.placeServer(event.world, blockPos, (EntityPlayerMP) event.player); - } - } - } + public void updateWaystoneCount(WaystoneContainer tile) { + if (tile == null || tile.getBaseInfo() == null) { + return; + } + UUID owner = tile.getBaseInfo().owner; + if (owner == null) { + return; + } + PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(owner); + if (restrictions.remainingWaystones >= 0) { + restrictions.remainingWaystones++; + } + } - public boolean checkWaystoneCount(EntityPlayerMP player){ - PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()); - int remaining = restrictions.remainingWaystones; - if(remaining == 0){ - player.addChatMessage(new ChatComponentText("You are not allowed to place more waystones")); - return false; - } - if(remaining > 0) restrictions.remainingWaystones--; - return true; - } - - public void updateWaystoneCount(WaystoneContainer tile){ - if(tile == null || tile.getBaseInfo() == null){ - return; - } - UUID owner = tile.getBaseInfo().owner; - if(owner == null){ - return; - } - PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(owner); - if(restrictions.remainingWaystones >= 0){ - restrictions.remainingWaystones++; - } - } + private boolean checkSignpostCount(EntityPlayerMP player) { + PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()); + int remaining = restrictions.remainingSignposts; + if (remaining == 0) { + player.addChatMessage(new ChatComponentText("You are not allowed to place more signposts")); + return false; + } + if (remaining > 0) restrictions.remainingSignposts--; + return true; + } - private boolean checkSignpostCount(EntityPlayerMP player){ - PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()); - int remaining = restrictions.remainingSignposts; - if(remaining == 0){ - player.addChatMessage(new ChatComponentText("You are not allowed to place more signposts")); - return false; - } - if(remaining > 0) restrictions.remainingSignposts--; - return true; - } - - private void updateSignpostCount(SuperPostPostTile tile){ - if(tile == null || tile.owner == null){ - return; - } - PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(tile.owner); - if(restrictions.remainingSignposts >= 0){ - restrictions.remainingSignposts++; - } - } + private void updateSignpostCount(SuperPostPostTile tile) { + if (tile == null || tile.owner == null) { + return; + } + PlayerRestrictions restrictions = PostHandler.getPlayerKnownWaystonePositions(tile.owner); + if (restrictions.remainingSignposts >= 0) { + restrictions.remainingSignposts++; + } + } - @SubscribeEvent - public void onBlockBreak(BreakEvent event){ - try{ - TileEntity tile = event.world.getTileEntity(event.x, event.y, event.z); - if(tile instanceof SuperPostPostTile - && event.getPlayer().getHeldItem()!=null - && (event.getPlayer().getHeldItem().getItem() instanceof PostWrench - || event.getPlayer().getHeldItem().getItem() instanceof CalibratedPostWrench - || event.getPlayer().getHeldItem().getItem().equals(Items.wheat_seeds) - || event.getPlayer().getHeldItem().getItem().equals(Items.snowball) - || event.getPlayer().getHeldItem().getItem().equals(Item.getItemFromBlock(Blocks.vine)))){ - event.setCanceled(true); - ((SuperPostPost)tile.blockType).onBlockClicked(event.world, event.x, event.y, event.z, event.getPlayer()); - return; - } - if(!(event.getPlayer() instanceof EntityPlayerMP)){ - return; - } - EntityPlayerMP player = (EntityPlayerMP)event.getPlayer(); - if(event.block instanceof BasePost){ - BasePostTile t = BasePost.getWaystoneRootTile(event.world, event.x, event.y, event.z); - if(!ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canUse(player, ""+t.getBaseInfo().owner)){ - event.setCanceled(true); - }else{ - updateWaystoneCount(t); - t.onBlockDestroy(new MyBlockPos(event.x, event.y, event.z, player.dimension)); - } - }else if(event.block instanceof BaseModelPost){ - BasePostTile t = BaseModelPost.getWaystoneRootTile(event.world, event.x, event.y, event.z); - if(!ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canUse(player, ""+t.getBaseInfo().owner)){ - event.setCanceled(true); - }else{ - updateWaystoneCount(t); - t.onBlockDestroy(new MyBlockPos(event.x, event.y, event.z, player.dimension)); - } - }else if(event.block instanceof SuperPostPost){ - SuperPostPostTile t = SuperPostPost.getSuperTile(event.world, event.x, event.y, event.z); - if(!ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().canUse(player, ""+t.owner)){ - event.setCanceled(true); - }else{ - updateSignpostCount(t); - t.onBlockDestroy(new MyBlockPos(event.x, event.y, event.z, player.dimension)); - } - } - }catch(Exception e){} - } + @SubscribeEvent + public void onBlockBreak(BreakEvent event) { + try { + TileEntity tile = event.world.getTileEntity(event.x, event.y, event.z); + if (tile instanceof SuperPostPostTile && event.getPlayer() + .getHeldItem() != null + && (event.getPlayer() + .getHeldItem() + .getItem() instanceof PostWrench + || event.getPlayer() + .getHeldItem() + .getItem() instanceof CalibratedPostWrench + || event.getPlayer() + .getHeldItem() + .getItem() + .equals(Items.wheat_seeds) + || event.getPlayer() + .getHeldItem() + .getItem() + .equals(Items.snowball) + || event.getPlayer() + .getHeldItem() + .getItem() + .equals(Item.getItemFromBlock(Blocks.vine)))) { + event.setCanceled(true); + ((SuperPostPost) tile.blockType) + .onBlockClicked(event.world, event.x, event.y, event.z, event.getPlayer()); + return; + } + if (!(event.getPlayer() instanceof EntityPlayerMP)) { + return; + } + EntityPlayerMP player = (EntityPlayerMP) event.getPlayer(); + if (event.block instanceof BasePost) { + BasePostTile t = BasePost.getWaystoneRootTile(event.world, event.x, event.y, event.z); + if (!ClientConfigStorage.INSTANCE.getSecurityLevelWaystone() + .canUse(player, "" + t.getBaseInfo().owner)) { + event.setCanceled(true); + } else { + updateWaystoneCount(t); + t.onBlockDestroy(new MyBlockPos(event.x, event.y, event.z, player.dimension)); + } + } else if (event.block instanceof BaseModelPost) { + BasePostTile t = BaseModelPost.getWaystoneRootTile(event.world, event.x, event.y, event.z); + if (!ClientConfigStorage.INSTANCE.getSecurityLevelWaystone() + .canUse(player, "" + t.getBaseInfo().owner)) { + event.setCanceled(true); + } else { + updateWaystoneCount(t); + t.onBlockDestroy(new MyBlockPos(event.x, event.y, event.z, player.dimension)); + } + } else if (event.block instanceof SuperPostPost) { + SuperPostPostTile t = SuperPostPost.getSuperTile(event.world, event.x, event.y, event.z); + if (!ClientConfigStorage.INSTANCE.getSecurityLevelSignpost() + .canUse(player, "" + t.owner)) { + event.setCanceled(true); + } else { + updateSignpostCount(t); + t.onBlockDestroy(new MyBlockPos(event.x, event.y, event.z, player.dimension)); + } + } + } catch (Exception e) {} + } } diff --git a/src/main/java/gollorum/signpost/Signpost.java b/src/main/java/gollorum/signpost/Signpost.java index 64a59b89..9f09ddb4 100644 --- a/src/main/java/gollorum/signpost/Signpost.java +++ b/src/main/java/gollorum/signpost/Signpost.java @@ -1,5 +1,13 @@ package gollorum.signpost; +import java.io.File; + +import net.minecraft.command.ServerCommandManager; +import net.minecraft.nbt.NBTTagCompound; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; @@ -12,59 +20,47 @@ import gollorum.signpost.management.PostHandler; import gollorum.signpost.worldGen.villages.NameLibrary; import gollorum.signpost.worldGen.villages.VillageLibrary; -import net.minecraft.command.ServerCommandManager; -import net.minecraft.nbt.NBTTagCompound; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import java.io.File; +@Mod(modid = Tags.MODID, version = Tags.VERSION, name = Tags.MODNAME) +public class Signpost { + + @Instance + public static Signpost instance; + public static final int GuiBaseID = 0; + public static final int GuiPostID = 1; + public static final int GuiBigPostID = 2; + public static final int GuiPostBrushID = 3; + public static final int GuiPostRotationID = 4; + + public static NBTTagCompound saveFile; + public static final Logger LOG = LogManager.getLogger(Tags.MODID); + + public static File configFile; + public static File configFolder; -@Mod(modid = Signpost.MODID, version = Signpost.VERSION, name = "SignPost") -public class Signpost{ - - @Instance - public static Signpost instance; - public static final String MODID = "signpost"; - public static final String VERSION = "1.08.4"; - - public static final int GuiBaseID = 0; - public static final int GuiPostID = 1; - public static final int GuiBigPostID = 2; - public static final int GuiPostBrushID = 3; - public static final int GuiPostRotationID = 4; - - public static NBTTagCompound saveFile; - public static final Logger LOG = LogManager.getLogger(MODID); - - public static File configFile; - public static File configFolder; - - @SidedProxy(clientSide = "gollorum.signpost.ClientProxy", serverSide = "gollorum.signpost.CommonProxy") - public static CommonProxy proxy; - - @EventHandler - public void preinit(FMLPreInitializationEvent event) { - - configFolder = new File(event.getModConfigurationDirectory() + "/" + MODID); - configFolder.mkdirs(); - configFile = new File(configFolder.getPath(), MODID + ".cfg"); - ConfigHandler.init(configFile); - NameLibrary.init(configFolder.getPath()); - proxy.preInit(); - - proxy.init(); - - } - - @EventHandler - public void init(FMLInitializationEvent event) { - NetworkRegistry.INSTANCE.registerGuiHandler(this, new SignGuiHandler()); - } - - @EventHandler - public void postInit(FMLPostInitializationEvent event){ - ConfigHandler.postInit(); - } + @SidedProxy(clientSide = "gollorum.signpost.ClientProxy", serverSide = "gollorum.signpost.CommonProxy") + public static CommonProxy proxy; + + @EventHandler + public void preinit(FMLPreInitializationEvent event) { + configFolder = new File(event.getModConfigurationDirectory() + "/" + Tags.MODID); + configFolder.mkdirs(); + configFile = new File(configFolder.getPath(), Tags.MODID + ".cfg"); + ConfigHandler.init(configFile); + NameLibrary.init(configFolder.getPath()); + proxy.preInit(); + proxy.init(); + } + + @EventHandler + public void init(FMLInitializationEvent event) { + NetworkRegistry.INSTANCE.registerGuiHandler(this, new SignGuiHandler()); + } + + @EventHandler + public void postInit(FMLPostInitializationEvent event) { + ConfigHandler.postInit(); + } @EventHandler public void preServerStart(FMLServerAboutToStartEvent event) { @@ -73,23 +69,25 @@ public void preServerStart(FMLServerAboutToStartEvent event) { } @EventHandler - public void serverAboutToStart(FMLServerAboutToStartEvent e){ - PostHandler.init(); + public void serverAboutToStart(FMLServerAboutToStartEvent e) { + PostHandler.init(); + } + + @EventHandler + public void serverStarting(FMLServerStartingEvent e) { + registerCommands( + (ServerCommandManager) e.getServer() + .getCommandManager()); + ConfigHandler.init(configFile); + } + + private void registerCommands(ServerCommandManager manager) { + manager.registerCommand(new ConfirmTeleportCommand()); + manager.registerCommand(new GetWaystoneCount()); + manager.registerCommand(new GetSignpostCount()); + manager.registerCommand(new SetWaystoneCount()); + manager.registerCommand(new SetSignpostCount()); + manager.registerCommand(new DiscoverWaystone()); + manager.registerCommand(new ListAllWaystones()); } - - @EventHandler - public void serverStarting(FMLServerStartingEvent e) { - registerCommands((ServerCommandManager) e.getServer().getCommandManager()); - ConfigHandler.init(configFile); - } - - private void registerCommands(ServerCommandManager manager) { - manager.registerCommand(new ConfirmTeleportCommand()); - manager.registerCommand(new GetWaystoneCount()); - manager.registerCommand(new GetSignpostCount()); - manager.registerCommand(new SetWaystoneCount()); - manager.registerCommand(new SetSignpostCount()); - manager.registerCommand(new DiscoverWaystone()); - manager.registerCommand(new ListAllWaystones()); - } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/blocks/BaseModelPost.java b/src/main/java/gollorum/signpost/blocks/BaseModelPost.java index 83cdc226..010144c7 100644 --- a/src/main/java/gollorum/signpost/blocks/BaseModelPost.java +++ b/src/main/java/gollorum/signpost/blocks/BaseModelPost.java @@ -1,19 +1,7 @@ package gollorum.signpost.blocks; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import gollorum.signpost.SPEventHandler; -import gollorum.signpost.Signpost; -import gollorum.signpost.blocks.tiles.BaseModelPostTile; -import gollorum.signpost.event.UpdateWaystoneEvent; -import gollorum.signpost.management.ClientConfigStorage; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.network.NetworkHandler; -import gollorum.signpost.network.messages.BaseUpdateClientMessage; -import gollorum.signpost.network.messages.ChatMessage; -import gollorum.signpost.network.messages.OpenGuiMessage; -import gollorum.signpost.util.BaseInfo; -import gollorum.signpost.util.MyBlockPos; +import java.util.UUID; + import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; @@ -29,180 +17,221 @@ import net.minecraftforge.client.model.IModelCustom; import net.minecraftforge.common.MinecraftForge; -import java.util.UUID; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import gollorum.signpost.SPEventHandler; +import gollorum.signpost.Signpost; +import gollorum.signpost.Tags; +import gollorum.signpost.blocks.tiles.BaseModelPostTile; +import gollorum.signpost.event.UpdateWaystoneEvent; +import gollorum.signpost.management.ClientConfigStorage; +import gollorum.signpost.management.PostHandler; +import gollorum.signpost.network.NetworkHandler; +import gollorum.signpost.network.messages.BaseUpdateClientMessage; +import gollorum.signpost.network.messages.ChatMessage; +import gollorum.signpost.network.messages.OpenGuiMessage; +import gollorum.signpost.util.BaseInfo; +import gollorum.signpost.util.MyBlockPos; public class BaseModelPost extends BlockContainer { - public static final String[] allTypeNames = {"simple0", "simple1", "simple2", "detailed0", "detailed1", "aer", "dwarf", "ygnar"}; - public static final String[] allDefaultVillageTypeNames = {"simple0", "simple1", "simple2", "detailed0", "detailed1"}; - public static final int[] allTypeIds = {5, 6, 7, 0, 1, 2, 3, 4}; + public static final String[] allTypeNames = { "simple0", "simple1", "simple2", "detailed0", "detailed1", "aer", + "dwarf", "ygnar" }; + public static final String[] allDefaultVillageTypeNames = { "simple0", "simple1", "simple2", "detailed0", + "detailed1" }; + public static final int[] allTypeIds = { 5, 6, 7, 0, 1, 2, 3, 4 }; - public static enum ModelType { + public static enum ModelType { MODEL0(0), - MODEL1(1), - MODEL2(2), - MODEL3(3), - MODEL4(4), + MODEL1(1), + MODEL2(2), + MODEL3(3), + MODEL4(4), MODEL5(5), MODEL6(6), MODEL7(7); - private int ID; + private int ID; public final String name; - public IModelCustom MODEL; - public final ResourceLocation TEXTURE; + public IModelCustom MODEL; + public final ResourceLocation TEXTURE; - private ModelType(int i){ + private ModelType(int i) { this(allTypeIds[i], allTypeNames[i]); } - private ModelType(int ID, String name){ - this(ID, name, new ResourceLocation("signpost:models/block/"+name+".obj"), new ResourceLocation("signpost:textures/blocks/waystone.png")); + private ModelType(int ID, String name) { + this( + ID, + name, + new ResourceLocation("signpost:models/block/" + name + ".obj"), + new ResourceLocation("signpost:textures/blocks/waystone.png")); + } + + private ModelType(int ID, String name, final ResourceLocation model, ResourceLocation texture) { + this.ID = ID; + this.name = name; + MODEL = null; + if (FMLCommonHandler.instance() + .getEffectiveSide() + .equals(Side.CLIENT) + || FMLCommonHandler.instance() + .getMinecraftServerInstance() + .isSinglePlayer()) { + SPEventHandler.scheduleTask(() -> { + try { + MODEL = AdvancedModelLoader.loadModel(model); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + }); + } + TEXTURE = texture; + } + + @Override + public String toString() { + return name; } - private ModelType(int ID, String name, final ResourceLocation model, ResourceLocation texture){ - this.ID = ID; - this.name = name; - MODEL = null; - if(FMLCommonHandler.instance().getEffectiveSide().equals(Side.CLIENT) || FMLCommonHandler.instance().getMinecraftServerInstance().isSinglePlayer()){ - SPEventHandler.scheduleTask(() -> { - try{ - MODEL = AdvancedModelLoader.loadModel(model); - return true; - }catch(Exception e){ - e.printStackTrace(); - return false; - } - }); - } - TEXTURE = texture; - } - - @Override - public String toString(){ - return name; - } - - public int getID(){ - return ID; - } - - public static ModelType getByID(int ID){ - for(ModelType now: ModelType.values()){ - if(ID == now.ID){ + public int getID() { + return ID; + } + + public static ModelType getByID(int ID) { + for (ModelType now : ModelType.values()) { + if (ID == now.ID) { return now; } } return ModelType.MODEL1; } - public static ModelType getByName(String name){ - for(ModelType now: ModelType.values()){ - if(name.equals(now.name)){ + public static ModelType getByName(String name) { + for (ModelType now : ModelType.values()) { + if (name.equals(now.name)) { return now; } } return ModelType.MODEL1; } - } - - public final ModelType type; - - public BaseModelPost(int typ) { - super(Material.rock); - this.setHardness(2); - this.setResistance(100000); - setBlockName("SignpostBase"); - setCreativeTab(CreativeTabs.tabTransport); - setBlockTextureName(Signpost.MODID + ":base"); - type = ModelType.values()[typ]; - } - - public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack){ - int l = MathHelper.floor_double((double)(entity.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3; - world.setBlockMetadataWithNotify(x, y, z, l, 2); - } - - @Override - public boolean onBlockActivated(World worldIn, int x, int y, int z, EntityPlayer playerIn, int side, float hitX, float hitY, float hitZ) { - if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { - return false; - } - if (!worldIn.isRemote) { - BaseInfo ws = getWaystoneRootTile(worldIn, x, y, z).getBaseInfo(); - if(ws==null){ - ws = new BaseInfo(BasePost.generateName(), new MyBlockPos(x, y, z, playerIn.dimension), playerIn.getUniqueID()); - PostHandler.addWaystone(ws); - } - if (!playerIn.isSneaking()) { - if(!PostHandler.doesPlayerKnowNativeWaystone((EntityPlayerMP) playerIn, ws)){ - if (!ClientConfigStorage.INSTANCE.deactivateTeleportation()) { - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.discovered", "", ws.getName()), (EntityPlayerMP) playerIn); - } - PostHandler.addDiscovered(playerIn.getUniqueID(), ws); - } - } else { - if (!ClientConfigStorage.INSTANCE.deactivateTeleportation() - && ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canUse((EntityPlayerMP) playerIn, ""+ws.owner)) { - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), (EntityPlayerMP) playerIn); - } - } - } - return true; - } - - @Override - public TileEntity createNewTileEntity(World world, int p_149915_2_) { - return new BaseModelPostTile(type).setup(); - } - - public static BaseModelPostTile getWaystoneRootTile(World world, int x, int y, int z) { - TileEntity ret = world.getTileEntity(x, y, z); - if (ret instanceof BaseModelPostTile) { - return (BaseModelPostTile) ret; - } else { - return null; - } - } - - public static void placeServer(World world, MyBlockPos blockPos, EntityPlayerMP player) { - MyBlockPos telePos = new MyBlockPos(player); - BaseModelPostTile tile = getWaystoneRootTile(world, blockPos.x, blockPos.y, blockPos.z); - String name = BasePost.generateName(); - UUID owner = player.getUniqueID(); - BaseInfo ws; - if((ws = tile.getBaseInfo())==null){ - ws = new BaseInfo(name, blockPos, telePos, owner); - PostHandler.addWaystone(ws); - }else{ - ws.setAll(new BaseInfo(name, blockPos, telePos, owner)); - } - PostHandler.addDiscovered(player.getUniqueID(), ws); - NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); - MinecraftForge.EVENT_BUS.post(new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.PLACED, world, blockPos.x, blockPos.y, blockPos.z, name)); - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, blockPos.x, blockPos.y, blockPos.z), player); - } - - public static void placeClient(final World world, final MyBlockPos blockPos, final EntityPlayer player) {} - - public int getRenderType() { - return -1; - } - - public boolean renderAsNormalBlock() { - return false; - } - - public boolean isOpaqueCube() { - return false; - } - - public static BaseModelPost[] createAll() { - BaseModelPost[] ret = new BaseModelPost[ModelType.values().length]; - for(int i=0; i", ws.getName()), + (EntityPlayerMP) playerIn); + } + PostHandler.addDiscovered(playerIn.getUniqueID(), ws); + } + } else { + if (!ClientConfigStorage.INSTANCE.deactivateTeleportation() + && ClientConfigStorage.INSTANCE.getSecurityLevelWaystone() + .canUse((EntityPlayerMP) playerIn, "" + ws.owner)) { + NetworkHandler.netWrap + .sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), (EntityPlayerMP) playerIn); + } + } + } + return true; + } + + @Override + public TileEntity createNewTileEntity(World world, int p_149915_2_) { + return new BaseModelPostTile(type).setup(); + } + + public static BaseModelPostTile getWaystoneRootTile(World world, int x, int y, int z) { + TileEntity ret = world.getTileEntity(x, y, z); + if (ret instanceof BaseModelPostTile) { + return (BaseModelPostTile) ret; + } else { + return null; + } + } + + public static void placeServer(World world, MyBlockPos blockPos, EntityPlayerMP player) { + MyBlockPos telePos = new MyBlockPos(player); + BaseModelPostTile tile = getWaystoneRootTile(world, blockPos.x, blockPos.y, blockPos.z); + String name = BasePost.generateName(); + UUID owner = player.getUniqueID(); + BaseInfo ws; + if ((ws = tile.getBaseInfo()) == null) { + ws = new BaseInfo(name, blockPos, telePos, owner); + PostHandler.addWaystone(ws); + } else { + ws.setAll(new BaseInfo(name, blockPos, telePos, owner)); + } + PostHandler.addDiscovered(player.getUniqueID(), ws); + NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); + MinecraftForge.EVENT_BUS.post( + new UpdateWaystoneEvent( + UpdateWaystoneEvent.WaystoneEventType.PLACED, + world, + blockPos.x, + blockPos.y, + blockPos.z, + name)); + NetworkHandler.netWrap + .sendTo(new OpenGuiMessage(Signpost.GuiBaseID, blockPos.x, blockPos.y, blockPos.z), player); + } + + public static void placeClient(final World world, final MyBlockPos blockPos, final EntityPlayer player) {} + + public int getRenderType() { + return -1; + } + + public boolean renderAsNormalBlock() { + return false; + } + + public boolean isOpaqueCube() { + return false; + } + + public static BaseModelPost[] createAll() { + BaseModelPost[] ret = new BaseModelPost[ModelType.values().length]; + for (int i = 0; i < ModelType.values().length; i++) { + ret[i] = new BaseModelPost(i); + } + return ret; + } } diff --git a/src/main/java/gollorum/signpost/blocks/BasePost.java b/src/main/java/gollorum/signpost/blocks/BasePost.java index 4938c529..ad0d75d6 100644 --- a/src/main/java/gollorum/signpost/blocks/BasePost.java +++ b/src/main/java/gollorum/signpost/blocks/BasePost.java @@ -1,6 +1,18 @@ package gollorum.signpost.blocks; +import java.util.UUID; + +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; + import gollorum.signpost.Signpost; +import gollorum.signpost.Tags; import gollorum.signpost.blocks.tiles.BasePostTile; import gollorum.signpost.event.UpdateWaystoneEvent; import gollorum.signpost.management.ClientConfigStorage; @@ -11,123 +23,130 @@ import gollorum.signpost.network.messages.OpenGuiMessage; import gollorum.signpost.util.BaseInfo; import gollorum.signpost.util.MyBlockPos; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; - -import java.util.UUID; public class BasePost extends BlockContainer { - public BasePost() { - super(Material.rock); - this.setHardness(2); - this.setResistance(100000); - setBlockName("SignpostBase"); - setCreativeTab(CreativeTabs.tabTransport); - setBlockTextureName(Signpost.MODID + ":waystone"); - } + public BasePost() { + super(Material.rock); + this.setHardness(2); + this.setResistance(100000); + setBlockName("SignpostBase"); + setCreativeTab(CreativeTabs.tabTransport); + setBlockTextureName(Tags.MODID + ":waystone"); + } - @Override - public boolean onBlockActivated(World worldIn, int x, int y, int z, EntityPlayer playerIn, int side, float hitX, float hitY, float hitZ) { - if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { - return false; - } - if (!worldIn.isRemote) { - BaseInfo ws = getWaystoneRootTile(worldIn, x, y, z).getBaseInfo(); - if(ws==null){ - ws = new BaseInfo(generateName(), new MyBlockPos(x, y, z, playerIn.dimension), playerIn.getUniqueID()); - PostHandler.addWaystone(ws); - } - if (!playerIn.isSneaking()) { - if(!PostHandler.doesPlayerKnowNativeWaystone((EntityPlayerMP) playerIn, ws)){ - if (!ClientConfigStorage.INSTANCE.deactivateTeleportation()||ClientConfigStorage.INSTANCE.isDisableDiscovery()) { - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.discovered", "", ws.getName()), (EntityPlayerMP) playerIn); - } - PostHandler.addDiscovered(playerIn.getUniqueID(), ws); - } - } else { - if (!ClientConfigStorage.INSTANCE.deactivateTeleportation() - && ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canUse((EntityPlayerMP) playerIn, ""+ws.owner)) { - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), (EntityPlayerMP) playerIn); - } - } - } - return true; - } + @Override + public boolean onBlockActivated(World worldIn, int x, int y, int z, EntityPlayer playerIn, int side, float hitX, + float hitY, float hitZ) { + if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + return false; + } + if (!worldIn.isRemote) { + BaseInfo ws = getWaystoneRootTile(worldIn, x, y, z).getBaseInfo(); + if (ws == null) { + ws = new BaseInfo(generateName(), new MyBlockPos(x, y, z, playerIn.dimension), playerIn.getUniqueID()); + PostHandler.addWaystone(ws); + } + if (!playerIn.isSneaking()) { + if (!PostHandler.doesPlayerKnowNativeWaystone((EntityPlayerMP) playerIn, ws)) { + if (!ClientConfigStorage.INSTANCE.deactivateTeleportation() + || ClientConfigStorage.INSTANCE.isDisableDiscovery()) { + NetworkHandler.netWrap.sendTo( + new ChatMessage("signpost.discovered", "", ws.getName()), + (EntityPlayerMP) playerIn); + } + PostHandler.addDiscovered(playerIn.getUniqueID(), ws); + } + } else { + if (!ClientConfigStorage.INSTANCE.deactivateTeleportation() + && ClientConfigStorage.INSTANCE.getSecurityLevelWaystone() + .canUse((EntityPlayerMP) playerIn, "" + ws.owner)) { + NetworkHandler.netWrap + .sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), (EntityPlayerMP) playerIn); + } + } + } + return true; + } - @Override - public TileEntity createNewTileEntity(World world, int p_149915_2_) { - return new BasePostTile().setup(); - } + @Override + public TileEntity createNewTileEntity(World world, int p_149915_2_) { + return new BasePostTile().setup(); + } - public static BasePostTile getWaystoneRootTile(World world, int x, int y, int z) { - TileEntity ret = world.getTileEntity(x, y, z); - if (ret instanceof BasePostTile) { - return (BasePostTile) ret; - } else { - return null; - } - } + public static BasePostTile getWaystoneRootTile(World world, int x, int y, int z) { + TileEntity ret = world.getTileEntity(x, y, z); + if (ret instanceof BasePostTile) { + return (BasePostTile) ret; + } else { + return null; + } + } - public static String generateName() { - int i = 1; - String ret; - do { - ret = "Waystone " + (i++); - } while (PostHandler.getAllWaystones().nameTaken(ret)); - return ret; - } + public static String generateName() { + int i = 1; + String ret; + do { + ret = "Waystone " + (i++); + } while (PostHandler.getAllWaystones() + .nameTaken(ret)); + return ret; + } - public static void placeServer(World world, MyBlockPos pos, EntityPlayerMP player) { - BasePostTile tile = getWaystoneRootTile(world, pos.x, pos.y, pos.z); - String name = generateName(); - UUID owner = player != null ? player.getUniqueID() : null; - BaseInfo ws; - if((ws = tile.getBaseInfo())==null){ - ws = new BaseInfo(name, pos, owner); - PostHandler.addWaystone(ws); - }else{ - ws.setAll(new BaseInfo(name, pos, owner)); - } - PostHandler.addDiscovered(player.getUniqueID(), ws); - NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); - MinecraftForge.EVENT_BUS.post(new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.PLACED, world, pos.x, pos.y, pos.z, name)); - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, pos.x, pos.y, pos.z), player); - } + public static void placeServer(World world, MyBlockPos pos, EntityPlayerMP player) { + BasePostTile tile = getWaystoneRootTile(world, pos.x, pos.y, pos.z); + String name = generateName(); + UUID owner = player != null ? player.getUniqueID() : null; + BaseInfo ws; + if ((ws = tile.getBaseInfo()) == null) { + ws = new BaseInfo(name, pos, owner); + PostHandler.addWaystone(ws); + } else { + ws.setAll(new BaseInfo(name, pos, owner)); + } + PostHandler.addDiscovered(player.getUniqueID(), ws); + NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); + MinecraftForge.EVENT_BUS.post( + new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.PLACED, world, pos.x, pos.y, pos.z, name)); + NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, pos.x, pos.y, pos.z), player); + } - public static void placeClient(final World world, final MyBlockPos pos, final EntityPlayer player) { - BasePostTile tile = getWaystoneRootTile(world, pos.x, pos.y, pos.z); - if (tile != null && tile.getBaseInfo() == null) { - BaseInfo ws = PostHandler.getAllWaystones().getByPos(pos); + public static void placeClient(final World world, final MyBlockPos pos, final EntityPlayer player) { + BasePostTile tile = getWaystoneRootTile(world, pos.x, pos.y, pos.z); + if (tile != null && tile.getBaseInfo() == null) { + BaseInfo ws = PostHandler.getAllWaystones() + .getByPos(pos); if (ws == null) { - UUID owner = player != null ? player.getUniqueID() : null; - PostHandler.getAllWaystones().add(new BaseInfo("", pos, owner)); + UUID owner = player != null ? player.getUniqueID() : null; + PostHandler.getAllWaystones() + .add(new BaseInfo("", pos, owner)); } - } - } - - public static void generate(World world, MyBlockPos blockPos, MyBlockPos telePos){ - String name = generateName(); - generate(world, blockPos, telePos, name); - } - - public static void generate(World world, MyBlockPos blockPos, MyBlockPos telePos, String name){ - BasePostTile tile = getWaystoneRootTile(world, blockPos.x, blockPos.y, blockPos.z); - UUID owner = null; - BaseInfo ws; - if((ws = tile.getBaseInfo())==null){ - ws = new BaseInfo(name, blockPos, telePos, owner); - PostHandler.addWaystone(ws); - }else{ - ws.setAll(new BaseInfo(name, blockPos, telePos, owner)); - } - NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); - MinecraftForge.EVENT_BUS.post(new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.PLACED, world, blockPos.x, blockPos.y, blockPos.z, name)); - } + } + } + + public static void generate(World world, MyBlockPos blockPos, MyBlockPos telePos) { + String name = generateName(); + generate(world, blockPos, telePos, name); + } + + public static void generate(World world, MyBlockPos blockPos, MyBlockPos telePos, String name) { + BasePostTile tile = getWaystoneRootTile(world, blockPos.x, blockPos.y, blockPos.z); + UUID owner = null; + BaseInfo ws; + if ((ws = tile.getBaseInfo()) == null) { + ws = new BaseInfo(name, blockPos, telePos, owner); + PostHandler.addWaystone(ws); + } else { + ws.setAll(new BaseInfo(name, blockPos, telePos, owner)); + } + NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); + MinecraftForge.EVENT_BUS.post( + new UpdateWaystoneEvent( + UpdateWaystoneEvent.WaystoneEventType.PLACED, + world, + blockPos.x, + blockPos.y, + blockPos.z, + name)); + } } diff --git a/src/main/java/gollorum/signpost/blocks/BigPostPost.java b/src/main/java/gollorum/signpost/blocks/BigPostPost.java index 41a0476b..fdbd0d3e 100644 --- a/src/main/java/gollorum/signpost/blocks/BigPostPost.java +++ b/src/main/java/gollorum/signpost/blocks/BigPostPost.java @@ -1,6 +1,22 @@ package gollorum.signpost.blocks; +import java.util.function.Function; + +import net.minecraft.block.material.Material; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; + import gollorum.signpost.Signpost; +import gollorum.signpost.Tags; import gollorum.signpost.blocks.tiles.BigPostPostTile; import gollorum.signpost.blocks.tiles.SuperPostPostTile; import gollorum.signpost.management.ClientConfigStorage; @@ -15,361 +31,373 @@ import gollorum.signpost.util.math.tracking.Cuboid; import gollorum.signpost.util.math.tracking.DDDVector; import gollorum.signpost.util.math.tracking.Intersect; -import net.minecraft.block.material.Material; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; - -import java.util.function.Function; public class BigPostPost extends SuperPostPost { - public BigPostType type; - - public enum BigPostType{ - OAK( Material.wood, "bigsign_oak", "log_oak", Item.getItemFromBlock(Blocks.log), 0), - SPRUCE( Material.wood, "bigsign_spruce", "log_spruce", Item.getItemFromBlock(Blocks.log), 1), - BIRCH( Material.wood, "bigsign_birch", "log_birch", Item.getItemFromBlock(Blocks.log), 2), - JUNGLE( Material.wood, "bigsign_jungle", "log_jungle", Item.getItemFromBlock(Blocks.log), 3), - ACACIA( Material.wood, "bigsign_acacia", "log_acacia", Item.getItemFromBlock(Blocks.log2), 0), - BIGOAK( Material.wood, "bigsign_big_oak", "log_big_oak", Item.getItemFromBlock(Blocks.log2), 1), - IRON( Material.iron, "bigsign_iron", "iron_block", Items.iron_ingot, 0), - STONE( Material.rock, "bigsign_stone", "stone", Item.getItemFromBlock(Blocks.stone), 0); - public Material material; - public ResourceLocation texture; - public String blockTexture; - public String textureMain; - public ResourceLocation resLocMain; - public Item baseItem; - public int metadata; - - BigPostType(Material material, String texture, String textureMain, Item baseItem, int metadata) { - this.material = material; - this.texture = new ResourceLocation(Signpost.MODID + ":textures/blocks/"+texture+".png"); - this.blockTexture = texture; - this.textureMain = textureMain; - this.resLocMain = new ResourceLocation("minecraft:textures/blocks/"+textureMain+".png"); - this.baseItem = baseItem; - this.metadata = metadata; - } - } - - public enum BigHitTarget{BASE, POST, STONE} - - public static class BigHit{ - public BigHitTarget target; - public DDDVector pos; - public BigHit(BigHitTarget target, DDDVector pos){ - this.target = target; this.pos = pos; - } - } - - @Deprecated - public BigPostPost() { - super(Material.wood); - setBlockName("SignpostBigPost"); - setCreativeTab(CreativeTabs.tabTransport); - setBlockTextureName("minecraft:planks_oak"); - this.setHardness(2); - this.setResistance(100000); - float f = 15F / 32; - this.setBlockBounds(0.5f - f, 0.0F, 0.5F - f, 0.5F + f, 1, 0.5F + f); - } - - public BigPostPost(BigPostType type){ - super(type.material); - this.type = type; - setBlockName("SignpostBigPost"+type.toString()); - setCreativeTab(CreativeTabs.tabTransport); - setBlockTextureName(Signpost.MODID+":"+type.blockTexture); - this.setHardness(2); - this.setResistance(100000); - float f = 15F / 32; - this.setBlockBounds(0.5f - f, 0.0F, 0.5F - f, 0.5F + f, 1, 0.5F + f); - } - - @Override - public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) { - BigPostPostTile tile = new BigPostPostTile(type); - return tile; - } - - public static BigPostPostTile getWaystonePostTile(World world, int x, int y, int z) { - TileEntity ret = world.getTileEntity(x, y, z); - if (ret instanceof BigPostPostTile) { - return (BigPostPostTile) ret; - } else { - return null; - } - } - - @Override - public void clickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - BigBaseInfo tilebases = ((BigPostPostTile)superTile).getBases(); - if (hit.target == BigHitTarget.BASE) { - tilebases.sign.rot(-15, x, z); - } - } - - @Override - public void rightClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - BigBaseInfo tilebases = ((BigPostPostTile)superTile).getBases(); - if (hit.target == BigHitTarget.BASE) { - tilebases.sign.rot(15, x, z); - } - } - - @Override - public void shiftClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - BigBaseInfo tilebases = ((BigPostPostTile)superTile).getBases(); - if (hit.target == BigHitTarget.BASE) { - tilebases.sign.flip = !tilebases.sign.flip; - } - } - - @Override - public void clickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiPostBrushID, x, y, z), player); - } - - @Override - public void rightClickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - BigBaseInfo tilebases = ((BigPostPostTile)superTile).getBases(); - if(tilebases.awaitingPaint && tilebases.paintObject!=null){ - tilebases.paintObject = null; - tilebases.awaitingPaint = false; - }else{ - BigHit hit = (BigHit)hitObj; - tilebases.awaitingPaint = true; - if(hit.target == BigHitTarget.POST){ - tilebases.paintObject = tilebases; - } else if (hit.target == BigHitTarget.BASE) { - tilebases.paintObject = tilebases.sign; - } else{ - tilebases.paintObject = null; - tilebases.awaitingPaint = false; - } - } - } - - public void clickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - if(((BigHit)hitObj).target.equals(BigHitTarget.BASE)){ - Sign sign = ((BigPostPostTile)superTile).getBases().sign; - if(sign != null){ - sign.rotation = (sign.flip?90:270) - (int) (player.rotationYawHead); - } - } - } - - public void rightClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - BigHit hit = (BigHit)hitObj; - if(hit.target.equals(BigHitTarget.BASE)){ - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiPostRotationID, x, y, z), player); - } - } - - public void shiftClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - if(((BigHit)hitObj).target.equals(BigHitTarget.BASE)){ - Sign sign = ((BigPostPostTile)superTile).getBases().sign; - if(sign != null){ - sign.rotation = (sign.flip?270:90) - (int) (player.rotationYawHead); - } - } - } - - @Override - public void click(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - BigBaseInfo tilebases = ((BigPostPostTile)superTile).getBases(); - if (hit.target == BigHitTarget.BASE) { - if(tilebases.sign.overlay != null){ - player.inventory.addItemStackToInventory(new ItemStack(tilebases.sign.overlay.item, 1)); - } - } - for(OverlayType now: OverlayType.values()){ - if(player.getHeldItem().getItem().getClass() == now.item.getClass()){ - if (hit.target == BigHitTarget.BASE) { - tilebases.sign.overlay = now; - } - player.inventory.consumeInventoryItem(now.item); - return; - } - } - if (hit.target == BigHitTarget.BASE) { - tilebases.sign.overlay = null; - } - } - - @Override - public void rightClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - if (hit.target != BigHitTarget.POST) { - if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { - return; - } - BigPostPostTile tile = (BigPostPostTile)superTile; - BaseInfo destination = tile.getBases().sign.base; - if (destination != null) { - if(destination.teleportPosition ==null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.noTeleport"), player); - }else{ - int stackSize = PostHandler.getStackSize(tile.toPos(), destination.teleportPosition); - if(PostHandler.canPay(player, tile.toPos(), destination.teleportPosition)){ - PostHandler.teleportMe(destination, player, stackSize); - }else{ - String[] keyword = { "", "" }; - String[] replacement = { ClientConfigStorage.INSTANCE.getCost().getUnlocalizedName() + ".name", "" + stackSize }; - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.payment", keyword, replacement), player); - } - } - } - } else { - if(!canUse(player, superTile)) return; - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBigPostID, x, y, z), player); - NetworkHandler.netWrap.sendTo(new SendAllWaystoneNamesMessage(PostHandler.getAllWaystones().select(new Function() { - @Override - public String apply(BaseInfo b) { - return b.getName(); - } - })), player); - } - } - - @Override - public void shiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - BigBaseInfo tilebases = ((BigPostPostTile)superTile).getBases(); - if (hit.target == BigHitTarget.BASE) { - tilebases.sign.point = !tilebases.sign.point; - } - } - - @Override - public void clickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - BigBaseInfo tilebases = ((BigPostPostTile)superTile).getBases(); - if (hit.target == BigHitTarget.BASE) { - tilebases.sign.point = !tilebases.sign.point; - } - } - - @Override - public void shiftClickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BigHit hit = (BigHit)hitObj; - shiftClick(hitObj, superTile, player, x, y, z); - } - - @Override - public void sendPostBasesToAll(SuperPostPostTile superTile) { - BigPostPostTile tile = (BigPostPostTile)superTile; - BigBaseInfo tilebases = tile.getBases(); - NetworkHandler.netWrap.sendToAll(new SendBigPostBasesMessage(tile, tilebases)); - } - - @Override - public void sendPostBasesToServer(SuperPostPostTile superTile) { - BigPostPostTile tile = (BigPostPostTile)superTile; - BigBaseInfo tilebases = tile.getBases(); - NetworkHandler.netWrap.sendToServer(new SendBigPostBasesMessage(tile, tilebases)); - } - - @Override - public Object getHitTarget(World world, int x, int y, int z, EntityPlayer player){ - Vec3 head = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); - head.yCoord+=player.getEyeHeight(); - if(player.isSneaking()) - head.yCoord-=0.08; - Vec3 look = player.getLookVec(); - BigPostPostTile tile = getWaystonePostTile(world, x, y, z); - BigBaseInfo bases = tile.getBases(); - DDDVector rotPos = new DDDVector(x+0.5,y+0.5,z+0.5); - DDDVector signPos; - DDDVector edges = new DDDVector(1.4375, 0.75, 0.0625); - - if(bases.sign.flip){ - signPos = new DDDVector(x-0.375, y+0.1875, z+0.625); - }else{ - signPos = new DDDVector(x-0.0625, y+0.1875, z+0.625); - } - Cuboid sign = new Cuboid(signPos, edges, bases.sign.calcRot(x, z), rotPos); - Cuboid post = new Cuboid(new DDDVector(x+0.375, y, z+0.375), new DDDVector(0.25, 1, 0.25), 0); - Cuboid waystone = new Cuboid(new DDDVector(x+0.25, y, z+0.25), new DDDVector(0.5, 0.5, 0.5), 0); - - DDDVector start = new DDDVector(head.xCoord, head.yCoord, head.zCoord); - DDDVector end = start.add(new DDDVector(look.xCoord, look.yCoord, look.zCoord)); - Intersect signHit = sign.traceLine(start, end, true); - Intersect postHit = post.traceLine(start, end, true); - Intersect waystoneHit = waystone.traceLine(start, end, true); - double signDist = signHit.exists&&bases.sign.base!=null&&bases.sign.base.hasName()?signHit.pos.distance(start):Double.MAX_VALUE; - double postDist = postHit.exists?postHit.pos.distance(start):Double.MAX_VALUE/2; - double waystoneDist = waystoneHit.exists&&tile.isWaystone()?waystoneHit.pos.distance(start):Double.MAX_VALUE; - double dist; - BigHitTarget target; - DDDVector pos; - dist = signDist; - pos = signHit.pos; - target = BigHitTarget.BASE; - if(waystoneDist", "" }; + String[] replacement = { ClientConfigStorage.INSTANCE.getCost() + .getUnlocalizedName() + ".name", "" + stackSize }; + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.payment", keyword, replacement), player); + } + } + } + } else { + if (!canUse(player, superTile)) return; + NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBigPostID, x, y, z), player); + NetworkHandler.netWrap.sendTo( + new SendAllWaystoneNamesMessage( + PostHandler.getAllWaystones() + .select(new Function() { + + @Override + public String apply(BaseInfo b) { + return b.getName(); + } + })), + player); + } + } + + @Override + public void shiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + BigHit hit = (BigHit) hitObj; + BigBaseInfo tilebases = ((BigPostPostTile) superTile).getBases(); + if (hit.target == BigHitTarget.BASE) { + tilebases.sign.point = !tilebases.sign.point; + } + } + + @Override + public void clickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + BigHit hit = (BigHit) hitObj; + BigBaseInfo tilebases = ((BigPostPostTile) superTile).getBases(); + if (hit.target == BigHitTarget.BASE) { + tilebases.sign.point = !tilebases.sign.point; + } + } + + @Override + public void shiftClickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + BigHit hit = (BigHit) hitObj; + shiftClick(hitObj, superTile, player, x, y, z); + } + + @Override + public void sendPostBasesToAll(SuperPostPostTile superTile) { + BigPostPostTile tile = (BigPostPostTile) superTile; + BigBaseInfo tilebases = tile.getBases(); + NetworkHandler.netWrap.sendToAll(new SendBigPostBasesMessage(tile, tilebases)); + } + + @Override + public void sendPostBasesToServer(SuperPostPostTile superTile) { + BigPostPostTile tile = (BigPostPostTile) superTile; + BigBaseInfo tilebases = tile.getBases(); + NetworkHandler.netWrap.sendToServer(new SendBigPostBasesMessage(tile, tilebases)); + } + + @Override + public Object getHitTarget(World world, int x, int y, int z, EntityPlayer player) { + Vec3 head = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); + head.yCoord += player.getEyeHeight(); + if (player.isSneaking()) head.yCoord -= 0.08; + Vec3 look = player.getLookVec(); + BigPostPostTile tile = getWaystonePostTile(world, x, y, z); + BigBaseInfo bases = tile.getBases(); + DDDVector rotPos = new DDDVector(x + 0.5, y + 0.5, z + 0.5); + DDDVector signPos; + DDDVector edges = new DDDVector(1.4375, 0.75, 0.0625); + + if (bases.sign.flip) { + signPos = new DDDVector(x - 0.375, y + 0.1875, z + 0.625); + } else { + signPos = new DDDVector(x - 0.0625, y + 0.1875, z + 0.625); + } + Cuboid sign = new Cuboid(signPos, edges, bases.sign.calcRot(x, z), rotPos); + Cuboid post = new Cuboid(new DDDVector(x + 0.375, y, z + 0.375), new DDDVector(0.25, 1, 0.25), 0); + Cuboid waystone = new Cuboid(new DDDVector(x + 0.25, y, z + 0.25), new DDDVector(0.5, 0.5, 0.5), 0); + + DDDVector start = new DDDVector(head.xCoord, head.yCoord, head.zCoord); + DDDVector end = start.add(new DDDVector(look.xCoord, look.yCoord, look.zCoord)); + Intersect signHit = sign.traceLine(start, end, true); + Intersect postHit = post.traceLine(start, end, true); + Intersect waystoneHit = waystone.traceLine(start, end, true); + double signDist = signHit.exists && bases.sign.base != null && bases.sign.base.hasName() + ? signHit.pos.distance(start) + : Double.MAX_VALUE; + double postDist = postHit.exists ? postHit.pos.distance(start) : Double.MAX_VALUE / 2; + double waystoneDist = waystoneHit.exists && tile.isWaystone() ? waystoneHit.pos.distance(start) + : Double.MAX_VALUE; + double dist; + BigHitTarget target; + DDDVector pos; + dist = signDist; + pos = signHit.pos; + target = BigHitTarget.BASE; + if (waystoneDist < dist) { + dist = waystoneDist; + pos = waystoneHit.pos; + target = BigHitTarget.STONE; + } + if (postDist < dist) { + dist = postDist; + pos = postHit.pos; + target = BigHitTarget.POST; + } + return new BigHit(target, pos); + } + + public int getRenderType() { + return -1; + } + + public boolean renderAsNormalBlock() { + return false; + } + + public boolean isOpaqueCube() { + return false; + } + + @Override + public Paintable getPaintableByHit(SuperPostPostTile tile, Object hit) { + switch ((BigHitTarget) hit) { + case BASE: + return ((BigPostPostTile) tile).getBases().sign; + case POST: + return ((BigPostPostTile) tile).getBases(); + default: + return null; + } + } + + public static BigPostPostTile getTile(World world, int x, int y, int z) { + TileEntity ret = world.getTileEntity(x, y, z); + if (ret instanceof BigPostPostTile) { + return (BigPostPostTile) ret; + } else { + return null; + } + } + + @Override + protected boolean isHitWaystone(Object hitObj) { + BigHit hit = (BigHit) hitObj; + return hit.target == BigHitTarget.STONE; + } + } diff --git a/src/main/java/gollorum/signpost/blocks/ItemBlockWithMeta.java b/src/main/java/gollorum/signpost/blocks/ItemBlockWithMeta.java index 495e6e74..2839866a 100644 --- a/src/main/java/gollorum/signpost/blocks/ItemBlockWithMeta.java +++ b/src/main/java/gollorum/signpost/blocks/ItemBlockWithMeta.java @@ -3,17 +3,17 @@ import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; -public class ItemBlockWithMeta extends ItemBlock{ +public class ItemBlockWithMeta extends ItemBlock { + + public ItemBlockWithMeta(Block block) { + super(block); + setMaxDamage(0); + setHasSubtypes(true); + } + + @Override + public int getMetadata(int damage) { + return damage; + } - public ItemBlockWithMeta(Block block){ - super(block); - setMaxDamage(0); - setHasSubtypes(true); - } - - @Override - public int getMetadata(int damage){ - return damage; - } - } diff --git a/src/main/java/gollorum/signpost/blocks/ItemBlockWithMetaFacing.java b/src/main/java/gollorum/signpost/blocks/ItemBlockWithMetaFacing.java index 526de184..571b12f1 100644 --- a/src/main/java/gollorum/signpost/blocks/ItemBlockWithMetaFacing.java +++ b/src/main/java/gollorum/signpost/blocks/ItemBlockWithMetaFacing.java @@ -3,12 +3,12 @@ import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; -public class ItemBlockWithMetaFacing extends ItemBlock{ - - public ItemBlockWithMetaFacing(Block block){ - super(block); - setMaxDamage(0); - setHasSubtypes(true); - } - +public class ItemBlockWithMetaFacing extends ItemBlock { + + public ItemBlockWithMetaFacing(Block block) { + super(block); + setMaxDamage(0); + setHasSubtypes(true); + } + } diff --git a/src/main/java/gollorum/signpost/blocks/PostPost.java b/src/main/java/gollorum/signpost/blocks/PostPost.java index 715372bb..7d991dd6 100644 --- a/src/main/java/gollorum/signpost/blocks/PostPost.java +++ b/src/main/java/gollorum/signpost/blocks/PostPost.java @@ -1,6 +1,22 @@ package gollorum.signpost.blocks; +import java.util.function.Function; + +import net.minecraft.block.material.Material; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; + import gollorum.signpost.Signpost; +import gollorum.signpost.Tags; import gollorum.signpost.blocks.tiles.PostPostTile; import gollorum.signpost.blocks.tiles.SuperPostPostTile; import gollorum.signpost.management.ClientConfigStorage; @@ -18,395 +34,407 @@ import gollorum.signpost.util.math.tracking.Cuboid; import gollorum.signpost.util.math.tracking.DDDVector; import gollorum.signpost.util.math.tracking.Intersect; -import net.minecraft.block.material.Material; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; - -import java.util.function.Function; public class PostPost extends SuperPostPost { - - public PostType type; - - public enum PostType{ - OAK( Material.wood, "sign_oak", "log_oak", Item.getItemFromBlock(Blocks.log), 0), - SPRUCE( Material.wood, "sign_spruce", "log_spruce", Item.getItemFromBlock(Blocks.log), 1), - BIRCH( Material.wood, "sign_birch", "log_birch", Item.getItemFromBlock(Blocks.log), 2), - JUNGLE( Material.wood, "sign_jungle", "log_jungle", Item.getItemFromBlock(Blocks.log), 3), - ACACIA( Material.wood, "sign_acacia", "log_acacia", Item.getItemFromBlock(Blocks.log2), 0), - BIGOAK( Material.wood, "sign_big_oak", "log_big_oak", Item.getItemFromBlock(Blocks.log2), 1), - IRON( Material.iron, "sign_iron", "iron_block", Items.iron_ingot, 0), - STONE( Material.rock, "sign_stone", "stone", Item.getItemFromBlock(Blocks.stone), 0); - public Material material; - public ResourceLocation texture; - public String blockTexture; - public String textureMain; - public ResourceLocation resLocMain; - public Item baseItem; - public int metadata; - - PostType(Material material, String texture, String textureMain, Item baseItem, int metadata) { - this.material = material; - this.texture = new ResourceLocation(Signpost.MODID + ":textures/blocks/"+texture+".png"); - this.blockTexture = texture; - this.textureMain = textureMain; - this.resLocMain = new ResourceLocation("minecraft:textures/blocks/"+textureMain+".png"); - this.baseItem = baseItem; - this.metadata = metadata; - } - } - - public enum HitTarget{BASE1, BASE2, POST, STONE} - - public static class Hit{ - public HitTarget target; - public DDDVector pos; - public Hit(HitTarget target, DDDVector pos){ - this.target = target; this.pos = pos; - } - } - - @Deprecated - public PostPost() { - super(Material.wood); - setBlockName("SignpostPost"); - setCreativeTab(CreativeTabs.tabTransport); - setBlockTextureName("minecraft:planks_oak"); - this.setHardness(2); - this.setResistance(100000); - float f = 15F / 32; - this.setBlockBounds(0.5f - f, 0.0F, 0.5F - f, 0.5F + f, 1, 0.5F + f); - } - - public PostPost(PostType type){ - super(type.material); - this.type = type; - setBlockName("SignpostPost"+type.toString()); - setCreativeTab(CreativeTabs.tabTransport); - setBlockTextureName(Signpost.MODID+":"+type.blockTexture); - this.setHardness(2); - this.setResistance(100000); - float f = 15F / 32; - this.setBlockBounds(0.5f - f, 0.0F, 0.5F - f, 0.5F + f, 1, 0.5F + f); - } - - @Override - public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) { - PostPostTile tile = new PostPostTile(type); - return tile; - } - - public static PostPostTile getWaystonePostTile(World world, int x, int y, int z) { - TileEntity ret = world.getTileEntity(x, y, z); - if (ret instanceof PostPostTile) { - return (PostPostTile) ret; - } else { - return null; - } - } - - @Override - public void clickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - Hit hit = (Hit)hitObj; - DoubleBaseInfo tilebases = ((PostPostTile)superTile).getBases(); - if (hit.target == HitTarget.BASE1) { - tilebases.sign1.rot(-15, x, z); - } else if(hit.target == HitTarget.BASE2) { - tilebases.sign2.rot(-15, x, z); - } - } - - @Override - public void rightClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - Hit hit = (Hit)hitObj; - DoubleBaseInfo tilebases = ((PostPostTile)superTile).getBases(); - if (hit.target == HitTarget.BASE1) { - tilebases.sign1.rot(15, x, z); - } else if (hit.target == HitTarget.BASE2) { - tilebases.sign2.rot(15, x, z); - } - } - - @Override - public void shiftClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - Hit hit = (Hit)hitObj; - DoubleBaseInfo tilebases = ((PostPostTile)superTile).getBases(); - if (hit.target == HitTarget.BASE1) { - tilebases.sign1.flip = !tilebases.sign1.flip; - } else if(hit.target == HitTarget.BASE2) { - tilebases.sign2.flip = !tilebases.sign2.flip; - } - } - - @Override - public void clickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiPostBrushID, x, y, z), player); - } - - @Override - public void rightClickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - DoubleBaseInfo tilebases = ((PostPostTile)superTile).getBases(); - if(tilebases.awaitingPaint && tilebases.paintObject!=null){ - tilebases.paintObject = null; - tilebases.awaitingPaint = false; - }else{ - Hit hit = (Hit)hitObj; - tilebases.awaitingPaint = true; - if(hit.target == HitTarget.POST){ - tilebases.paintObject = tilebases; - } else if (hit.target == HitTarget.BASE1) { - tilebases.paintObject = tilebases.sign1; - } else if (hit.target == HitTarget.BASE2) { - tilebases.paintObject = tilebases.sign2; - } else{ - tilebases.paintObject = null; - tilebases.awaitingPaint = false; - } - } - } - - public void clickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - Sign sign = getSignByHit((Hit)hitObj, (PostPostTile) superTile); - if(sign != null){ - sign.rotation = (sign.flip?90:270) - (int) (player.rotationYawHead); - } - } - - public void rightClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - Hit hit = (Hit)hitObj; - if(hit.target.equals(HitTarget.BASE1)||hit.target.equals(HitTarget.BASE2)){ - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiPostRotationID, x, y, z), player); - } - } - - public void shiftClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - Sign sign = getSignByHit((Hit)hitObj, (PostPostTile) superTile); - if(sign != null){ - sign.rotation = (sign.flip?270:90) - (int) (player.rotationYawHead); - } - } - - @Override - public void click(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - Hit hit = (Hit)hitObj; - PostPostTile tile = (PostPostTile)superTile; - DoubleBaseInfo tilebases = tile.getBases(); - if (hit.target == HitTarget.BASE1) { - if(tilebases.sign1.overlay != null){ - player.inventory.addItemStackToInventory(new ItemStack(tilebases.sign1.overlay.item, 1)); - } - } else if(hit.target == HitTarget.BASE2) { - if(tilebases.sign2.overlay != null){ - player.inventory.addItemStackToInventory(new ItemStack(tilebases.sign2.overlay.item, 1)); - } - } - for(OverlayType now: OverlayType.values()){ - if(player.getHeldItem().getItem().getClass() == now.item.getClass()){ - if (hit.target == HitTarget.BASE1) { - tilebases.sign1.overlay = now; - } else if(hit.target == HitTarget.BASE2) { - tilebases.sign2.overlay = now; - } - player.inventory.consumeInventoryItem(now.item); - NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); - return; - } - } - if (hit.target == HitTarget.BASE1) { - tilebases.sign1.overlay = null; - } else if(hit.target == HitTarget.BASE2) { - tilebases.sign2.overlay = null; - } - NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); - } - - @Override - public void rightClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - Hit hit = (Hit)hitObj; - PostPostTile tile = (PostPostTile)superTile; - if (hit.target != HitTarget.POST) { - if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { - return; - } - BaseInfo destination = hit.target == HitTarget.BASE1 ? tile.getBases().sign1.base : tile.getBases().sign2.base; - if (destination != null) { - if(destination.teleportPosition ==null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.noTeleport"), player); - }else{ - int stackSize = PostHandler.getStackSize(tile.toPos(), destination.teleportPosition); - if(PostHandler.canPay(player, tile.toPos(), destination.teleportPosition)){ - PostHandler.teleportMe(destination, player, stackSize); - }else{ - String[] keyword = { "", "" }; - String[] replacement = { ClientConfigStorage.INSTANCE.getCost().getUnlocalizedName() + ".name", "" + stackSize }; - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.payment", keyword, replacement), player); - } - } - } - } else { - if(!canUse(player, superTile)) return; - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiPostID, x, y, z), player); - NetworkHandler.netWrap.sendTo(new SendAllWaystoneNamesMessage(PostHandler.getAllWaystones().select(new Function() { - @Override - public String apply(BaseInfo b) { - return b.getName(); - } - })), player); - } - } - - @Override - public void shiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - Hit hit = (Hit)hitObj; - DoubleBaseInfo tilebases = ((PostPostTile)superTile).getBases(); - if (hit.target == HitTarget.BASE1) { - tilebases.sign1.point = !tilebases.sign1.point; - } else if(hit.target == HitTarget.BASE2) { - tilebases.sign2.point = !tilebases.sign2.point; - } - } - - @Override - public void clickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - Hit hit = (Hit)hitObj; - PostPostTile tile = (PostPostTile)superTile; - DoubleBaseInfo tilebases = tile.getBases(); - if (hit.target == HitTarget.BASE1) { - tilebases.sign1.point = !tilebases.sign1.point; - NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); - } else if(hit.target == HitTarget.BASE2) { - tilebases.sign2.point = !tilebases.sign2.point; - NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); - } - } - - @Override - public void shiftClickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - shiftClick(hitObj, superTile, player, x, y, z); - } - - @Override - public void sendPostBasesToAll(SuperPostPostTile superTile) { - PostPostTile tile = (PostPostTile)superTile; - DoubleBaseInfo tilebases = tile.getBases(); - NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); - } - - @Override - public void sendPostBasesToServer(SuperPostPostTile superTile) { - PostPostTile tile = (PostPostTile)superTile; - DoubleBaseInfo tilebases = tile.getBases(); - NetworkHandler.netWrap.sendToServer(new SendPostBasesMessage(tile, tilebases)); - } - - @Override - public Object getHitTarget(World world, int x, int y, int z, EntityPlayer player){ - Vec3 head = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); - head.yCoord+=player.getEyeHeight(); - if(player.isSneaking()) - head.yCoord-=0.08; - Vec3 look = player.getLookVec(); - PostPostTile tile = getWaystonePostTile(world, x, y, z); - DoubleBaseInfo bases = tile.getBases(); - DDDVector rotPos = new DDDVector(x+0.5,y+0.5,z+0.5); - DDDVector signPos; - DDDVector edges = new DDDVector(1.4375, 0.375, 0.0625); - - if(bases.sign1.flip){ - signPos = new DDDVector(x-0.375, y+0.5625, z+0.625); - }else{ - signPos = new DDDVector(x-0.0625, y+0.5625, z+0.625); - } - Cuboid sign1 = new Cuboid(signPos, edges, bases.sign1.calcRot(x, z), rotPos); - - if(bases.sign2.flip){ - signPos = new DDDVector(x-0.375, y+0.0625, z+0.625); - }else{ - signPos = new DDDVector(x-0.0625, y+0.0625, z+0.625); - } - Cuboid sign2 = new Cuboid(signPos, edges, bases.sign2.calcRot(x, z), rotPos); - Cuboid post = new Cuboid(new DDDVector(x+0.375, y, z+0.375), new DDDVector(0.25, 1, 0.25), 0); - Cuboid waystone = new Cuboid(new DDDVector(x+0.25, y, z+0.25), new DDDVector(0.5, 0.5, 0.5), 0); - - DDDVector start = new DDDVector(head.xCoord, head.yCoord, head.zCoord); - DDDVector end = start.add(new DDDVector(look.xCoord, look.yCoord, look.zCoord)); - Intersect sign1Hit = sign1.traceLine(start, end, true); - Intersect sign2Hit = sign2.traceLine(start, end, true); - Intersect postHit = post.traceLine(start, end, true); - Intersect waystoneHit = waystone.traceLine(start, end, true); - double sign1Dist = sign1Hit.exists&&bases.sign1.isValid()?sign1Hit.pos.distance(start):Double.MAX_VALUE; - double sign2Dist = sign2Hit.exists&&bases.sign2.isValid()?sign2Hit.pos.distance(start):Double.MAX_VALUE; - double postDist = postHit.exists?postHit.pos.distance(start):Double.MAX_VALUE/2; - double waystoneDist = waystoneHit.exists&&tile.isWaystone()?waystoneHit.pos.distance(start):Double.MAX_VALUE; - double dist; - HitTarget target; - DDDVector pos; - if(sign1Dist", "" }; + String[] replacement = { ClientConfigStorage.INSTANCE.getCost() + .getUnlocalizedName() + ".name", "" + stackSize }; + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.payment", keyword, replacement), player); + } + } + } + } else { + if (!canUse(player, superTile)) return; + NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiPostID, x, y, z), player); + NetworkHandler.netWrap.sendTo( + new SendAllWaystoneNamesMessage( + PostHandler.getAllWaystones() + .select(new Function() { + + @Override + public String apply(BaseInfo b) { + return b.getName(); + } + })), + player); + } + } + + @Override + public void shiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + Hit hit = (Hit) hitObj; + DoubleBaseInfo tilebases = ((PostPostTile) superTile).getBases(); + if (hit.target == HitTarget.BASE1) { + tilebases.sign1.point = !tilebases.sign1.point; + } else if (hit.target == HitTarget.BASE2) { + tilebases.sign2.point = !tilebases.sign2.point; + } + } + + @Override + public void clickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + Hit hit = (Hit) hitObj; + PostPostTile tile = (PostPostTile) superTile; + DoubleBaseInfo tilebases = tile.getBases(); + if (hit.target == HitTarget.BASE1) { + tilebases.sign1.point = !tilebases.sign1.point; + NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); + } else if (hit.target == HitTarget.BASE2) { + tilebases.sign2.point = !tilebases.sign2.point; + NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); + } + } + + @Override + public void shiftClickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + shiftClick(hitObj, superTile, player, x, y, z); + } + + @Override + public void sendPostBasesToAll(SuperPostPostTile superTile) { + PostPostTile tile = (PostPostTile) superTile; + DoubleBaseInfo tilebases = tile.getBases(); + NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage(tile, tilebases)); + } + + @Override + public void sendPostBasesToServer(SuperPostPostTile superTile) { + PostPostTile tile = (PostPostTile) superTile; + DoubleBaseInfo tilebases = tile.getBases(); + NetworkHandler.netWrap.sendToServer(new SendPostBasesMessage(tile, tilebases)); + } + + @Override + public Object getHitTarget(World world, int x, int y, int z, EntityPlayer player) { + Vec3 head = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); + head.yCoord += player.getEyeHeight(); + if (player.isSneaking()) head.yCoord -= 0.08; + Vec3 look = player.getLookVec(); + PostPostTile tile = getWaystonePostTile(world, x, y, z); + DoubleBaseInfo bases = tile.getBases(); + DDDVector rotPos = new DDDVector(x + 0.5, y + 0.5, z + 0.5); + DDDVector signPos; + DDDVector edges = new DDDVector(1.4375, 0.375, 0.0625); + + if (bases.sign1.flip) { + signPos = new DDDVector(x - 0.375, y + 0.5625, z + 0.625); + } else { + signPos = new DDDVector(x - 0.0625, y + 0.5625, z + 0.625); + } + Cuboid sign1 = new Cuboid(signPos, edges, bases.sign1.calcRot(x, z), rotPos); + + if (bases.sign2.flip) { + signPos = new DDDVector(x - 0.375, y + 0.0625, z + 0.625); + } else { + signPos = new DDDVector(x - 0.0625, y + 0.0625, z + 0.625); + } + Cuboid sign2 = new Cuboid(signPos, edges, bases.sign2.calcRot(x, z), rotPos); + Cuboid post = new Cuboid(new DDDVector(x + 0.375, y, z + 0.375), new DDDVector(0.25, 1, 0.25), 0); + Cuboid waystone = new Cuboid(new DDDVector(x + 0.25, y, z + 0.25), new DDDVector(0.5, 0.5, 0.5), 0); + + DDDVector start = new DDDVector(head.xCoord, head.yCoord, head.zCoord); + DDDVector end = start.add(new DDDVector(look.xCoord, look.yCoord, look.zCoord)); + Intersect sign1Hit = sign1.traceLine(start, end, true); + Intersect sign2Hit = sign2.traceLine(start, end, true); + Intersect postHit = post.traceLine(start, end, true); + Intersect waystoneHit = waystone.traceLine(start, end, true); + double sign1Dist = sign1Hit.exists && bases.sign1.isValid() ? sign1Hit.pos.distance(start) : Double.MAX_VALUE; + double sign2Dist = sign2Hit.exists && bases.sign2.isValid() ? sign2Hit.pos.distance(start) : Double.MAX_VALUE; + double postDist = postHit.exists ? postHit.pos.distance(start) : Double.MAX_VALUE / 2; + double waystoneDist = waystoneHit.exists && tile.isWaystone() ? waystoneHit.pos.distance(start) + : Double.MAX_VALUE; + double dist; + HitTarget target; + DDDVector pos; + if (sign1Dist < sign2Dist) { + dist = sign1Dist; + pos = sign1Hit.pos; + target = HitTarget.BASE1; + } else { + dist = sign2Dist; + pos = sign2Hit.pos; + target = HitTarget.BASE2; + } + if (waystoneDist <= dist) { + dist = waystoneDist; + pos = waystoneHit.pos; + target = HitTarget.STONE; + } + if (postDist < dist) { + dist = postDist; + pos = postHit.pos; + target = HitTarget.POST; + } + return new Hit(target, pos); + } + + @Override + public Paintable getPaintableByHit(SuperPostPostTile tile, Object hit) { + switch ((HitTarget) hit) { + case BASE1: + return ((PostPostTile) tile).getBases().sign1; + case BASE2: + return ((PostPostTile) tile).getBases().sign2; + case POST: + return ((PostPostTile) tile).getBases(); + default: + return null; + } + } + + public static PostPostTile getTile(World world, int x, int y, int z) { + TileEntity ret = world.getTileEntity(x, y, z); + if (ret instanceof PostPostTile) { + return (PostPostTile) ret; + } else { + return null; + } + } + + public Sign getSignByHit(Hit hit, PostPostTile tile) { + if (hit.target.equals(HitTarget.BASE1)) { + return tile.getBases().sign1; + } else if (hit.target.equals(HitTarget.BASE2)) { + return tile.getBases().sign2; + } else { + return null; + } + } + + @Override + protected boolean isHitWaystone(Object hitObj) { + return ((Hit) hitObj).target.equals(HitTarget.STONE); + } } diff --git a/src/main/java/gollorum/signpost/blocks/SuperPostPost.java b/src/main/java/gollorum/signpost/blocks/SuperPostPost.java index 7460a9bd..6004cdf2 100644 --- a/src/main/java/gollorum/signpost/blocks/SuperPostPost.java +++ b/src/main/java/gollorum/signpost/blocks/SuperPostPost.java @@ -1,5 +1,17 @@ package gollorum.signpost.blocks; +import java.util.UUID; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; + import gollorum.signpost.BlockHandler; import gollorum.signpost.SPEventHandler; import gollorum.signpost.Signpost; @@ -19,270 +31,305 @@ import gollorum.signpost.util.BaseInfo; import gollorum.signpost.util.MyBlockPos; import gollorum.signpost.util.Paintable; -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.Item; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; - -import java.util.UUID; public abstract class SuperPostPost extends BlockContainer { - - protected SuperPostPost(Material p_i45386_1_) {super(p_i45386_1_);} - - @Override - public void onBlockClicked(World world, int x, int y, int z, EntityPlayer playerIn) { - SuperPostPostTile superTile = getSuperTile(world, x, y, z); - if (world.isRemote || !canUse((EntityPlayerMP) playerIn, superTile)) { - return; - } - EntityPlayerMP player = (EntityPlayerMP) playerIn; - Object hit = getHitTarget(world, x, y, z, player); - if(isHitWaystone(hit)&&player.isSneaking()){ - superTile.destroyWaystone(); - - }else if (player.getHeldItem() != null){ - Item item = player.getHeldItem().getItem(); - if(item instanceof PostWrench) { - if (player.isSneaking()) { - if(preShiftClick(hit, superTile, player, x, y, z)){ - shiftClickWrench(hit, superTile, player, x, y, z); - } - } else { - clickWrench(hit, superTile, player, x, y, z); - } - }else if(item instanceof CalibratedPostWrench) { - if (player.isSneaking()) { - if(preShiftClick(hit, superTile, player, x, y, z)){ - shiftClickCalibratedWrench(hit, superTile, player, x, y, z); - } - } else { - clickCalibratedWrench(hit, superTile, player, x, y, z); - } - }else if(item instanceof PostBrush) { - clickBrush(hit, superTile, player, x, y, z); - }else{ - if (player.isSneaking()) { - if(preShiftClick(hit, superTile, player, x, y, z)){ - shiftClick(hit, superTile, player, x, y, z); - } - }else{ - click(hit, superTile, player, x, y, z); - } - } - }else{ - if (player.isSneaking()) { - if(preShiftClick(hit, superTile, player, x, y, z)){ - shiftClickBare(hit, superTile, player, x, y, z); - } - }else{ - clickBare(hit, superTile, player, x, y, z); - } - } - sendPostBasesToAll(superTile); - } - - @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer playerIn, int facing, float hitX, float hitY, float hitZ) { - if(MinecraftForge.EVENT_BUS.post(new UseSignpostEvent(playerIn, world, x, y, z)) || world.isRemote){ - return true; - } - Object hit = getHitTarget(world, x, y, z, playerIn); - SuperPostPostTile superTile = getSuperTile(world, x, y, z); - EntityPlayerMP player = (EntityPlayerMP) playerIn; - if(isHitWaystone(hit)){ - rightClickWaystone(superTile, player, x, y, z); - }else if (player.getHeldItem() != null){ - if(player.getHeldItem().getItem() instanceof PostWrench){ - if(!canUse(player, superTile)){ - return true; - } - rightClickWrench(hit, superTile, player, x, y, z); - sendPostBasesToAll(superTile); - }else if(player.getHeldItem().getItem() instanceof CalibratedPostWrench){ - if(!canUse(player, superTile)){ - return true; - } - rightClickCalibratedWrench(hit, superTile, player, x, y, z); - }else if(player.getHeldItem().getItem() instanceof PostBrush){ - if(!canUse(player, superTile)){ - return true; - } - rightClickBrush(hit, superTile, player, x, y, z); - sendPostBasesToAll(superTile); - }else if(superTile.isAwaitingPaint()){ - if(!canUse(player, superTile)){ - return true; - } - if(superTile.getPaintObject()==null){ - superTile.setAwaitingPaint(false); - }else{ - NetworkHandler.netWrap.sendTo(new RequestTextureMessage(x, y, z), player); - } - }else if(Block.getBlockFromItem(player.getHeldItem().getItem()) instanceof BasePost){ - if(rightClickBase(superTile, player, x, y, z)){ - preRightClick(hit, superTile, player, x, y, z); - } - }else{ - preRightClick(hit, superTile, player, x, y, z); - } - } else { - preRightClick(hit, superTile, player, x, y, z); - } - return true; - } - - protected boolean canUse(EntityPlayerMP player, SuperPostPostTile tile) { - return ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().canUse(player, ""+tile.owner); - } - - private void rightClickWaystone(SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - BaseInfo ws = superTile.getBaseInfo(); - if(!player.isSneaking()){ - if(!PostHandler.doesPlayerKnowNativeWaystone(player, ws)){ - if (!ClientConfigStorage.INSTANCE.deactivateTeleportation()) { - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.discovered", "", ws.getName()), player); - } - PostHandler.addDiscovered(player.getUniqueID(), ws); - } - }else{ - if (!ClientConfigStorage.INSTANCE.deactivateTeleportation() - && ClientConfigStorage.INSTANCE.getSecurityLevelWaystone().canUse(player, ""+ws.owner)) { - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), player); - } - } - } - - /** - * @return whether the signpost already is a waystone - */ - private boolean rightClickBase(SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - if(superTile.isWaystone()){ - return true; - } - if(!(ClientConfigStorage.INSTANCE.getSecurityLevelSignpost().canUse(player, ""+superTile.owner) && SPEventHandler.INSTANCE.checkWaystoneCount(player))){ - return true; - } - MyBlockPos blockPos = superTile.toPos(); - MyBlockPos telePos = new MyBlockPos(player); - String name = BasePost.generateName(); - UUID owner = player.getUniqueID(); - BaseInfo ws = new BaseInfo(name, blockPos, telePos, owner); - PostHandler.addWaystone(ws); - PostHandler.addDiscovered(owner, ws); - NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); - MinecraftForge.EVENT_BUS.post(new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.PLACED,superTile.getWorldObj(), telePos.x, telePos.y, telePos.z, name)); - NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), player); - superTile.isWaystone = true; - player.inventory.consumeInventoryItem(Item.getItemFromBlock(BlockHandler.base)); - return false; - } - - private void preRightClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z){ - if(isHitWaystone(hitObj)){ - BaseInfo ws = superTile.getBaseInfo(); - if(!PostHandler.doesPlayerKnowNativeWaystone(player, ws)){ - if (!ClientConfigStorage.INSTANCE.deactivateTeleportation()) { - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.discovered", "", ws.getName()), player); - } - PostHandler.addDiscovered(player.getUniqueID(), ws); - } - }else{ - rightClick(hitObj, superTile, player, x, y, z); - } - } - - private boolean preShiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { - if(isHitWaystone(hitObj)){ - superTile.destroyWaystone(); - return false; - }else{ - return true; - } - } - - protected abstract boolean isHitWaystone(Object hitObj); - - public abstract void clickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void rightClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void shiftClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - - public abstract void clickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void rightClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void shiftClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - - public abstract void clickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void rightClickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - - public abstract void click(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void rightClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void shiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - - public abstract void clickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - public abstract void shiftClickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); - - public abstract void sendPostBasesToAll(SuperPostPostTile superTile); - public abstract void sendPostBasesToServer(SuperPostPostTile superTile); - - public static SuperPostPostTile getSuperTile(World world, int x, int y, int z){ - return (SuperPostPostTile) world.getTileEntity(x, y, z); - } - - public static SuperPostPostTile getSuperTile(MyBlockPos pos){ - TileEntity tile = pos.getTile(); - if(tile == null){ - pos.getWorld().getBlock(pos.x, pos.y, pos.z); - tile = pos.getTile(); - } - if(tile instanceof SuperPostPostTile){ - return (SuperPostPostTile) tile; - } - return null; - } - - public static void updateServer(MyBlockPos pos){ - SuperPostPostTile tile = getSuperTile(pos); - if(tile == null){ - return; - } - tile.getSuperBlock().sendPostBasesToAll(tile); - } - - public static void updateClient(MyBlockPos pos){ - SuperPostPostTile tile = getSuperTile(pos); - if(tile == null){ - return; - } - tile.getSuperBlock().sendPostBasesToServer(tile); - } - - public abstract Object getHitTarget(World world, int x, int y, int z, EntityPlayer/*MP*/ player); - - public abstract Paintable getPaintableByHit(SuperPostPostTile tile, Object hit); - - public int getRenderType() { - return -1; - } - - public boolean renderAsNormalBlock() { - return false; - } - - public boolean isOpaqueCube() { - return false; - } - - public static void placeClient(World world, MyBlockPos blockPos, EntityPlayer player) { - getSuperTile(world, blockPos.x, blockPos.y, blockPos.z).owner = player.getUniqueID(); - } - - public static void placeServer(World world, MyBlockPos blockPos, EntityPlayerMP player) { - getSuperTile(world, blockPos.x, blockPos.y, blockPos.z).owner = player.getUniqueID(); - } + + protected SuperPostPost(Material p_i45386_1_) { + super(p_i45386_1_); + } + + @Override + public void onBlockClicked(World world, int x, int y, int z, EntityPlayer playerIn) { + SuperPostPostTile superTile = getSuperTile(world, x, y, z); + if (world.isRemote || !canUse((EntityPlayerMP) playerIn, superTile)) { + return; + } + EntityPlayerMP player = (EntityPlayerMP) playerIn; + Object hit = getHitTarget(world, x, y, z, player); + if (isHitWaystone(hit) && player.isSneaking()) { + superTile.destroyWaystone(); + + } else if (player.getHeldItem() != null) { + Item item = player.getHeldItem() + .getItem(); + if (item instanceof PostWrench) { + if (player.isSneaking()) { + if (preShiftClick(hit, superTile, player, x, y, z)) { + shiftClickWrench(hit, superTile, player, x, y, z); + } + } else { + clickWrench(hit, superTile, player, x, y, z); + } + } else if (item instanceof CalibratedPostWrench) { + if (player.isSneaking()) { + if (preShiftClick(hit, superTile, player, x, y, z)) { + shiftClickCalibratedWrench(hit, superTile, player, x, y, z); + } + } else { + clickCalibratedWrench(hit, superTile, player, x, y, z); + } + } else if (item instanceof PostBrush) { + clickBrush(hit, superTile, player, x, y, z); + } else { + if (player.isSneaking()) { + if (preShiftClick(hit, superTile, player, x, y, z)) { + shiftClick(hit, superTile, player, x, y, z); + } + } else { + click(hit, superTile, player, x, y, z); + } + } + } else { + if (player.isSneaking()) { + if (preShiftClick(hit, superTile, player, x, y, z)) { + shiftClickBare(hit, superTile, player, x, y, z); + } + } else { + clickBare(hit, superTile, player, x, y, z); + } + } + sendPostBasesToAll(superTile); + } + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer playerIn, int facing, float hitX, + float hitY, float hitZ) { + if (MinecraftForge.EVENT_BUS.post(new UseSignpostEvent(playerIn, world, x, y, z)) || world.isRemote) { + return true; + } + Object hit = getHitTarget(world, x, y, z, playerIn); + SuperPostPostTile superTile = getSuperTile(world, x, y, z); + EntityPlayerMP player = (EntityPlayerMP) playerIn; + if (isHitWaystone(hit)) { + rightClickWaystone(superTile, player, x, y, z); + } else if (player.getHeldItem() != null) { + if (player.getHeldItem() + .getItem() instanceof PostWrench) { + if (!canUse(player, superTile)) { + return true; + } + rightClickWrench(hit, superTile, player, x, y, z); + sendPostBasesToAll(superTile); + } else if (player.getHeldItem() + .getItem() instanceof CalibratedPostWrench) { + if (!canUse(player, superTile)) { + return true; + } + rightClickCalibratedWrench(hit, superTile, player, x, y, z); + } else if (player.getHeldItem() + .getItem() instanceof PostBrush) { + if (!canUse(player, superTile)) { + return true; + } + rightClickBrush(hit, superTile, player, x, y, z); + sendPostBasesToAll(superTile); + } else if (superTile.isAwaitingPaint()) { + if (!canUse(player, superTile)) { + return true; + } + if (superTile.getPaintObject() == null) { + superTile.setAwaitingPaint(false); + } else { + NetworkHandler.netWrap.sendTo(new RequestTextureMessage(x, y, z), player); + } + } else if (Block.getBlockFromItem( + player.getHeldItem() + .getItem()) instanceof BasePost) { + if (rightClickBase(superTile, player, x, y, z)) { + preRightClick(hit, superTile, player, x, y, z); + } + } else { + preRightClick(hit, superTile, player, x, y, z); + } + } else { + preRightClick(hit, superTile, player, x, y, z); + } + return true; + } + + protected boolean canUse(EntityPlayerMP player, SuperPostPostTile tile) { + return ClientConfigStorage.INSTANCE.getSecurityLevelSignpost() + .canUse(player, "" + tile.owner); + } + + private void rightClickWaystone(SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + BaseInfo ws = superTile.getBaseInfo(); + if (!player.isSneaking()) { + if (!PostHandler.doesPlayerKnowNativeWaystone(player, ws)) { + if (!ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.discovered", "", ws.getName()), player); + } + PostHandler.addDiscovered(player.getUniqueID(), ws); + } + } else { + if (!ClientConfigStorage.INSTANCE.deactivateTeleportation() + && ClientConfigStorage.INSTANCE.getSecurityLevelWaystone() + .canUse(player, "" + ws.owner)) { + NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), player); + } + } + } + + /** + * @return whether the signpost already is a waystone + */ + private boolean rightClickBase(SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + if (superTile.isWaystone()) { + return true; + } + if (!(ClientConfigStorage.INSTANCE.getSecurityLevelSignpost() + .canUse(player, "" + superTile.owner) && SPEventHandler.INSTANCE.checkWaystoneCount(player))) { + return true; + } + MyBlockPos blockPos = superTile.toPos(); + MyBlockPos telePos = new MyBlockPos(player); + String name = BasePost.generateName(); + UUID owner = player.getUniqueID(); + BaseInfo ws = new BaseInfo(name, blockPos, telePos, owner); + PostHandler.addWaystone(ws); + PostHandler.addDiscovered(owner, ws); + NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); + MinecraftForge.EVENT_BUS.post( + new UpdateWaystoneEvent( + UpdateWaystoneEvent.WaystoneEventType.PLACED, + superTile.getWorldObj(), + telePos.x, + telePos.y, + telePos.z, + name)); + NetworkHandler.netWrap.sendTo(new OpenGuiMessage(Signpost.GuiBaseID, x, y, z), player); + superTile.isWaystone = true; + player.inventory.consumeInventoryItem(Item.getItemFromBlock(BlockHandler.base)); + return false; + } + + private void preRightClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z) { + if (isHitWaystone(hitObj)) { + BaseInfo ws = superTile.getBaseInfo(); + if (!PostHandler.doesPlayerKnowNativeWaystone(player, ws)) { + if (!ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.discovered", "", ws.getName()), player); + } + PostHandler.addDiscovered(player.getUniqueID(), ws); + } + } else { + rightClick(hitObj, superTile, player, x, y, z); + } + } + + private boolean preShiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, + int z) { + if (isHitWaystone(hitObj)) { + superTile.destroyWaystone(); + return false; + } else { + return true; + } + } + + protected abstract boolean isHitWaystone(Object hitObj); + + public abstract void clickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, + int z); + + public abstract void rightClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, + int y, int z); + + public abstract void shiftClickWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, + int y, int z); + + public abstract void clickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, + int y, int z); + + public abstract void rightClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, + int x, int y, int z); + + public abstract void shiftClickCalibratedWrench(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, + int x, int y, int z); + + public abstract void clickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, + int z); + + public abstract void rightClickBrush(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, + int y, int z); + + public abstract void click(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, int z); + + public abstract void rightClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, + int z); + + public abstract void shiftClick(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, + int z); + + public abstract void clickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, + int z); + + public abstract void shiftClickBare(Object hitObj, SuperPostPostTile superTile, EntityPlayerMP player, int x, int y, + int z); + + public abstract void sendPostBasesToAll(SuperPostPostTile superTile); + + public abstract void sendPostBasesToServer(SuperPostPostTile superTile); + + public static SuperPostPostTile getSuperTile(World world, int x, int y, int z) { + return (SuperPostPostTile) world.getTileEntity(x, y, z); + } + + public static SuperPostPostTile getSuperTile(MyBlockPos pos) { + TileEntity tile = pos.getTile(); + if (tile == null) { + pos.getWorld() + .getBlock(pos.x, pos.y, pos.z); + tile = pos.getTile(); + } + if (tile instanceof SuperPostPostTile) { + return (SuperPostPostTile) tile; + } + return null; + } + + public static void updateServer(MyBlockPos pos) { + SuperPostPostTile tile = getSuperTile(pos); + if (tile == null) { + return; + } + tile.getSuperBlock() + .sendPostBasesToAll(tile); + } + + public static void updateClient(MyBlockPos pos) { + SuperPostPostTile tile = getSuperTile(pos); + if (tile == null) { + return; + } + tile.getSuperBlock() + .sendPostBasesToServer(tile); + } + + public abstract Object getHitTarget(World world, int x, int y, int z, EntityPlayer/* MP */ player); + + public abstract Paintable getPaintableByHit(SuperPostPostTile tile, Object hit); + + public int getRenderType() { + return -1; + } + + public boolean renderAsNormalBlock() { + return false; + } + + public boolean isOpaqueCube() { + return false; + } + + public static void placeClient(World world, MyBlockPos blockPos, EntityPlayer player) { + getSuperTile(world, blockPos.x, blockPos.y, blockPos.z).owner = player.getUniqueID(); + } + + public static void placeServer(World world, MyBlockPos blockPos, EntityPlayerMP player) { + getSuperTile(world, blockPos.x, blockPos.y, blockPos.z).owner = player.getUniqueID(); + } } diff --git a/src/main/java/gollorum/signpost/blocks/WaystoneContainer.java b/src/main/java/gollorum/signpost/blocks/WaystoneContainer.java index 373fe601..df52311b 100644 --- a/src/main/java/gollorum/signpost/blocks/WaystoneContainer.java +++ b/src/main/java/gollorum/signpost/blocks/WaystoneContainer.java @@ -3,9 +3,11 @@ import gollorum.signpost.util.BaseInfo; public interface WaystoneContainer { - - public String getName(); - public void setName(String name); - public BaseInfo getBaseInfo(); + + public String getName(); + + public void setName(String name); + + public BaseInfo getBaseInfo(); } diff --git a/src/main/java/gollorum/signpost/blocks/tiles/BaseModelPostTile.java b/src/main/java/gollorum/signpost/blocks/tiles/BaseModelPostTile.java index 70b18b60..e62996d1 100644 --- a/src/main/java/gollorum/signpost/blocks/tiles/BaseModelPostTile.java +++ b/src/main/java/gollorum/signpost/blocks/tiles/BaseModelPostTile.java @@ -1,83 +1,86 @@ package gollorum.signpost.blocks.tiles; -import gollorum.signpost.blocks.BaseModelPost.ModelType; -import gollorum.signpost.util.render.ModelObject; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.IModelCustom; -public class BaseModelPostTile extends BasePostTile implements ModelObject{ - - private ModelType typ; - - private static final byte[] facingMatrix = new byte[]{1,0,3,2}; - - public BaseModelPostTile(){ - this(ModelType.MODEL1); - } - - public BaseModelPostTile(ModelType typ){ - super(); - this.typ = typ; - } - - @Override - public IModelCustom getModel() { - return typ.MODEL; - } - - @Override - public ResourceLocation getTexture() { - return typ.TEXTURE; - } - - @Override - public double rotX() { - return 0; - } - - @Override - public double rotY() { - return 1; - } - - @Override - public double rotZ() { - return 0; - } - - @Override - public double getAngle() { - if(getWorldObj()==null){ - return 0; - }else{ - return facingMatrix[getWorldObj().getBlockMetadata(xCoord, yCoord, zCoord)]*90; - } - } - - @Override - public double transX() { - return 0; - } - - @Override - public double transY() { - return 0; - } - - @Override - public double transZ() { - return 0; - } - - @Override - public int getBlockMetadata(){ - try{ - if(getWorldObj()==null){ - return 0; - }else{ - return super.getBlockMetadata(); - } - }catch(NullPointerException e){return 0;} - } - +import gollorum.signpost.blocks.BaseModelPost.ModelType; +import gollorum.signpost.util.render.ModelObject; + +public class BaseModelPostTile extends BasePostTile implements ModelObject { + + private ModelType typ; + + private static final byte[] facingMatrix = new byte[] { 1, 0, 3, 2 }; + + public BaseModelPostTile() { + this(ModelType.MODEL1); + } + + public BaseModelPostTile(ModelType typ) { + super(); + this.typ = typ; + } + + @Override + public IModelCustom getModel() { + return typ.MODEL; + } + + @Override + public ResourceLocation getTexture() { + return typ.TEXTURE; + } + + @Override + public double rotX() { + return 0; + } + + @Override + public double rotY() { + return 1; + } + + @Override + public double rotZ() { + return 0; + } + + @Override + public double getAngle() { + if (getWorldObj() == null) { + return 0; + } else { + return facingMatrix[getWorldObj().getBlockMetadata(xCoord, yCoord, zCoord)] * 90; + } + } + + @Override + public double transX() { + return 0; + } + + @Override + public double transY() { + return 0; + } + + @Override + public double transZ() { + return 0; + } + + @Override + public int getBlockMetadata() { + try { + if (getWorldObj() == null) { + return 0; + } else { + return super.getBlockMetadata(); + } + } catch (NullPointerException e) { + return 0; + } + } + } diff --git a/src/main/java/gollorum/signpost/blocks/tiles/BasePostTile.java b/src/main/java/gollorum/signpost/blocks/tiles/BasePostTile.java index ccc55183..eb841c86 100644 --- a/src/main/java/gollorum/signpost/blocks/tiles/BasePostTile.java +++ b/src/main/java/gollorum/signpost/blocks/tiles/BasePostTile.java @@ -1,5 +1,8 @@ package gollorum.signpost.blocks.tiles; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.MinecraftForge; + import gollorum.signpost.blocks.WaystoneContainer; import gollorum.signpost.event.UpdateWaystoneEvent; import gollorum.signpost.management.PostHandler; @@ -8,65 +11,75 @@ import gollorum.signpost.network.messages.BaseUpdateServerMessage; import gollorum.signpost.util.BaseInfo; import gollorum.signpost.util.MyBlockPos; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.MinecraftForge; public class BasePostTile extends TileEntity implements WaystoneContainer { - public boolean isCanceled = false; + public boolean isCanceled = false; + + public BasePostTile() { + super(); + } + + public BasePostTile setup() { + return this; + } + + public BaseInfo getBaseInfo() { + return PostHandler.getNativeWaystones() + .getByPos(toPos()); + } + + public MyBlockPos toPos() { + return new MyBlockPos(xCoord, yCoord, zCoord, dim()); + } - public BasePostTile() {super();} - - public BasePostTile setup(){ - return this; - } - - public BaseInfo getBaseInfo(){ - return PostHandler.getNativeWaystones().getByPos(toPos()); - } + public int dim() { + if (getWorldObj() == null || getWorldObj().provider == null) { + return Integer.MIN_VALUE; + } else return getWorldObj().provider.dimensionId; + } - public MyBlockPos toPos(){ - return new MyBlockPos(xCoord, yCoord, zCoord, dim()); - } + public void onBlockDestroy(MyBlockPos pos) { + isCanceled = true; + BaseInfo base = getBaseInfo(); + if (PostHandler.getNativeWaystones() + .remove(base)) { + MinecraftForge.EVENT_BUS.post( + new UpdateWaystoneEvent( + UpdateWaystoneEvent.WaystoneEventType.DESTROYED, + getWorldObj(), + xCoord, + yCoord, + zCoord, + base == null ? "" : base.getName())); + NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); + } + } - public int dim(){ - if(getWorldObj()==null||getWorldObj().provider==null){ - return Integer.MIN_VALUE; - }else - return getWorldObj().provider.dimensionId; - } - - public void onBlockDestroy(MyBlockPos pos) { - isCanceled = true; - BaseInfo base = getBaseInfo(); - if(PostHandler.getNativeWaystones().remove(base)){ - MinecraftForge.EVENT_BUS.post(new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.DESTROYED, getWorldObj(), xCoord, yCoord, zCoord, base==null?"":base.getName())); - NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); - } - } + @Override + public void setName(String name) { + BaseInfo bi = getBaseInfo(); + bi.setName(name); + NetworkHandler.netWrap.sendToServer(new BaseUpdateServerMessage(bi, false)); + } - @Override - public void setName(String name) { - BaseInfo bi = getBaseInfo(); - bi.setName(name); - NetworkHandler.netWrap.sendToServer(new BaseUpdateServerMessage(bi, false)); - } + @Override + public String getName() { + BaseInfo ws = getBaseInfo(); + return ws == null ? "null" : getBaseInfo().toString(); + } - @Override - public String getName() { - BaseInfo ws = getBaseInfo(); - return ws == null ? "null" : getBaseInfo().toString(); - } + @Override + public String toString() { + return getName(); + } - @Override - public String toString() { - return getName(); - } - - @Override - public int getBlockMetadata(){ - try{ - return super.getBlockMetadata(); - }catch(NullPointerException e){return 0;} - } + @Override + public int getBlockMetadata() { + try { + return super.getBlockMetadata(); + } catch (NullPointerException e) { + return 0; + } + } } diff --git a/src/main/java/gollorum/signpost/blocks/tiles/BigPostPostTile.java b/src/main/java/gollorum/signpost/blocks/tiles/BigPostPostTile.java index 2e0e6248..8bf66994 100644 --- a/src/main/java/gollorum/signpost/blocks/tiles/BigPostPostTile.java +++ b/src/main/java/gollorum/signpost/blocks/tiles/BigPostPostTile.java @@ -3,6 +3,12 @@ import java.util.LinkedList; import java.util.List; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; + import gollorum.signpost.SPEventHandler; import gollorum.signpost.blocks.BigPostPost; import gollorum.signpost.blocks.BigPostPost.BigHit; @@ -19,206 +25,217 @@ import gollorum.signpost.util.Paintable; import gollorum.signpost.util.Sign; import gollorum.signpost.util.Sign.OverlayType; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; public class BigPostPostTile extends SuperPostPostTile { - public BigPostType type = BigPostType.OAK; - public static final int DESCRIPTIONLENGTH = 4; - private boolean isLoading = false; - - @Deprecated - public BigBaseInfo bases = null; - - public BigPostPostTile(){super();} - - public BigPostPostTile(BigPostType type){ - this(); - this.type = type; - } - - public BigBaseInfo getBases(){ - BigBaseInfo bases = PostHandler.getBigPosts().get(toPos()); - if(bases==null){ - bases = new BigBaseInfo(type.texture, type.resLocMain); - PostHandler.getBigPosts().put(toPos(), bases); - } else { - if (bases.sign != null && bases.sign.base != null && bases.sign.base.teleportPosition == null) { - BaseInfo newBase = PostHandler.getWSbyName(bases.sign.base.getName()); - if (newBase != null) { - bases.sign.base = newBase; - } - } - } - this.bases = bases; - return bases; - } - - @Override - public void onBlockDestroy(MyBlockPos pos) { - super.onBlockDestroy(pos); - isCanceled = true; - BigBaseInfo bases = getBases(); - if(bases.sign.overlay!=null){ - EntityItem item = new EntityItem(getWorldObj(), pos.x, pos.y, pos.z, new ItemStack(bases.sign.overlay.item, 1)); - getWorldObj().spawnEntityInWorld(item); - } - if(PostHandler.getBigPosts().remove(pos)!=null){ - NetworkHandler.netWrap.sendToAll(new SendAllBigPostBasesMessage()); - } - } - - @Override - public void save(NBTTagCompound tagCompound) { - BigBaseInfo bases = getBases(); - tagCompound.setString("base", ""+bases.sign.base); - tagCompound.setInteger("rot", bases.sign.rotation); - tagCompound.setBoolean("flip", bases.sign.flip); - tagCompound.setString("overlay", ""+bases.sign.overlay); - tagCompound.setBoolean("point", bases.sign.point); - tagCompound.setString("paint", locToString(bases.sign.paint)); - tagCompound.setString("postPaint", locToString(bases.postPaint)); - for(int i=0; i getEmptySigns() { - List ret = new LinkedList(); - BigBaseInfo bases = getBases(); - if(bases.sign == null && !bases.sign.isValid()){ - ret.add(bases.sign); - } - return ret; - } -} \ No newline at end of file + public BigPostType type = BigPostType.OAK; + public static final int DESCRIPTIONLENGTH = 4; + private boolean isLoading = false; + + @Deprecated + public BigBaseInfo bases = null; + + public BigPostPostTile() { + super(); + } + + public BigPostPostTile(BigPostType type) { + this(); + this.type = type; + } + + public BigBaseInfo getBases() { + BigBaseInfo bases = PostHandler.getBigPosts() + .get(toPos()); + if (bases == null) { + bases = new BigBaseInfo(type.texture, type.resLocMain); + PostHandler.getBigPosts() + .put(toPos(), bases); + } else { + if (bases.sign != null && bases.sign.base != null && bases.sign.base.teleportPosition == null) { + BaseInfo newBase = PostHandler.getWSbyName(bases.sign.base.getName()); + if (newBase != null) { + bases.sign.base = newBase; + } + } + } + this.bases = bases; + return bases; + } + + @Override + public void onBlockDestroy(MyBlockPos pos) { + super.onBlockDestroy(pos); + isCanceled = true; + BigBaseInfo bases = getBases(); + if (bases.sign.overlay != null) { + EntityItem item = new EntityItem( + getWorldObj(), + pos.x, + pos.y, + pos.z, + new ItemStack(bases.sign.overlay.item, 1)); + getWorldObj().spawnEntityInWorld(item); + } + if (PostHandler.getBigPosts() + .remove(pos) != null) { + NetworkHandler.netWrap.sendToAll(new SendAllBigPostBasesMessage()); + } + } + + @Override + public void save(NBTTagCompound tagCompound) { + BigBaseInfo bases = getBases(); + tagCompound.setString("base", "" + bases.sign.base); + tagCompound.setInteger("rot", bases.sign.rotation); + tagCompound.setBoolean("flip", bases.sign.flip); + tagCompound.setString("overlay", "" + bases.sign.overlay); + tagCompound.setBoolean("point", bases.sign.point); + tagCompound.setString("paint", locToString(bases.sign.paint)); + tagCompound.setString("postPaint", locToString(bases.postPaint)); + for (int i = 0; i < bases.description.length; i++) { + tagCompound.setString("description" + i, bases.description[i]); + } + if (bases.equals(getPaintObject())) { + tagCompound.setByte("paintObjectIndex", (byte) 1); + } else if (bases.sign.equals(getPaintObject())) { + tagCompound.setByte("paintObjectIndex", (byte) 2); + } else { + tagCompound.setByte("paintObjectIndex", (byte) 0); + } + } + + @Override + public void load(NBTTagCompound tagCompound) { + isLoading = true; + final String base = tagCompound.getString("base"); + final int rotation = tagCompound.getInteger("rot"); + final boolean flip = tagCompound.getBoolean("flip"); + final OverlayType overlay = OverlayType.get(tagCompound.getString("overlay")); + final boolean point = tagCompound.getBoolean("point"); + final String[] description = new String[DESCRIPTIONLENGTH]; + final String paint = tagCompound.getString("paint"); + final String postPaint = tagCompound.getString("postPaint"); + + for (int i = 0; i < DESCRIPTIONLENGTH; i++) { + description[i] = tagCompound.getString("description" + i); + } + final byte paintObjectIndex = tagCompound.getByte("paintObjectIndex"); + + SPEventHandler.scheduleTask(new BoolRun() { + + @Override + public boolean run() { + if (getWorldObj() == null) { + return false; + } else { + if (getWorldObj().isRemote) { + return true; + } + BigBaseInfo bases = getBases(); + bases.sign.base = PostHandler.getForceWSbyName(base); + bases.sign.rotation = rotation; + bases.sign.flip = flip; + bases.sign.overlay = overlay; + bases.sign.point = point; + bases.description = description; + bases.sign.paint = stringToLoc(paint); + bases.postPaint = postPaint == null || postPaint.equals("") + || postPaint.equals("null") + || postPaint.equals("minecraft:") ? type.resLocMain : stringToLoc(postPaint); + switch (paintObjectIndex) { + case 1: + bases.paintObject = bases; + bases.awaitingPaint = true; + break; + case 2: + bases.paintObject = bases.sign; + bases.awaitingPaint = true; + break; + default: + bases.paintObject = null; + bases.awaitingPaint = false; + break; + } + NetworkHandler.netWrap.sendToAll( + new SendBigPostBasesMessage( + (BigPostPostTile) getWorldObj().getTileEntity(xCoord, yCoord, zCoord), + bases)); + isLoading = false; + return true; + } + } + }); + } + + public boolean isLoading() { + return isLoading; + } + + @Override + public Sign getSign(EntityPlayer player) { + BigBaseInfo bases = getBases(); + BigHit hit = (BigHit) ((BigPostPost) blockType).getHitTarget(getWorldObj(), xCoord, yCoord, zCoord, player); + if (hit.target.equals(BigHitTarget.BASE)) { + return bases.sign; + } else { + return null; + } + } + + @Override + public Paintable getPaintable(EntityPlayer player) { + BigBaseInfo bases = getBases(); + BigHit hit = (BigHit) ((BigPostPost) getBlockType()) + .getHitTarget(getWorldObj(), xCoord, yCoord, zCoord, player); + if (hit.target.equals(BigHitTarget.BASE)) { + return bases.sign; + } else { + return bases; + } + } + + @Override + public ResourceLocation getPostPaint() { + return getBases().postPaint; + } + + public void setPostPaint(ResourceLocation loc) { + getBases().postPaint = loc; + } + + @Override + public boolean isAwaitingPaint() { + return getBases().awaitingPaint; + } + + @Override + public Paintable getPaintObject() { + return getBases().paintObject; + } + + @Override + public void setAwaitingPaint(boolean awaitingPaint) { + getBases().awaitingPaint = awaitingPaint; + } + + @Override + public void setPaintObject(Paintable paintObject) { + getBases().paintObject = paintObject; + } + + @Override + public String toString() { + return getBases() + " at " + toPos(); + } + + @Override + public List getEmptySigns() { + List ret = new LinkedList(); + BigBaseInfo bases = getBases(); + if (bases.sign == null && !bases.sign.isValid()) { + ret.add(bases.sign); + } + return ret; + } +} diff --git a/src/main/java/gollorum/signpost/blocks/tiles/PostPostTile.java b/src/main/java/gollorum/signpost/blocks/tiles/PostPostTile.java index 09ae07d2..13ed19e0 100644 --- a/src/main/java/gollorum/signpost/blocks/tiles/PostPostTile.java +++ b/src/main/java/gollorum/signpost/blocks/tiles/PostPostTile.java @@ -3,6 +3,12 @@ import java.util.LinkedList; import java.util.List; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ResourceLocation; + import gollorum.signpost.SPEventHandler; import gollorum.signpost.blocks.PostPost; import gollorum.signpost.blocks.PostPost.Hit; @@ -19,246 +25,260 @@ import gollorum.signpost.util.Paintable; import gollorum.signpost.util.Sign; import gollorum.signpost.util.Sign.OverlayType; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; public class PostPostTile extends SuperPostPostTile { - public PostType type = PostType.OAK; - private boolean isLoading = false; - - @Deprecated - public DoubleBaseInfo bases = null; - - public PostPostTile(){super();} - - public PostPostTile(PostType type){ - this(); - this.type = type; - } - - public DoubleBaseInfo getBases(){ - DoubleBaseInfo bases = PostHandler.getPosts().get(toPos()); - if(bases==null){ - bases = new DoubleBaseInfo(type.texture, type.resLocMain); - PostHandler.getPosts().put(toPos(), bases); - }else{ - if(bases.sign1!=null && bases.sign1.base!=null && bases.sign1.base.teleportPosition ==null){ - BaseInfo newBase = PostHandler.getWSbyName(bases.sign1.base.getName()); - if(newBase!=null){ - bases.sign1.base = newBase; - } - } - if(bases.sign2!=null && bases.sign2.base!=null && bases.sign2.base.teleportPosition ==null){ - BaseInfo newBase = PostHandler.getWSbyName(bases.sign2.base.getName()); - if(newBase!=null){ - bases.sign2.base = newBase; - } - } - } - return this.bases = bases; - } - - @Override - public void onBlockDestroy(MyBlockPos pos) { - super.onBlockDestroy(pos); - isCanceled = true; - DoubleBaseInfo bases = getBases(); - if(bases.sign1.overlay!=null){ - EntityItem item = new EntityItem(getWorldObj(), pos.x, pos.y, pos.z, new ItemStack(bases.sign1.overlay.item, 1)); - getWorldObj().spawnEntityInWorld(item); - } - if(bases.sign2.overlay!=null){ - EntityItem item = new EntityItem(getWorldObj(), pos.x, pos.y, pos.z, new ItemStack(bases.sign2.overlay.item, 1)); - getWorldObj().spawnEntityInWorld(item); - } - if(PostHandler.getPosts().remove(pos)!=null){ - NetworkHandler.netWrap.sendToAll(new SendAllPostBasesMessage()); - } - } - - @Override - public void save(NBTTagCompound tagCompound) { - DoubleBaseInfo bases = getBases(); - tagCompound.setString("base1", ""+bases.sign1.base); - tagCompound.setString("base2", ""+bases.sign2.base); - tagCompound.setInteger("rot1", bases.sign1.rotation); - tagCompound.setInteger("rot2", bases.sign2.rotation); - tagCompound.setBoolean("flip1", bases.sign1.flip); - tagCompound.setBoolean("flip2", bases.sign2.flip); - tagCompound.setString("overlay1", ""+bases.sign1.overlay); - tagCompound.setString("overlay2", ""+bases.sign2.overlay); - tagCompound.setBoolean("point1", bases.sign1.point); - tagCompound.setBoolean("point2", bases.sign2.point); - tagCompound.setString("paint1", SuperPostPostTile.locToString(bases.sign1.paint)); - tagCompound.setString("paint2", SuperPostPostTile.locToString(bases.sign2.paint)); - tagCompound.setString("postPaint", SuperPostPostTile.locToString(bases.postPaint)); - - if(bases.equals(bases.paintObject)){ - tagCompound.setByte("paintObjectIndex", (byte)1); - }else if(bases.sign1.equals(bases.paintObject)){ - tagCompound.setByte("paintObjectIndex", (byte)2); - }else if(bases.sign2.equals(bases.paintObject)){ - tagCompound.setByte("paintObjectIndex", (byte)3); - }else{ - tagCompound.setByte("paintObjectIndex", (byte)0); - } - } - - @Override - public void load(NBTTagCompound tagCompound) { - isLoading = true; - final String base1 = tagCompound.getString("base1"); - final String base2 = tagCompound.getString("base2"); - - final int rotation1 = tagCompound.getInteger("rot1"); - final int rotation2 = tagCompound.getInteger("rot2"); - - final boolean flip1 = tagCompound.getBoolean("flip1"); - final boolean flip2 = tagCompound.getBoolean("flip2"); - - final OverlayType overlay1 = OverlayType.get(tagCompound.getString("overlay1")); - final OverlayType overlay2 = OverlayType.get(tagCompound.getString("overlay2")); - - final boolean point1 = tagCompound.getBoolean("point1"); - final boolean point2 = tagCompound.getBoolean("point2"); - - final String paint1 = tagCompound.getString("paint1"); - final String paint2 = tagCompound.getString("paint2"); - - final String postPaint = tagCompound.getString("postPaint"); - - final byte paintObjectIndex = tagCompound.getByte("paintObjectIndex"); - - SPEventHandler.scheduleTask(new BoolRun(){ - @Override - public boolean run() { - if(getWorldObj()==null){ - return false; - }else{ - if(getWorldObj().isRemote){ - return true; - } - DoubleBaseInfo bases = getBases(); - bases.sign1.base = PostHandler.getForceWSbyName(base1); - bases.sign2.base = PostHandler.getForceWSbyName(base2); - bases.sign1.rotation = rotation1; - bases.sign2.rotation = rotation2; - bases.sign1.flip = flip1; - bases.sign2.flip = flip2; - bases.sign1.overlay = overlay1; - bases.sign2.overlay = overlay2; - bases.sign1.point = point1; - bases.sign2.point = point2; - bases.sign1.paint = stringToLoc(paint1); - bases.sign2.paint = stringToLoc(paint2); - bases.postPaint = postPaint==null || postPaint.equals("") || postPaint.equals("null") || postPaint.equals("minecraft:") ? type.resLocMain : stringToLoc(postPaint); - - switch(paintObjectIndex){ - case 1: - bases.paintObject = bases; - bases.awaitingPaint = true; - break; - case 2: - bases.paintObject = bases.sign1; - bases.awaitingPaint = true; - break; - case 3: - bases.paintObject = bases.sign2; - bases.awaitingPaint = true; - break; - default: - bases.paintObject = null; - bases.awaitingPaint = false; - break; - } - NetworkHandler.netWrap.sendToAll(new SendPostBasesMessage((PostPostTile) getWorldObj().getTileEntity(xCoord, yCoord, zCoord), bases)); - isLoading = false; - return true; - } - } - }); - } - - public boolean isLoading(){ - return isLoading; - } - - @Override - public Sign getSign(EntityPlayer player) { - DoubleBaseInfo bases = getBases(); - Hit hit = (Hit) ((PostPost)blockType).getHitTarget(getWorldObj(), xCoord, yCoord, zCoord, player); - if(hit.target.equals(HitTarget.BASE1)){ - return bases.sign1; - }else if(hit.target.equals(HitTarget.BASE2)){ - return bases.sign2; - }else{ - return null; - } - } - - @Override - public Paintable getPaintable(EntityPlayer player) { - DoubleBaseInfo bases = getBases(); - Hit hit = (Hit) ((PostPost)getBlockType()).getHitTarget(getWorldObj(), xCoord, yCoord, zCoord, player); - if(hit.target.equals(HitTarget.BASE1)){ - return bases.sign1; - }else if(hit.target.equals(HitTarget.BASE2)){ - return bases.sign2; - }else{ - return bases; - } - } - - @Override - public ResourceLocation getPostPaint(){ - return getBases().postPaint; - } - - public void setPostPaint(ResourceLocation loc){ - getBases().postPaint = loc; - } - - @Override - public boolean isAwaitingPaint() { - return getBases().awaitingPaint; - } - - - @Override - public Paintable getPaintObject() { - return getBases().paintObject; - } - - @Override - public void setAwaitingPaint(boolean awaitingPaint){ - getBases().awaitingPaint = awaitingPaint; - } - - @Override - public void setPaintObject(Paintable paintObject){ - getBases().paintObject = paintObject; - } - - @Override - public String toString(){ - return getBases()+" at "+toPos(); - } - - - @Override - public List getEmptySigns() { - List ret = new LinkedList(); - DoubleBaseInfo bases = getBases(); - if(bases.sign1 == null || !bases.sign1.isValid()){ - ret.add(bases.sign1); - } - if(bases.sign2 == null || !bases.sign2.isValid()){ - ret.add(bases.sign2); - } - return ret; - } + public PostType type = PostType.OAK; + private boolean isLoading = false; + + @Deprecated + public DoubleBaseInfo bases = null; + + public PostPostTile() { + super(); + } + + public PostPostTile(PostType type) { + this(); + this.type = type; + } + + public DoubleBaseInfo getBases() { + DoubleBaseInfo bases = PostHandler.getPosts() + .get(toPos()); + if (bases == null) { + bases = new DoubleBaseInfo(type.texture, type.resLocMain); + PostHandler.getPosts() + .put(toPos(), bases); + } else { + if (bases.sign1 != null && bases.sign1.base != null && bases.sign1.base.teleportPosition == null) { + BaseInfo newBase = PostHandler.getWSbyName(bases.sign1.base.getName()); + if (newBase != null) { + bases.sign1.base = newBase; + } + } + if (bases.sign2 != null && bases.sign2.base != null && bases.sign2.base.teleportPosition == null) { + BaseInfo newBase = PostHandler.getWSbyName(bases.sign2.base.getName()); + if (newBase != null) { + bases.sign2.base = newBase; + } + } + } + return this.bases = bases; + } + + @Override + public void onBlockDestroy(MyBlockPos pos) { + super.onBlockDestroy(pos); + isCanceled = true; + DoubleBaseInfo bases = getBases(); + if (bases.sign1.overlay != null) { + EntityItem item = new EntityItem( + getWorldObj(), + pos.x, + pos.y, + pos.z, + new ItemStack(bases.sign1.overlay.item, 1)); + getWorldObj().spawnEntityInWorld(item); + } + if (bases.sign2.overlay != null) { + EntityItem item = new EntityItem( + getWorldObj(), + pos.x, + pos.y, + pos.z, + new ItemStack(bases.sign2.overlay.item, 1)); + getWorldObj().spawnEntityInWorld(item); + } + if (PostHandler.getPosts() + .remove(pos) != null) { + NetworkHandler.netWrap.sendToAll(new SendAllPostBasesMessage()); + } + } + + @Override + public void save(NBTTagCompound tagCompound) { + DoubleBaseInfo bases = getBases(); + tagCompound.setString("base1", "" + bases.sign1.base); + tagCompound.setString("base2", "" + bases.sign2.base); + tagCompound.setInteger("rot1", bases.sign1.rotation); + tagCompound.setInteger("rot2", bases.sign2.rotation); + tagCompound.setBoolean("flip1", bases.sign1.flip); + tagCompound.setBoolean("flip2", bases.sign2.flip); + tagCompound.setString("overlay1", "" + bases.sign1.overlay); + tagCompound.setString("overlay2", "" + bases.sign2.overlay); + tagCompound.setBoolean("point1", bases.sign1.point); + tagCompound.setBoolean("point2", bases.sign2.point); + tagCompound.setString("paint1", SuperPostPostTile.locToString(bases.sign1.paint)); + tagCompound.setString("paint2", SuperPostPostTile.locToString(bases.sign2.paint)); + tagCompound.setString("postPaint", SuperPostPostTile.locToString(bases.postPaint)); + + if (bases.equals(bases.paintObject)) { + tagCompound.setByte("paintObjectIndex", (byte) 1); + } else if (bases.sign1.equals(bases.paintObject)) { + tagCompound.setByte("paintObjectIndex", (byte) 2); + } else if (bases.sign2.equals(bases.paintObject)) { + tagCompound.setByte("paintObjectIndex", (byte) 3); + } else { + tagCompound.setByte("paintObjectIndex", (byte) 0); + } + } + + @Override + public void load(NBTTagCompound tagCompound) { + isLoading = true; + final String base1 = tagCompound.getString("base1"); + final String base2 = tagCompound.getString("base2"); + + final int rotation1 = tagCompound.getInteger("rot1"); + final int rotation2 = tagCompound.getInteger("rot2"); + + final boolean flip1 = tagCompound.getBoolean("flip1"); + final boolean flip2 = tagCompound.getBoolean("flip2"); + + final OverlayType overlay1 = OverlayType.get(tagCompound.getString("overlay1")); + final OverlayType overlay2 = OverlayType.get(tagCompound.getString("overlay2")); + + final boolean point1 = tagCompound.getBoolean("point1"); + final boolean point2 = tagCompound.getBoolean("point2"); + + final String paint1 = tagCompound.getString("paint1"); + final String paint2 = tagCompound.getString("paint2"); + + final String postPaint = tagCompound.getString("postPaint"); + + final byte paintObjectIndex = tagCompound.getByte("paintObjectIndex"); + + SPEventHandler.scheduleTask(new BoolRun() { + + @Override + public boolean run() { + if (getWorldObj() == null) { + return false; + } else { + if (getWorldObj().isRemote) { + return true; + } + DoubleBaseInfo bases = getBases(); + bases.sign1.base = PostHandler.getForceWSbyName(base1); + bases.sign2.base = PostHandler.getForceWSbyName(base2); + bases.sign1.rotation = rotation1; + bases.sign2.rotation = rotation2; + bases.sign1.flip = flip1; + bases.sign2.flip = flip2; + bases.sign1.overlay = overlay1; + bases.sign2.overlay = overlay2; + bases.sign1.point = point1; + bases.sign2.point = point2; + bases.sign1.paint = stringToLoc(paint1); + bases.sign2.paint = stringToLoc(paint2); + bases.postPaint = postPaint == null || postPaint.equals("") + || postPaint.equals("null") + || postPaint.equals("minecraft:") ? type.resLocMain : stringToLoc(postPaint); + + switch (paintObjectIndex) { + case 1: + bases.paintObject = bases; + bases.awaitingPaint = true; + break; + case 2: + bases.paintObject = bases.sign1; + bases.awaitingPaint = true; + break; + case 3: + bases.paintObject = bases.sign2; + bases.awaitingPaint = true; + break; + default: + bases.paintObject = null; + bases.awaitingPaint = false; + break; + } + NetworkHandler.netWrap.sendToAll( + new SendPostBasesMessage( + (PostPostTile) getWorldObj().getTileEntity(xCoord, yCoord, zCoord), + bases)); + isLoading = false; + return true; + } + } + }); + } + + public boolean isLoading() { + return isLoading; + } + + @Override + public Sign getSign(EntityPlayer player) { + DoubleBaseInfo bases = getBases(); + Hit hit = (Hit) ((PostPost) blockType).getHitTarget(getWorldObj(), xCoord, yCoord, zCoord, player); + if (hit.target.equals(HitTarget.BASE1)) { + return bases.sign1; + } else if (hit.target.equals(HitTarget.BASE2)) { + return bases.sign2; + } else { + return null; + } + } + + @Override + public Paintable getPaintable(EntityPlayer player) { + DoubleBaseInfo bases = getBases(); + Hit hit = (Hit) ((PostPost) getBlockType()).getHitTarget(getWorldObj(), xCoord, yCoord, zCoord, player); + if (hit.target.equals(HitTarget.BASE1)) { + return bases.sign1; + } else if (hit.target.equals(HitTarget.BASE2)) { + return bases.sign2; + } else { + return bases; + } + } + + @Override + public ResourceLocation getPostPaint() { + return getBases().postPaint; + } + + public void setPostPaint(ResourceLocation loc) { + getBases().postPaint = loc; + } + + @Override + public boolean isAwaitingPaint() { + return getBases().awaitingPaint; + } + + @Override + public Paintable getPaintObject() { + return getBases().paintObject; + } + + @Override + public void setAwaitingPaint(boolean awaitingPaint) { + getBases().awaitingPaint = awaitingPaint; + } + + @Override + public void setPaintObject(Paintable paintObject) { + getBases().paintObject = paintObject; + } + + @Override + public String toString() { + return getBases() + " at " + toPos(); + } + + @Override + public List getEmptySigns() { + List ret = new LinkedList(); + DoubleBaseInfo bases = getBases(); + if (bases.sign1 == null || !bases.sign1.isValid()) { + ret.add(bases.sign1); + } + if (bases.sign2 == null || !bases.sign2.isValid()) { + ret.add(bases.sign2); + } + return ret; + } } diff --git a/src/main/java/gollorum/signpost/blocks/tiles/SuperPostPostTile.java b/src/main/java/gollorum/signpost/blocks/tiles/SuperPostPostTile.java index 1b0117a3..b59a4451 100644 --- a/src/main/java/gollorum/signpost/blocks/tiles/SuperPostPostTile.java +++ b/src/main/java/gollorum/signpost/blocks/tiles/SuperPostPostTile.java @@ -1,5 +1,16 @@ package gollorum.signpost.blocks.tiles; +import java.util.List; +import java.util.UUID; + +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.MinecraftForge; + import gollorum.signpost.BlockHandler; import gollorum.signpost.SPEventHandler; import gollorum.signpost.blocks.SuperPostPost; @@ -13,150 +24,159 @@ import gollorum.signpost.util.MyBlockPos; import gollorum.signpost.util.Paintable; import gollorum.signpost.util.Sign; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.MinecraftForge; - -import java.util.List; -import java.util.UUID; -public abstract class SuperPostPostTile extends TileEntity implements WaystoneContainer{ - - public boolean isItem = false; - public boolean isCanceled = false; - public UUID owner; - - @Deprecated - public boolean isWaystone = false; - - public SuperPostPostTile(){ - SPEventHandler.scheduleTask(() -> { - if(getWorldObj()==null){ - return false; - }else{ - isWaystone(); - return true; - } - }); - } - - public final MyBlockPos toPos(){ - return new MyBlockPos(xCoord, yCoord, zCoord, dim()); - } - - public final int dim(){ - if(getWorldObj()==null||getWorldObj().provider==null){ - return Integer.MIN_VALUE; - }else - return getWorldObj().provider.dimensionId; - } - - public static final ResourceLocation stringToLoc(String str){ - return str==null||str.equals("null")||str.equals("")?null:new ResourceLocation(str); - } - - public static final String locToString(ResourceLocation loc){ - return loc==null?"null":loc.getResourceDomain()+":"+loc.getResourcePath(); - } - - public void onBlockDestroy(MyBlockPos pos){ - if(isWaystone()){ - destroyWaystone(); - } - } - - public boolean isWaystone(){ - return isWaystone = (getBaseInfo()!=null); - } - - public void destroyWaystone(){ - MyBlockPos pos = toPos(); - isWaystone = false; - EntityItem item = new EntityItem(getWorldObj(), pos.x, pos.y, pos.z, new ItemStack(BlockHandler.base, 1)); - getWorldObj().spawnEntityInWorld(item); - BaseInfo base = PostHandler.getNativeWaystones().getByPos(pos); - SPEventHandler.INSTANCE.updateWaystoneCount(this); - if(PostHandler.getNativeWaystones().removeByPos(pos)){ - MinecraftForge.EVENT_BUS.post(new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.DESTROYED, getWorldObj(), base.teleportPosition.x, base.teleportPosition.y, base.teleportPosition.z, base==null?"":base.getName())); - NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); - } - } - - @Override - public void writeToNBT(NBTTagCompound tagCompound) { - super.writeToNBT(tagCompound); - tagCompound.setInteger("signpostNBTVersion", 1); - NBTTagCompound tagComp = new NBTTagCompound(); - if(!(owner == null)){ - tagComp.setString("PostOwner", owner.toString()); - } - save(tagComp); - tagCompound.setTag("signpostDataTag", tagComp); - } - - @Override - public void readFromNBT(NBTTagCompound tagCompound) { - super.readFromNBT(tagCompound); - if(tagCompound.getInteger("signpostNBTVersion")==1){ - NBTTagCompound tagComp = (NBTTagCompound) tagCompound.getTag("signpostDataTag"); - String owner = tagComp.getString("PostOwner"); - try{ - this.owner = owner==null ? null : UUID.fromString(owner); - }catch(Exception e){ - this.owner = null; - } - load(tagComp); - }else{ - load(tagCompound); - } - } - - public abstract void save(NBTTagCompound tagCompound); - public abstract void load(NBTTagCompound tagCompound); - - public abstract Sign getSign(EntityPlayer player); - public abstract Paintable getPaintable(EntityPlayer player); - public abstract ResourceLocation getPostPaint(); - public abstract void setPostPaint(ResourceLocation loc); - - public abstract boolean isAwaitingPaint(); - public abstract Paintable getPaintObject(); - public abstract void setAwaitingPaint(boolean awaitingPaint); - public abstract void setPaintObject(Paintable paintObject); - - public abstract boolean isLoading(); - - public abstract List getEmptySigns(); - - public SuperPostPost getSuperBlock(){ - return (SuperPostPost) this.getBlockType(); - } - - public BaseInfo getBaseInfo(){ - return PostHandler.getNativeWaystones().getByPos(toPos()); - } - - @Override - public void setName(String name) { - BaseInfo ws = getBaseInfo(); - ws.setName(name); - NetworkHandler.netWrap.sendToServer(new BaseUpdateServerMessage(ws, false)); - } - - @Override - public String getName() { - BaseInfo ws = getBaseInfo(); - return ws == null ? "null" : getBaseInfo().toString(); - } - - @Override - public int getBlockMetadata(){ - try{ - return super.getBlockMetadata(); - }catch(NullPointerException e){System.out.println(getClass());return 0;} - } +public abstract class SuperPostPostTile extends TileEntity implements WaystoneContainer { + + public boolean isItem = false; + public boolean isCanceled = false; + public UUID owner; + + @Deprecated + public boolean isWaystone = false; + + public SuperPostPostTile() { + SPEventHandler.scheduleTask(() -> { + if (getWorldObj() == null) { + return false; + } else { + isWaystone(); + return true; + } + }); + } + + public final MyBlockPos toPos() { + return new MyBlockPos(xCoord, yCoord, zCoord, dim()); + } + + public final int dim() { + if (getWorldObj() == null || getWorldObj().provider == null) { + return Integer.MIN_VALUE; + } else return getWorldObj().provider.dimensionId; + } + + public static final ResourceLocation stringToLoc(String str) { + return str == null || str.equals("null") || str.equals("") ? null : new ResourceLocation(str); + } + + public static final String locToString(ResourceLocation loc) { + return loc == null ? "null" : loc.getResourceDomain() + ":" + loc.getResourcePath(); + } + + public void onBlockDestroy(MyBlockPos pos) { + if (isWaystone()) { + destroyWaystone(); + } + } + + public boolean isWaystone() { + return isWaystone = (getBaseInfo() != null); + } + + public void destroyWaystone() { + MyBlockPos pos = toPos(); + isWaystone = false; + EntityItem item = new EntityItem(getWorldObj(), pos.x, pos.y, pos.z, new ItemStack(BlockHandler.base, 1)); + getWorldObj().spawnEntityInWorld(item); + BaseInfo base = PostHandler.getNativeWaystones() + .getByPos(pos); + SPEventHandler.INSTANCE.updateWaystoneCount(this); + if (PostHandler.getNativeWaystones() + .removeByPos(pos)) { + MinecraftForge.EVENT_BUS.post( + new UpdateWaystoneEvent( + UpdateWaystoneEvent.WaystoneEventType.DESTROYED, + getWorldObj(), + base.teleportPosition.x, + base.teleportPosition.y, + base.teleportPosition.z, + base == null ? "" : base.getName())); + NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); + } + } + + @Override + public void writeToNBT(NBTTagCompound tagCompound) { + super.writeToNBT(tagCompound); + tagCompound.setInteger("signpostNBTVersion", 1); + NBTTagCompound tagComp = new NBTTagCompound(); + if (!(owner == null)) { + tagComp.setString("PostOwner", owner.toString()); + } + save(tagComp); + tagCompound.setTag("signpostDataTag", tagComp); + } + + @Override + public void readFromNBT(NBTTagCompound tagCompound) { + super.readFromNBT(tagCompound); + if (tagCompound.getInteger("signpostNBTVersion") == 1) { + NBTTagCompound tagComp = (NBTTagCompound) tagCompound.getTag("signpostDataTag"); + String owner = tagComp.getString("PostOwner"); + try { + this.owner = owner == null ? null : UUID.fromString(owner); + } catch (Exception e) { + this.owner = null; + } + load(tagComp); + } else { + load(tagCompound); + } + } + + public abstract void save(NBTTagCompound tagCompound); + + public abstract void load(NBTTagCompound tagCompound); + + public abstract Sign getSign(EntityPlayer player); + + public abstract Paintable getPaintable(EntityPlayer player); + + public abstract ResourceLocation getPostPaint(); + + public abstract void setPostPaint(ResourceLocation loc); + + public abstract boolean isAwaitingPaint(); + + public abstract Paintable getPaintObject(); + + public abstract void setAwaitingPaint(boolean awaitingPaint); + + public abstract void setPaintObject(Paintable paintObject); + + public abstract boolean isLoading(); + + public abstract List getEmptySigns(); + + public SuperPostPost getSuperBlock() { + return (SuperPostPost) this.getBlockType(); + } + + public BaseInfo getBaseInfo() { + return PostHandler.getNativeWaystones() + .getByPos(toPos()); + } + + @Override + public void setName(String name) { + BaseInfo ws = getBaseInfo(); + ws.setName(name); + NetworkHandler.netWrap.sendToServer(new BaseUpdateServerMessage(ws, false)); + } + + @Override + public String getName() { + BaseInfo ws = getBaseInfo(); + return ws == null ? "null" : getBaseInfo().toString(); + } + + @Override + public int getBlockMetadata() { + try { + return super.getBlockMetadata(); + } catch (NullPointerException e) { + System.out.println(getClass()); + return 0; + } + } } diff --git a/src/main/java/gollorum/signpost/commands/ConfirmTeleportCommand.java b/src/main/java/gollorum/signpost/commands/ConfirmTeleportCommand.java index c7c1e86b..73b44372 100644 --- a/src/main/java/gollorum/signpost/commands/ConfirmTeleportCommand.java +++ b/src/main/java/gollorum/signpost/commands/ConfirmTeleportCommand.java @@ -1,39 +1,41 @@ package gollorum.signpost.commands; -import gollorum.signpost.SPEventHandler; -import gollorum.signpost.management.PostHandler; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +import gollorum.signpost.SPEventHandler; +import gollorum.signpost.management.PostHandler; + public class ConfirmTeleportCommand extends CommandBase { - @Override - public String getCommandName() { - return "signpostconfirm"; - } - - @Override - public String getCommandUsage(ICommandSender p_71518_1_) { - return "/signpostconfirm"; - } - - @Override - public void processCommand(final ICommandSender sender, String[] args) { - if(sender instanceof EntityPlayerMP){ - SPEventHandler.scheduleTask(new Runnable(){ - @Override - public void run() { - PostHandler.confirm((EntityPlayerMP) sender); - } - }, 0); - } - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return sender instanceof EntityPlayer; + @Override + public String getCommandName() { + return "signpostconfirm"; + } + + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/signpostconfirm"; + } + + @Override + public void processCommand(final ICommandSender sender, String[] args) { + if (sender instanceof EntityPlayerMP) { + SPEventHandler.scheduleTask(new Runnable() { + + @Override + public void run() { + PostHandler.confirm((EntityPlayerMP) sender); + } + }, 0); + } + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender instanceof EntityPlayer; } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/commands/DiscoverWaystone.java b/src/main/java/gollorum/signpost/commands/DiscoverWaystone.java index 02f76237..d12b6ba6 100644 --- a/src/main/java/gollorum/signpost/commands/DiscoverWaystone.java +++ b/src/main/java/gollorum/signpost/commands/DiscoverWaystone.java @@ -1,77 +1,82 @@ package gollorum.signpost.commands; -import cpw.mods.fml.common.FMLCommonHandler; -import gollorum.signpost.management.ConfigHandler; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.network.NetworkHandler; -import gollorum.signpost.network.messages.ChatMessage; -import gollorum.signpost.util.BaseInfo; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.command.PlayerNotFoundException; import net.minecraft.command.WrongUsageException; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; + +import cpw.mods.fml.common.FMLCommonHandler; +import gollorum.signpost.management.ConfigHandler; +import gollorum.signpost.management.PostHandler; +import gollorum.signpost.network.NetworkHandler; +import gollorum.signpost.network.messages.ChatMessage; +import gollorum.signpost.util.BaseInfo; public class DiscoverWaystone extends CommandBase { - @Override - public String getCommandName() { - return "discoverwaystone"; - } + @Override + public String getCommandName() { + return "discoverwaystone"; + } - @Override - public String getCommandUsage(ICommandSender p_71518_1_) { - return "/discoverwaystone [player]"; - } + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/discoverwaystone [player]"; + } - @Override - public void processCommand(ICommandSender sender, String[] args) throws PlayerNotFoundException, CommandException { - if(sender instanceof EntityPlayerMP){ - EntityPlayerMP player = (EntityPlayerMP) sender; - if (args.length < 1){ - throw new WrongUsageException(getCommandUsage(null), new Object[0]); - } - String waystoneName = ""; - String playerName = null; - for(String now: args){ - waystoneName+=" "+now; - } - waystoneName = waystoneName.substring(1); - BaseInfo base = PostHandler.getNativeWaystones().getByName(waystoneName); - if(base==null && args.length>1){ - waystoneName=""; - playerName = args[args.length-1]; - for(int i=0; i"}; - String[] replacement = {waystoneName}; - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.waystoneNotFound", keys, replacement), player); - }else{ - PostHandler.addDiscovered(target.getUniqueID(), base); - String[] keys = {""}; - String[] replacement = {waystoneName}; - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.discovered", keys, replacement), target); - } - } - } + @Override + public void processCommand(ICommandSender sender, String[] args) throws PlayerNotFoundException, CommandException { + if (sender instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) sender; + if (args.length < 1) { + throw new WrongUsageException(getCommandUsage(null), new Object[0]); + } + String waystoneName = ""; + String playerName = null; + for (String now : args) { + waystoneName += " " + now; + } + waystoneName = waystoneName.substring(1); + BaseInfo base = PostHandler.getNativeWaystones() + .getByName(waystoneName); + if (base == null && args.length > 1) { + waystoneName = ""; + playerName = args[args.length - 1]; + for (int i = 0; i < args.length - 1; i++) { + waystoneName += " " + args[i]; + } + waystoneName = waystoneName.substring(1); + base = PostHandler.getNativeWaystones() + .getByName(waystoneName); + } + EntityPlayerMP target = player; + if (playerName != null) { + target = getPlayer( + FMLCommonHandler.instance() + .getMinecraftServerInstance(), + playerName); + } + if (base == null) { + String[] keys = { "" }; + String[] replacement = { waystoneName }; + NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.waystoneNotFound", keys, replacement), player); + } else { + PostHandler.addDiscovered(target.getUniqueID(), base); + String[] keys = { "" }; + String[] replacement = { waystoneName }; + NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.discovered", keys, replacement), target); + } + } + } - public int getRequiredPermissionLevel(){ - return 2; - } + public int getRequiredPermissionLevel() { + return 2; + } - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return sender instanceof EntityPlayerMP && ConfigHandler.isOp((EntityPlayerMP)sender); - } -} \ No newline at end of file + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender instanceof EntityPlayerMP && ConfigHandler.isOp((EntityPlayerMP) sender); + } +} diff --git a/src/main/java/gollorum/signpost/commands/GetSignpostCount.java b/src/main/java/gollorum/signpost/commands/GetSignpostCount.java index 96ef9631..38290b34 100644 --- a/src/main/java/gollorum/signpost/commands/GetSignpostCount.java +++ b/src/main/java/gollorum/signpost/commands/GetSignpostCount.java @@ -1,56 +1,60 @@ package gollorum.signpost.commands; -import gollorum.signpost.management.ConfigHandler; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.network.NetworkHandler; -import gollorum.signpost.network.messages.ChatMessage; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +import gollorum.signpost.management.ConfigHandler; +import gollorum.signpost.management.PostHandler; +import gollorum.signpost.network.NetworkHandler; +import gollorum.signpost.network.messages.ChatMessage; + public class GetSignpostCount extends CommandBase { - @Override - public String getCommandName() { - return "getsignpostsleft"; - } - - @Override - public String getCommandUsage(ICommandSender p_71518_1_) { - return "/getsignpostsleft [Player - op only]"; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) { - if(sender instanceof EntityPlayerMP){ - EntityPlayerMP player = (EntityPlayerMP) sender; - if(args.length==0 || !ConfigHandler.isOp(player)){ - String amount = ""+PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingSignposts; - if(amount.equals("-1")){ - amount = "unlimited"; - } - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.getsignpostsleft", "", amount), player); - }else{ - EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[0]); - if(p==null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.playerNotFound", "", args[0]), player); - return; - } - String amount = ""+PostHandler.getPlayerKnownWaystonePositions(p.getUniqueID()).remainingSignposts; - if(amount.equals("-1")){ - amount = "unlimited"; - } - String[] keys = {"", ""}; - String[] replacement = {amount, args[0]}; - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.getsignpostsleftop", keys, replacement), player); - } - } - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return sender instanceof EntityPlayer; + @Override + public String getCommandName() { + return "getsignpostsleft"; + } + + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/getsignpostsleft [Player - op only]"; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (sender instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) sender; + if (args.length == 0 || !ConfigHandler.isOp(player)) { + String amount = "" + + PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingSignposts; + if (amount.equals("-1")) { + amount = "unlimited"; + } + NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.getsignpostsleft", "", amount), player); + } else { + EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[0]); + if (p == null) { + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.playerNotFound", "", args[0]), player); + return; + } + String amount = "" + PostHandler.getPlayerKnownWaystonePositions(p.getUniqueID()).remainingSignposts; + if (amount.equals("-1")) { + amount = "unlimited"; + } + String[] keys = { "", "" }; + String[] replacement = { amount, args[0] }; + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.getsignpostsleftop", keys, replacement), player); + } + } + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender instanceof EntityPlayer; } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/commands/GetWaystoneCount.java b/src/main/java/gollorum/signpost/commands/GetWaystoneCount.java index d7ad9f76..becdb1bd 100644 --- a/src/main/java/gollorum/signpost/commands/GetWaystoneCount.java +++ b/src/main/java/gollorum/signpost/commands/GetWaystoneCount.java @@ -1,56 +1,61 @@ package gollorum.signpost.commands; -import gollorum.signpost.management.ConfigHandler; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.network.NetworkHandler; -import gollorum.signpost.network.messages.ChatMessage; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +import gollorum.signpost.management.ConfigHandler; +import gollorum.signpost.management.PostHandler; +import gollorum.signpost.network.NetworkHandler; +import gollorum.signpost.network.messages.ChatMessage; + public class GetWaystoneCount extends CommandBase { - @Override - public String getCommandName() { - return "getwaystonesleft"; - } - - @Override - public String getCommandUsage(ICommandSender p_71518_1_) { - return "/getwaystonesleft"; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) { - if(sender instanceof EntityPlayerMP){ - EntityPlayerMP player = (EntityPlayerMP) sender; - if(args.length==0 || !ConfigHandler.isOp(player)){ - String amount = ""+PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones; - if(amount.equals("-1")){ - amount = "unlimited"; - } - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.getwaystonesleft", "", amount), player); - }else{ - EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[0]); - if(p==null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.playerNotFound", "", args[0]), player); - return; - } - String amount = ""+PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones; - if(amount.equals("-1")){ - amount = "unlimited"; - } - String[] keys = {"", ""}; - String[] replacement = {amount, args[0]}; - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.getwaystonesleftop", keys, replacement), player); - } - } - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return sender instanceof EntityPlayer; + @Override + public String getCommandName() { + return "getwaystonesleft"; + } + + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/getwaystonesleft"; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (sender instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) sender; + if (args.length == 0 || !ConfigHandler.isOp(player)) { + String amount = "" + + PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones; + if (amount.equals("-1")) { + amount = "unlimited"; + } + NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.getwaystonesleft", "", amount), player); + } else { + EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[0]); + if (p == null) { + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.playerNotFound", "", args[0]), player); + return; + } + String amount = "" + + PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones; + if (amount.equals("-1")) { + amount = "unlimited"; + } + String[] keys = { "", "" }; + String[] replacement = { amount, args[0] }; + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.getwaystonesleftop", keys, replacement), player); + } + } + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender instanceof EntityPlayer; } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/commands/ListAllWaystones.java b/src/main/java/gollorum/signpost/commands/ListAllWaystones.java index 2f741363..84ab46c1 100644 --- a/src/main/java/gollorum/signpost/commands/ListAllWaystones.java +++ b/src/main/java/gollorum/signpost/commands/ListAllWaystones.java @@ -1,47 +1,49 @@ package gollorum.signpost.commands; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.util.BaseInfo; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; +import gollorum.signpost.management.PostHandler; +import gollorum.signpost.util.BaseInfo; + public class ListAllWaystones extends CommandBase { - @Override - public String getCommandName() { - return "signpost"; - } - - @Override - public String getCommandUsage(ICommandSender sender) { - return "/signpost list"; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) { - if (sender instanceof EntityPlayerMP) { - if (args.length == 1 && args[0].toLowerCase().equals("list".toLowerCase())) { - printAllWaystones(sender); - } else { - sender.addChatMessage(new ChatComponentText("Usage: " + getCommandUsage(sender))); - } - } - } - - private void printAllWaystones(ICommandSender sender) { - for (BaseInfo base : PostHandler.getAllWaystones()) { - if (base.hasName()) { - sender.addChatMessage(new ChatComponentText(base.getName())); - } - } - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return sender instanceof EntityPlayer; + @Override + public String getCommandName() { + return "signpost"; + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return "/signpost list"; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (sender instanceof EntityPlayerMP) { + if (args.length == 1 && args[0].toLowerCase() + .equals("list".toLowerCase())) { + printAllWaystones(sender); + } else { + sender.addChatMessage(new ChatComponentText("Usage: " + getCommandUsage(sender))); + } + } + } + + private void printAllWaystones(ICommandSender sender) { + for (BaseInfo base : PostHandler.getAllWaystones()) { + if (base.hasName()) { + sender.addChatMessage(new ChatComponentText(base.getName())); + } + } + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender instanceof EntityPlayer; } } diff --git a/src/main/java/gollorum/signpost/commands/SetSignpostCount.java b/src/main/java/gollorum/signpost/commands/SetSignpostCount.java index 0f2f43f5..59c5d05c 100644 --- a/src/main/java/gollorum/signpost/commands/SetSignpostCount.java +++ b/src/main/java/gollorum/signpost/commands/SetSignpostCount.java @@ -1,58 +1,63 @@ package gollorum.signpost.commands; -import gollorum.signpost.management.ConfigHandler; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.network.NetworkHandler; -import gollorum.signpost.network.messages.ChatMessage; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; +import gollorum.signpost.management.ConfigHandler; +import gollorum.signpost.management.PostHandler; +import gollorum.signpost.network.NetworkHandler; +import gollorum.signpost.network.messages.ChatMessage; + public class SetSignpostCount extends CommandBase { - @Override - public String getCommandName() { - return "setsignpostsleft"; - } - - @Override - public String getCommandUsage(ICommandSender p_71518_1_) { - return "/setsignpostsleft []"; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) { - if(sender instanceof EntityPlayerMP){ - EntityPlayerMP player = (EntityPlayerMP) sender; - if(args.length==1){ - try{ - PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingSignposts = Integer.parseInt(args[0]); - }catch(Exception e){ - sender.addChatMessage(new ChatComponentText("Error: '"+args[0]+"' is not a numer")); - } - }else if(args.length==2){ - EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[1]); - if(p==null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.playerNotFound", "", args[1]), player); - return; - }else{ - try{ - PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingSignposts = Integer.parseInt(args[0]); - }catch(Exception e){ - sender.addChatMessage(new ChatComponentText("Error: '"+args[0]+"' is not a numer")); - } - } - }else{ - sender.addChatMessage(new ChatComponentText("Error: wrong argument count, use "+getCommandUsage(null))); - } - } - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return sender instanceof EntityPlayer && ConfigHandler.isOp((EntityPlayer)sender); + @Override + public String getCommandName() { + return "setsignpostsleft"; + } + + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/setsignpostsleft []"; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (sender instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) sender; + if (args.length == 1) { + try { + PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingSignposts = Integer + .parseInt(args[0]); + } catch (Exception e) { + sender.addChatMessage(new ChatComponentText("Error: '" + args[0] + "' is not a numer")); + } + } else if (args.length == 2) { + EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[1]); + if (p == null) { + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.playerNotFound", "", args[1]), player); + return; + } else { + try { + PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingSignposts = Integer + .parseInt(args[0]); + } catch (Exception e) { + sender.addChatMessage(new ChatComponentText("Error: '" + args[0] + "' is not a numer")); + } + } + } else { + sender + .addChatMessage(new ChatComponentText("Error: wrong argument count, use " + getCommandUsage(null))); + } + } + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender instanceof EntityPlayer && ConfigHandler.isOp((EntityPlayer) sender); } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/commands/SetWaystoneCount.java b/src/main/java/gollorum/signpost/commands/SetWaystoneCount.java index babc6e9c..ec448cbf 100644 --- a/src/main/java/gollorum/signpost/commands/SetWaystoneCount.java +++ b/src/main/java/gollorum/signpost/commands/SetWaystoneCount.java @@ -1,58 +1,63 @@ package gollorum.signpost.commands; -import gollorum.signpost.management.ConfigHandler; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.network.NetworkHandler; -import gollorum.signpost.network.messages.ChatMessage; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ChatComponentText; +import gollorum.signpost.management.ConfigHandler; +import gollorum.signpost.management.PostHandler; +import gollorum.signpost.network.NetworkHandler; +import gollorum.signpost.network.messages.ChatMessage; + public class SetWaystoneCount extends CommandBase { - @Override - public String getCommandName() { - return "setwaystonesleft"; - } - - @Override - public String getCommandUsage(ICommandSender p_71518_1_) { - return "/setwaystonesleft []"; - } - - @Override - public void processCommand(ICommandSender sender, String[] args) { - if(sender instanceof EntityPlayerMP){ - EntityPlayerMP player = (EntityPlayerMP) sender; - if(args.length==1){ - try{ - PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones = Integer.parseInt(args[0]); - }catch(Exception e){ - sender.addChatMessage(new ChatComponentText("Error: '"+args[0]+"' is not a numer")); - } - }else if(args.length==2){ - EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[1]); - if(p==null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.playerNotFound", "", args[1]), player); - return; - }else{ - try{ - PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones = Integer.parseInt(args[0]); - }catch(Exception e){ - sender.addChatMessage(new ChatComponentText("Error: '"+args[0]+"' is not a numer")); - } - } - }else{ - sender.addChatMessage(new ChatComponentText("Error: wrong argument count, use "+getCommandUsage(null))); - } - } - } - - @Override - public boolean canCommandSenderUseCommand(ICommandSender sender){ - return sender instanceof EntityPlayer && ConfigHandler.isOp((EntityPlayer)sender); + @Override + public String getCommandName() { + return "setwaystonesleft"; + } + + @Override + public String getCommandUsage(ICommandSender p_71518_1_) { + return "/setwaystonesleft []"; + } + + @Override + public void processCommand(ICommandSender sender, String[] args) { + if (sender instanceof EntityPlayerMP) { + EntityPlayerMP player = (EntityPlayerMP) sender; + if (args.length == 1) { + try { + PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones = Integer + .parseInt(args[0]); + } catch (Exception e) { + sender.addChatMessage(new ChatComponentText("Error: '" + args[0] + "' is not a numer")); + } + } else if (args.length == 2) { + EntityPlayerMP p = (EntityPlayerMP) PostHandler.getPlayerByName(args[1]); + if (p == null) { + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.playerNotFound", "", args[1]), player); + return; + } else { + try { + PostHandler.getPlayerKnownWaystonePositions(player.getUniqueID()).remainingWaystones = Integer + .parseInt(args[0]); + } catch (Exception e) { + sender.addChatMessage(new ChatComponentText("Error: '" + args[0] + "' is not a numer")); + } + } + } else { + sender + .addChatMessage(new ChatComponentText("Error: wrong argument count, use " + getCommandUsage(null))); + } + } + } + + @Override + public boolean canCommandSenderUseCommand(ICommandSender sender) { + return sender instanceof EntityPlayer && ConfigHandler.isOp((EntityPlayer) sender); } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/event/UpdateWaystoneEvent.java b/src/main/java/gollorum/signpost/event/UpdateWaystoneEvent.java index a650c39b..602863cc 100644 --- a/src/main/java/gollorum/signpost/event/UpdateWaystoneEvent.java +++ b/src/main/java/gollorum/signpost/event/UpdateWaystoneEvent.java @@ -1,30 +1,33 @@ package gollorum.signpost.event; -import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.world.World; +import cpw.mods.fml.common.eventhandler.Event; + /** * Server-side only */ -public class UpdateWaystoneEvent extends Event{ +public class UpdateWaystoneEvent extends Event { + + public static enum WaystoneEventType { + PLACED, + NAMECHANGED, + DESTROYED; + } + + public WaystoneEventType type; + public World world; + public int x, y, z; + public String name; + + public UpdateWaystoneEvent(WaystoneEventType type, World world, int x, int y, int z, String name) { + super(); + this.type = type; + this.world = world; + this.x = x; + this.y = y; + this.z = z; + this.name = name; + } - public static enum WaystoneEventType{ - PLACED, NAMECHANGED, DESTROYED; - } - - public WaystoneEventType type; - public World world; - public int x, y, z; - public String name; - - public UpdateWaystoneEvent(WaystoneEventType type, World world, int x, int y, int z, String name) { - super(); - this.type = type; - this.world = world; - this.x = x; - this.y = y; - this.z = z; - this.name = name; - } - } diff --git a/src/main/java/gollorum/signpost/event/UseSignpostEvent.java b/src/main/java/gollorum/signpost/event/UseSignpostEvent.java index e83eed5a..7cb2feae 100644 --- a/src/main/java/gollorum/signpost/event/UseSignpostEvent.java +++ b/src/main/java/gollorum/signpost/event/UseSignpostEvent.java @@ -1,32 +1,33 @@ package gollorum.signpost.event; -import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; +import cpw.mods.fml.common.eventhandler.Event; + /** * Fired server- and client-side upon right-clicking a signpost. */ public class UseSignpostEvent extends Event { - public EntityPlayer player; - public World world; - public int x; - public int y; - public int z; - - public UseSignpostEvent(EntityPlayer player, World world, int x, int y, int z) { - super(); - this.player = player; - this.world = world; - this.x = x; - this.y = y; - this.z = z; - } + public EntityPlayer player; + public World world; + public int x; + public int y; + public int z; - @Override - public boolean isCancelable(){ + public UseSignpostEvent(EntityPlayer player, World world, int x, int y, int z) { + super(); + this.player = player; + this.world = world; + this.x = x; + this.y = y; + this.z = z; + } + + @Override + public boolean isCancelable() { return true; } - + } diff --git a/src/main/java/gollorum/signpost/gui/BaseInputBox.java b/src/main/java/gollorum/signpost/gui/BaseInputBox.java index 7fefea9f..3da935c6 100644 --- a/src/main/java/gollorum/signpost/gui/BaseInputBox.java +++ b/src/main/java/gollorum/signpost/gui/BaseInputBox.java @@ -1,8 +1,5 @@ package gollorum.signpost.gui; -import org.lwjgl.opengl.GL11; - -import cpw.mods.fml.client.FMLClientHandler; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiScreen; @@ -10,110 +7,115 @@ import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.ResourceLocation; -public class BaseInputBox extends Gui{ - - private static final double pWidth = 25.0; - private static final double pHeight = 6.0; - private static final double verh = pWidth/pHeight; - - public int x; - public int y; - public int width; - public int height; - private boolean isFocused = false; +import org.lwjgl.opengl.GL11; + +import cpw.mods.fml.client.FMLClientHandler; + +public class BaseInputBox extends Gui { + + private static final double pWidth = 25.0; + private static final double pHeight = 6.0; + private static final double verh = pWidth / pHeight; + + public int x; + public int y; + public int width; + public int height; + private boolean isFocused = false; private int cursorPosition; - + public int color = 0; private int count = 0; public int drawXat; public double scc; private static final ResourceLocation texture = new ResourceLocation("signpost:textures/gui/base_gui.png"); - - private FontRenderer fontRend; - - public String text = ""; - - public BaseInputBox(FontRenderer p_i1032_1_, int x, int y, int width) { - this.fontRend = p_i1032_1_; - this.x = x; - this.y = y; - this.width = width; - this.height = (int) (width/verh); - setText(null); - } - - public void setFocused(boolean bool){ - isFocused = bool; - cursorPosition = getText().length(); - } - - public boolean isFocused(){ - return isFocused; - } - - public void drawSignBox(FontRenderer fontRend){ - FMLClientHandler.instance().getClient().renderEngine.bindTexture(texture); - drawTexturedModalRect(this.x, this.y, 0, 0, width, height); - if((this.fontRend = fontRend)!=null){ - drawText(); - } - } - - @Override - public void drawTexturedModalRect(int x, int y, int u, int v, int width, int height){ + + private FontRenderer fontRend; + + public String text = ""; + + public BaseInputBox(FontRenderer p_i1032_1_, int x, int y, int width) { + this.fontRend = p_i1032_1_; + this.x = x; + this.y = y; + this.width = width; + this.height = (int) (width / verh); + setText(null); + } + + public void setFocused(boolean bool) { + isFocused = bool; + cursorPosition = getText().length(); + } + + public boolean isFocused() { + return isFocused; + } + + public void drawSignBox(FontRenderer fontRend) { + FMLClientHandler.instance() + .getClient().renderEngine.bindTexture(texture); + drawTexturedModalRect(this.x, this.y, 0, 0, width, height); + if ((this.fontRend = fontRend) != null) { + drawText(); + } + } + + @Override + public void drawTexturedModalRect(int x, int y, int u, int v, int width, int height) { float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)(x), (double)(y+height), (double)this.zLevel, 0.0, 1.0); - tessellator.addVertexWithUV((double)(x+width), (double)(y+height), (double)this.zLevel, 1.0, 1.0); - tessellator.addVertexWithUV((double)(x+width), (double)(y), (double)this.zLevel, 1.0, 0.0); - tessellator.addVertexWithUV((double)(x), (double)(y), (double)this.zLevel, 0.0, 0.0); + tessellator.addVertexWithUV((double) (x), (double) (y + height), (double) this.zLevel, 0.0, 1.0); + tessellator.addVertexWithUV((double) (x + width), (double) (y + height), (double) this.zLevel, 1.0, 1.0); + tessellator.addVertexWithUV((double) (x + width), (double) (y), (double) this.zLevel, 1.0, 0.0); + tessellator.addVertexWithUV((double) (x), (double) (y), (double) this.zLevel, 0.0, 0.0); tessellator.draw(); } - - public void drawText(){ - String txt; - count = (count+1)%60; - if(count<30&&isFocused){ - txt = getText().substring(0, cursorPosition)+"|"+getText().substring(cursorPosition); - }else{ - txt = getText(); - } - double x = this.x+(this.width)/2.0; - double y = this.y+(this.height)/2.0; - double sc2 = 100d/fontRend.getStringWidth(txt); - if(sc2>=1){ - sc2 = 1; - } - scc = sc2; - GL11.glPushMatrix(); - GL11.glScaled(sc2, sc2, 1); - if(sc2==1.0){ - x = (int) (x = ((x-fontRend.getStringWidth(txt)/2.0))/sc2); - drawXat = (int) (x*sc2); - }else{ - drawXat = (int) (x-50); - x = (x-50)/sc2; - } - fontRend.drawString(txt, (int) x, (int) ((y-fontRend.FONT_HEIGHT/2.0*sc2)/sc2), color); - GL11.glPopMatrix(); - } - - public void setText(String text){ - this.text = text==null?"null":text; - } - - public String getText(){ - return text; - } - - public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_){ - if (!this.isFocused){ + + public void drawText() { + String txt; + count = (count + 1) % 60; + if (count < 30 && isFocused) { + txt = getText().substring(0, cursorPosition) + "|" + getText().substring(cursorPosition); + } else { + txt = getText(); + } + double x = this.x + (this.width) / 2.0; + double y = this.y + (this.height) / 2.0; + double sc2 = 100d / fontRend.getStringWidth(txt); + if (sc2 >= 1) { + sc2 = 1; + } + scc = sc2; + GL11.glPushMatrix(); + GL11.glScaled(sc2, sc2, 1); + if (sc2 == 1.0) { + x = (int) (x = ((x - fontRend.getStringWidth(txt) / 2.0)) / sc2); + drawXat = (int) (x * sc2); + } else { + drawXat = (int) (x - 50); + x = (x - 50) / sc2; + } + fontRend.drawString(txt, (int) x, (int) ((y - fontRend.FONT_HEIGHT / 2.0 * sc2) / sc2), color); + GL11.glPopMatrix(); + } + + public void setText(String text) { + this.text = text == null ? "null" : text; + } + + public String getText() { + return text; + } + + public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_) { + if (!this.isFocused) { return false; - }else{ - switch (p_146201_1_){ + } else { + switch (p_146201_1_) { case 1: cursorPosition = text.length(); return true; @@ -121,28 +123,28 @@ public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_){ this.writeText(GuiScreen.getClipboardString()); return true; default: - switch (p_146201_2_){ - case 14: - if (GuiScreen.isCtrlKeyDown()){ - this.deleteWords(-1); - }else{ - this.deleteFromCursor(-1); - } - return true; + switch (p_146201_2_) { + case 14: + if (GuiScreen.isCtrlKeyDown()) { + this.deleteWords(-1); + } else { + this.deleteFromCursor(-1); + } + return true; case 199: cursorPosition = 0; return true; case 203: - if (GuiScreen.isCtrlKeyDown()){ + if (GuiScreen.isCtrlKeyDown()) { this.setCursorPosition(this.getNthWordFromCursor(-1)); - }else{ + } else { this.moveCursorBy(-1); } return true; case 205: - if (GuiScreen.isCtrlKeyDown()){ + if (GuiScreen.isCtrlKeyDown()) { this.setCursorPosition(this.getNthWordFromCursor(1)); - }else{ + } else { this.moveCursorBy(1); } return true; @@ -150,18 +152,17 @@ public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_){ cursorPosition = text.length(); return true; case 211: - if (GuiScreen.isCtrlKeyDown()){ + if (GuiScreen.isCtrlKeyDown()) { this.deleteWords(1); - } - else{ - this.deleteFromCursor(1); + } else { + this.deleteFromCursor(1); } return true; default: - if (ChatAllowedCharacters.isAllowedCharacter(p_146201_1_)){ - this.writeText(Character.toString(p_146201_1_)); + if (ChatAllowedCharacters.isAllowedCharacter(p_146201_1_)) { + this.writeText(Character.toString(p_146201_1_)); return true; - }else{ + } else { return false; } } @@ -169,98 +170,88 @@ public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_){ } } - public void writeText(String p_146191_1_){ + public void writeText(String p_146191_1_) { String s2 = ChatAllowedCharacters.filerAllowedCharacters(p_146191_1_); - this.text = text.substring(0, cursorPosition)+s2+text.substring(cursorPosition); + this.text = text.substring(0, cursorPosition) + s2 + text.substring(cursorPosition); this.moveCursorBy(s2.length()); } - public void moveCursorBy(int p_146182_1_){ + public void moveCursorBy(int p_146182_1_) { this.setCursorPosition(cursorPosition + p_146182_1_); } - public void setCursorPosition(int p_146190_1_){ - count = 0; + public void setCursorPosition(int p_146190_1_) { + count = 0; this.cursorPosition = p_146190_1_; int j = this.text.length(); - if (this.cursorPosition < 0){ + if (this.cursorPosition < 0) { this.cursorPosition = 0; - }else if (this.cursorPosition > j){ + } else if (this.cursorPosition > j) { this.cursorPosition = j; } } - public void deleteFromCursor(int p_146175_1_){ - if (this.text.length() != 0){ - boolean flag = p_146175_1_ < 0; - int j = flag ? this.cursorPosition + p_146175_1_ : this.cursorPosition; - int k = flag ? this.cursorPosition : this.cursorPosition + p_146175_1_; - String s = ""; - - if (j >= 0){ - s = this.text.substring(0, j); - } - - if (k < this.text.length()){ - s = s + this.text.substring(k); - } - - this.text = s; - - if (flag){ - this.moveCursorBy(p_146175_1_); - } + public void deleteFromCursor(int p_146175_1_) { + if (this.text.length() != 0) { + boolean flag = p_146175_1_ < 0; + int j = flag ? this.cursorPosition + p_146175_1_ : this.cursorPosition; + int k = flag ? this.cursorPosition : this.cursorPosition + p_146175_1_; + String s = ""; + + if (j >= 0) { + s = this.text.substring(0, j); + } + + if (k < this.text.length()) { + s = s + this.text.substring(k); + } + + this.text = s; + + if (flag) { + this.moveCursorBy(p_146175_1_); + } } } - public void deleteWords(int p_146177_1_){ - if (this.text.length() != 0){ + public void deleteWords(int p_146177_1_) { + if (this.text.length() != 0) { this.deleteFromCursor(this.getNthWordFromCursor(p_146177_1_) - this.cursorPosition); } } - public int getNthWordFromCursor(int p_146187_1_){ + public int getNthWordFromCursor(int p_146187_1_) { return this.getNthWordFromPos(p_146187_1_, this.cursorPosition); } - public int getNthWordFromPos(int p_146183_1_, int p_146183_2_){ + public int getNthWordFromPos(int p_146183_1_, int p_146183_2_) { return this.func_146197_a(p_146183_1_, this.cursorPosition, true); } - public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_){ + public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_) { int k = p_146197_2_; boolean flag1 = p_146197_1_ < 0; int l = Math.abs(p_146197_1_); - for (int i1 = 0; i1 < l; ++i1) - { - if (flag1) - { - while (p_146197_3_ && k > 0 && this.text.charAt(k - 1) == 32) - { + for (int i1 = 0; i1 < l; ++i1) { + if (flag1) { + while (p_146197_3_ && k > 0 && this.text.charAt(k - 1) == 32) { --k; } - while (k > 0 && this.text.charAt(k - 1) != 32) - { + while (k > 0 && this.text.charAt(k - 1) != 32) { --k; } - } - else - { + } else { int j1 = this.text.length(); k = this.text.indexOf(32, k); - if (k == -1) - { + if (k == -1) { k = j1; - } - else - { - while (p_146197_3_ && k < j1 && this.text.charAt(k) == 32) - { + } else { + while (p_146197_3_ && k < j1 && this.text.charAt(k) == 32) { ++k; } } @@ -270,31 +261,34 @@ public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_){ return k; } - public void mouseClicked(int p_146192_1_, int p_146192_2_, int p_146192_3_){ - isFocused = (p_146192_1_ >= this.x && p_146192_1_ < this.x + this.width && p_146192_2_ >= this.y && p_146192_2_ < this.y + this.height); + public void mouseClicked(int p_146192_1_, int p_146192_2_, int p_146192_3_) { + isFocused = (p_146192_1_ >= this.x && p_146192_1_ < this.x + this.width + && p_146192_2_ >= this.y + && p_146192_2_ < this.y + this.height); - if (this.isFocused && p_146192_3_ == 0){ + if (this.isFocused && p_146192_3_ == 0) { int l = p_146192_1_ - drawXat; - this.setCursorPosition(correctTrim((int) (l/scc)).length()); + this.setCursorPosition(correctTrim((int) (l / scc)).length()); } } - - public String correctTrim(int width){ - int l = this.fontRend.trimStringToWidth(getText(), width).length(); - if(getText().length() == l){ - return getText(); - } - int l1 = this.fontRend.getStringWidth(getText().substring(0, l)); - int l2 = this.fontRend.getStringWidth(getText().substring(0, l+1)); - if(width-l1", + "" + (int) tile.toPos() + .distance(inf.teleportPosition) + 1); + out = out.replaceAll("", "" + ClientConfigStorage.INSTANCE.getMaxDist()); + std = out; + col = Color.red.getRGB(); + go = false; + + } else if (connect.equals(Connection.WORLD)) { + + String out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiWorldDim"); + if (out.equals("")) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiWorldDim", "en_US"); + } + std = out; + col = Color.red.getRGB(); + go = false; + + } else { + std = ""; + col = Color.red.getRGB(); + go = false; + } + } else { + box.setTextColor(Color.black.getRGB()); + col = Color.white.getRGB(); + go = true; -public class SignGuiBigPost extends GuiScreen implements SignInput{ - - private SignInputBox baseInputBox; - - private GuiTextField desc1InputBox; - private GuiTextField desc2InputBox; - private GuiTextField desc3InputBox; - private GuiTextField desc4InputBox; - - private String std = ""; - private int col = 0; - private boolean go; - - private BigPostPostTile tile; - - private boolean resetMouse; - - public SignGuiBigPost(BigPostPostTile tile) { - this.tile = tile; - initGui(); - } - - @Override - public void initGui() { - BigBaseInfo tilebases = tile.getBases(); - baseInputBox = new SignInputBox(this.fontRendererObj, this.width / 2 - 68, 46, 137, this); - baseInputBox.setText(tilebases.sign.base==null?"":tilebases.sign.base.toString()); - go = true; - baseInputBox.setFocused(true); - - desc1InputBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 68, 106, 137, 20); - desc1InputBox.setText(""+tilebases.description[0]); - desc2InputBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 68, 136, 137, 20); - desc2InputBox.setText(""+tilebases.description[1]); - desc3InputBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 68, 166, 137, 20); - desc3InputBox.setText(""+tilebases.description[2]); - desc4InputBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 68, 196, 137, 20); - desc4InputBox.setText(""+tilebases.description[3]); - - resetMouse = true; - } - - @Override - protected void mouseClicked(int x, int y, int bla){ - super.mouseClicked(x, y, bla); - baseInputBox.mouseClicked(x, y, bla); - desc1InputBox.mouseClicked(x, y, bla); - desc2InputBox.mouseClicked(x, y, bla); - desc3InputBox.mouseClicked(x, y, bla); - desc4InputBox.mouseClicked(x, y, bla); - } - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - super.drawScreen(mouseX, mouseY, partialTicks); - try{ - if(mc==null){ - mc = FMLClientHandler.instance().getClient(); - } - if(baseInputBox==null || desc1InputBox==null || desc2InputBox==null || desc3InputBox==null || desc4InputBox==null){ - initGui(); - } - drawDefaultBackground(); - baseInputBox.drawSignBox(fontRendererObj); - this.drawCenteredString(fontRendererObj, std, this.width/2, baseInputBox.y+baseInputBox.height+10, col); - desc1InputBox.drawTextBox(); - desc2InputBox.drawTextBox(); - desc3InputBox.drawTextBox(); - desc4InputBox.drawTextBox(); - if(resetMouse){ - resetMouse = false; - org.lwjgl.input.Mouse.setGrabbed(false); - } - }catch(Exception e){} - } - - @Override - protected void keyTyped(char par1, int par2) { - super.keyTyped(par1, par2); - if((par1==13&&par2==28) || (par1==9&&par2==15) || (par1==0&&par2==208)){ - if(baseInputBox.isFocused()){ - if(par1==13&&par2==28){ - if(!go){ - go=true; - baseInputBox.textColor = Color.orange.getRGB(); - } - } - baseInputBox.setFocused(false); - desc1InputBox.setFocused(true); - }else if(desc1InputBox.isFocused()){ - desc1InputBox.setFocused(false); - desc2InputBox.setFocused(true); - }else if(desc2InputBox.isFocused()){ - desc2InputBox.setFocused(false); - desc3InputBox.setFocused(true); - }else if(desc3InputBox.isFocused()){ - desc3InputBox.setFocused(false); - desc4InputBox.setFocused(true); - }else if(desc4InputBox.isFocused()){ - if(par1==13&&par2==28){ - this.mc.displayGuiScreen(null); - }else{ - desc4InputBox.setFocused(false); - baseInputBox.setFocused(true); - } - }else{ - baseInputBox.setFocused(true); - } - return; - }else if(par1==0&&par2==200){ - if(baseInputBox.isFocused()){ - baseInputBox.setFocused(false); - desc4InputBox.setFocused(true); - }else if(desc1InputBox.isFocused()){ - desc1InputBox.setFocused(false); - baseInputBox.setFocused(true); - }else if(desc2InputBox.isFocused()){ - desc2InputBox.setFocused(false); - desc1InputBox.setFocused(true); - }else if(desc3InputBox.isFocused()){ - desc3InputBox.setFocused(false); - desc2InputBox.setFocused(true); - }else if(desc4InputBox.isFocused()){ - desc4InputBox.setFocused(false); - desc3InputBox.setFocused(true); - }else{ - baseInputBox.setFocused(true); - } - return; - } - baseType(par1, par2); - desc1InputBox.textboxKeyTyped(par1, par2); - desc2InputBox.textboxKeyTyped(par1, par2); - desc3InputBox.textboxKeyTyped(par1, par2); - desc4InputBox.textboxKeyTyped(par1, par2); - } - - private void baseType(char par1, int par2){ - SignInputBox tf = baseInputBox; - String before = tf.getText(); - if(tf.textboxKeyTyped(par1, par2)&&!tf.getText().equals(before)){ - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()){ - return; - } - onTextChange(tf); - } - } - - @Override - public void onGuiClosed() { - BigBaseInfo tilebases = tile.getBases(); - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()||go){ - tilebases.sign.base = PostHandler.getForceWSbyName(baseInputBox.getText()); - }else{ - tilebases.sign.base = null; - } - tilebases.description[0] = desc1InputBox.getText(); - tilebases.description[1] = desc2InputBox.getText(); - tilebases.description[2] = desc3InputBox.getText(); - tilebases.description[3] = desc4InputBox.getText(); - NetworkHandler.netWrap.sendToServer(new SendBigPostBasesMessage(tile, tilebases)); - } - - @Override - public void onTextChange(SignInputBox box){ - BaseInfo inf = PostHandler.getWSbyName(box.getText()); - Connection connect = tile.toPos().canConnectTo(inf); - if(inf==null||!connect.equals(Connection.VALID)){ - box.setTextColor(Color.red.getRGB()); - if(connect.equals(Connection.DIST)){ - - String out = LanguageRegistry.instance().getStringLocalization("signpost.guiTooFar"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.guiTooFar", "en_US"); - } - out = out.replaceAll("", ""+(int)tile.toPos().distance(inf.teleportPosition)+1); - out = out.replaceAll("", ""+ClientConfigStorage.INSTANCE.getMaxDist()); - std = out; - col = Color.red.getRGB(); - go = false; - - }else if(connect.equals(Connection.WORLD)){ - - String out = LanguageRegistry.instance().getStringLocalization("signpost.guiWorldDim"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.guiWorldDim", "en_US"); - } - std = out; - col = Color.red.getRGB(); - go = false; - - }else{ - std = ""; - col = Color.red.getRGB(); - go = false; - } - }else{ - box.setTextColor(Color.black.getRGB()); - col = Color.white.getRGB(); - go = true; - - if(!(ClientConfigStorage.INSTANCE.deactivateTeleportation()||ClientConfigStorage.INSTANCE.getCost()==null)){ - String out = LanguageRegistry.instance().getStringLocalization("signpost.guiPrev"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.guiPrev", "en_US"); - } - int distance = (int) tile.toPos().distance(inf.teleportPosition)+1; - out = out.replaceAll("", ""+distance); - out = out.replaceAll("", Integer.toString(PostHandler.getStackSize(tile.toPos(), inf.teleportPosition))); - out = out.replaceAll("", ConfigHandler.costName()); - col = Color.white.getRGB(); - std = out; - } - } - } + if (!(ClientConfigStorage.INSTANCE.deactivateTeleportation() + || ClientConfigStorage.INSTANCE.getCost() == null)) { + String out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiPrev"); + if (out.equals("")) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiPrev", "en_US"); + } + int distance = (int) tile.toPos() + .distance(inf.teleportPosition) + 1; + out = out.replaceAll("", "" + distance); + out = out.replaceAll( + "", + Integer.toString(PostHandler.getStackSize(tile.toPos(), inf.teleportPosition))); + out = out.replaceAll("", ConfigHandler.costName()); + col = Color.white.getRGB(); + std = out; + } + } + } } diff --git a/src/main/java/gollorum/signpost/gui/SignGuiHandler.java b/src/main/java/gollorum/signpost/gui/SignGuiHandler.java index daad8d38..dea43dc0 100644 --- a/src/main/java/gollorum/signpost/gui/SignGuiHandler.java +++ b/src/main/java/gollorum/signpost/gui/SignGuiHandler.java @@ -1,41 +1,42 @@ package gollorum.signpost.gui; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + import cpw.mods.fml.common.network.IGuiHandler; import gollorum.signpost.Signpost; import gollorum.signpost.blocks.WaystoneContainer; import gollorum.signpost.blocks.tiles.BigPostPostTile; import gollorum.signpost.blocks.tiles.PostPostTile; import gollorum.signpost.blocks.tiles.SuperPostPostTile; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; public class SignGuiHandler implements IGuiHandler { - @Override - public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { - return null; - } + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + return null; + } - @Override - public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { - TileEntity ti = world.getTileEntity(x, y, z); - if(ti == null) return null; - switch (ID) { - case Signpost.GuiBaseID: - return new SignGuiBase((WaystoneContainer) ti); - case Signpost.GuiPostID: - return new SignGuiPost((PostPostTile) ti); - case Signpost.GuiBigPostID: - return new SignGuiBigPost((BigPostPostTile) ti); - case Signpost.GuiPostBrushID: - SuperPostPostTile tile = (SuperPostPostTile) ti; - return new SignGuiPaint(tile.getPaintable(player), tile); - case Signpost.GuiPostRotationID: - tile = (SuperPostPostTile) ti; - return new SignGuiRotation(tile.getSign(player), tile); - } - return null; - } + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity ti = world.getTileEntity(x, y, z); + if (ti == null) return null; + switch (ID) { + case Signpost.GuiBaseID: + return new SignGuiBase((WaystoneContainer) ti); + case Signpost.GuiPostID: + return new SignGuiPost((PostPostTile) ti); + case Signpost.GuiBigPostID: + return new SignGuiBigPost((BigPostPostTile) ti); + case Signpost.GuiPostBrushID: + SuperPostPostTile tile = (SuperPostPostTile) ti; + return new SignGuiPaint(tile.getPaintable(player), tile); + case Signpost.GuiPostRotationID: + tile = (SuperPostPostTile) ti; + return new SignGuiRotation(tile.getSign(player), tile); + } + return null; + } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/gui/SignGuiPaint.java b/src/main/java/gollorum/signpost/gui/SignGuiPaint.java index 92619601..1f78e8ce 100644 --- a/src/main/java/gollorum/signpost/gui/SignGuiPaint.java +++ b/src/main/java/gollorum/signpost/gui/SignGuiPaint.java @@ -1,146 +1,151 @@ package gollorum.signpost.gui; +import java.util.HashSet; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.util.ResourceLocation; + import cpw.mods.fml.client.FMLClientHandler; import gollorum.signpost.SPEventHandler; import gollorum.signpost.blocks.SuperPostPost; import gollorum.signpost.blocks.tiles.SuperPostPostTile; import gollorum.signpost.util.BoolRun; import gollorum.signpost.util.Paintable; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.util.ResourceLocation; - -import java.util.HashSet; public class SignGuiPaint extends GuiScreen { - private GuiTextField nameInputBox; - private Paintable paintable; - private SuperPostPostTile tile; - - private HashSet possibilities = new HashSet<>(); - private int possibleCount = 0; - private int possibleIndex = 0; - - private boolean resetMouse; - - public SignGuiPaint(Paintable paintable, SuperPostPostTile tile) { - this.paintable = paintable; - this.tile = tile; - initGui(); - } - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - if(mc==null){ - mc = FMLClientHandler.instance().getClient(); - } - if(nameInputBox==null){ - initGui(); - } - drawDefaultBackground(); - if(nameInputBox.getText() == null || nameInputBox.getText().equals("null")){ - ResourceLocation loc = paintable==null ? tile.getPostPaint() : paintable.getTexture(); - String name; - if(loc==null){ - name = ""; - }else{ - name = SuperPostPostTile.locToString(loc); - } - nameInputBox.setText(name); - } - - try{ - nameInputBox.drawTextBox(); - }catch(Exception e){} - - if(resetMouse){ - resetMouse = false; - org.lwjgl.input.Mouse.setGrabbed(false); - } - super.drawScreen(mouseX, mouseY, partialTicks); - } - - @Override - public boolean doesGuiPauseGame() { - return false; - } - - @Override - public void initGui() { - SPEventHandler.scheduleTask(new BoolRun(){ - @Override - public boolean run(){ - if(fontRendererObj==null){ - return false; - } - nameInputBox = new GuiTextField(fontRendererObj, width/4, height/2 - 46, width/2, 20); - nameInputBox.setMaxStringLength(100); - ResourceLocation loc = paintable==null ? tile.getPostPaint() : paintable.getTexture(); - String name; - if(loc==null){ - name = ""; - }else{ - name = SuperPostPostTile.locToString(loc); - } - nameInputBox.setText(name); - return true; - } - }); - nameInputBox = new GuiTextField(this.fontRendererObj, this.width/4, this.height/2 - 46, this.width/2, 20); - nameInputBox.setMaxStringLength(100); - if(mc==null){ - mc = FMLClientHandler.instance().getClient(); - } - ResourceLocation loc = paintable==null ? tile.getPostPaint() : paintable.getTexture(); - String name; - if(loc==null){ - name = ""; - }else{ - name = SuperPostPostTile.locToString(loc); - } - nameInputBox.setText(name); - nameInputBox.setFocused(true); - - resetMouse = true; - } - - @Override - protected void keyTyped(char par1, int par2) { - if(par1==13){ - this.mc.displayGuiScreen(null); - return; - } - super.keyTyped(par1, par2); - this.nameInputBox.textboxKeyTyped(par1, par2); - } - - @Override - public void updateScreen() { - super.updateScreen(); - this.nameInputBox.updateCursorCounter(); - } - - public void updateName(String newName) { - if (nameInputBox != null) { - nameInputBox.setText(newName); - } - } - - @Override - protected void mouseClicked(int x, int y, int btn) { - super.mouseClicked(x, y, btn); - this.nameInputBox.mouseClicked(x, y, btn); - } - - @Override - public void onGuiClosed() { - super.onGuiClosed(); - if(paintable!=null){ - paintable.setTexture(new ResourceLocation(nameInputBox.getText())); - }else{ - tile.setPostPaint(new ResourceLocation(nameInputBox.getText())); - } - ((SuperPostPost)tile.blockType).sendPostBasesToServer(tile); - } + private GuiTextField nameInputBox; + private Paintable paintable; + private SuperPostPostTile tile; + + private HashSet possibilities = new HashSet<>(); + private int possibleCount = 0; + private int possibleIndex = 0; + + private boolean resetMouse; + + public SignGuiPaint(Paintable paintable, SuperPostPostTile tile) { + this.paintable = paintable; + this.tile = tile; + initGui(); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + if (mc == null) { + mc = FMLClientHandler.instance() + .getClient(); + } + if (nameInputBox == null) { + initGui(); + } + drawDefaultBackground(); + if (nameInputBox.getText() == null || nameInputBox.getText() + .equals("null")) { + ResourceLocation loc = paintable == null ? tile.getPostPaint() : paintable.getTexture(); + String name; + if (loc == null) { + name = ""; + } else { + name = SuperPostPostTile.locToString(loc); + } + nameInputBox.setText(name); + } + + try { + nameInputBox.drawTextBox(); + } catch (Exception e) {} + + if (resetMouse) { + resetMouse = false; + org.lwjgl.input.Mouse.setGrabbed(false); + } + super.drawScreen(mouseX, mouseY, partialTicks); + } + + @Override + public boolean doesGuiPauseGame() { + return false; + } + + @Override + public void initGui() { + SPEventHandler.scheduleTask(new BoolRun() { + + @Override + public boolean run() { + if (fontRendererObj == null) { + return false; + } + nameInputBox = new GuiTextField(fontRendererObj, width / 4, height / 2 - 46, width / 2, 20); + nameInputBox.setMaxStringLength(100); + ResourceLocation loc = paintable == null ? tile.getPostPaint() : paintable.getTexture(); + String name; + if (loc == null) { + name = ""; + } else { + name = SuperPostPostTile.locToString(loc); + } + nameInputBox.setText(name); + return true; + } + }); + nameInputBox = new GuiTextField(this.fontRendererObj, this.width / 4, this.height / 2 - 46, this.width / 2, 20); + nameInputBox.setMaxStringLength(100); + if (mc == null) { + mc = FMLClientHandler.instance() + .getClient(); + } + ResourceLocation loc = paintable == null ? tile.getPostPaint() : paintable.getTexture(); + String name; + if (loc == null) { + name = ""; + } else { + name = SuperPostPostTile.locToString(loc); + } + nameInputBox.setText(name); + nameInputBox.setFocused(true); + + resetMouse = true; + } + + @Override + protected void keyTyped(char par1, int par2) { + if (par1 == 13) { + this.mc.displayGuiScreen(null); + return; + } + super.keyTyped(par1, par2); + this.nameInputBox.textboxKeyTyped(par1, par2); + } + + @Override + public void updateScreen() { + super.updateScreen(); + this.nameInputBox.updateCursorCounter(); + } + + public void updateName(String newName) { + if (nameInputBox != null) { + nameInputBox.setText(newName); + } + } + + @Override + protected void mouseClicked(int x, int y, int btn) { + super.mouseClicked(x, y, btn); + this.nameInputBox.mouseClicked(x, y, btn); + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + if (paintable != null) { + paintable.setTexture(new ResourceLocation(nameInputBox.getText())); + } else { + tile.setPostPaint(new ResourceLocation(nameInputBox.getText())); + } + ((SuperPostPost) tile.blockType).sendPostBasesToServer(tile); + } } diff --git a/src/main/java/gollorum/signpost/gui/SignGuiPost.java b/src/main/java/gollorum/signpost/gui/SignGuiPost.java index 53a48a66..cc18c5a3 100644 --- a/src/main/java/gollorum/signpost/gui/SignGuiPost.java +++ b/src/main/java/gollorum/signpost/gui/SignGuiPost.java @@ -2,6 +2,8 @@ import java.awt.Color; +import net.minecraft.client.gui.GuiScreen; + import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.registry.LanguageRegistry; import gollorum.signpost.blocks.tiles.PostPostTile; @@ -13,231 +15,256 @@ import gollorum.signpost.util.BaseInfo; import gollorum.signpost.util.DoubleBaseInfo; import gollorum.signpost.util.MyBlockPos.Connection; -import net.minecraft.client.gui.GuiScreen; public class SignGuiPost extends GuiScreen implements SignInput { - private SignInputBox base1InputBox; - private SignInputBox base2InputBox; - - private String std1 = ""; - private int col1 = Color.black.getRGB(); - private boolean go1; - - private String std2 = ""; - private int col2 = Color.black.getRGB(); - private boolean go2; - - private PostPostTile tile; - - private boolean resetMouse; - - public SignGuiPost(PostPostTile tile) { - this.tile = tile; - initGui(); - } - - @Override - public void initGui() { - setupInputBox1(); - setupInputBox2(); - resetMouse = true; - base1InputBox.setFocused(true); - } - - private void setupInputBox1() { - DoubleBaseInfo tilebases = tile.getBases(); - base1InputBox = new SignInputBox(this.fontRendererObj, this.width / 2 - 68, this.height / 2 - 46, 137, this); - base1InputBox.setText(tilebases.sign1.base==null?"":tilebases.sign1.base.toString()); - go1 = true; - } - - private void setupInputBox2() { - DoubleBaseInfo tilebases = tile.getBases(); - base2InputBox = new SignInputBox(this.fontRendererObj, this.width / 2 - 68, this.height / 2 + 40, 137, this); - base2InputBox.setText(tilebases.sign2.base==null?"":tilebases.sign2.base.toString()); - go2 = true; - } - - @Override - protected void mouseClicked(int x, int y, int bla){ - super.mouseClicked(x, y, bla); - base1InputBox.mouseClicked(x, y, bla); - base2InputBox.mouseClicked(x, y, bla); - } - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - super.drawScreen(mouseX, mouseY, partialTicks); - try{ - if(mc==null){ - mc = FMLClientHandler.instance().getClient(); - } - if (base1InputBox == null) { - setupInputBox1(); - } - if (base2InputBox == null) { - setupInputBox2(); - } - drawDefaultBackground(); - - base1InputBox.drawSignBox(fontRendererObj); - this.drawCenteredString(fontRendererObj, std2, this.width/2, base1InputBox.y+base1InputBox.height+10, col2); - - base2InputBox.drawSignBox(fontRendererObj); - this.drawCenteredString(fontRendererObj, std1, this.width/2, base2InputBox.y+base2InputBox.height+10, col1); - - if(resetMouse){ - resetMouse = false; - org.lwjgl.input.Mouse.setGrabbed(false); - } - }catch(Exception e){} - } - - @Override - protected void keyTyped(char par1, int par2) { - super.keyTyped(par1, par2); - if(par1==13){ - if(base1InputBox.isFocused()){ - if(!go2){ - go2=true; - base1InputBox.textColor = Color.orange.getRGB(); - } - base1InputBox.setFocused(false); - base2InputBox.setFocused(true); - }else if(base2InputBox.isFocused()){ - if(!go1){ - go1=true; - base2InputBox.textColor = Color.orange.getRGB(); - } - this.mc.displayGuiScreen(null); - }else{ - base1InputBox.setFocused(true); - } - return; - }else if(par1==9){ - if(base1InputBox.isFocused()){ - base1InputBox.setFocused(false); - base2InputBox.setFocused(true); - }else if(base2InputBox.isFocused()){ - base2InputBox.setFocused(false); - base1InputBox.setFocused(true); - }else{ - base1InputBox.setFocused(true); - } - return; - } - baseType(par1, par2, false); - baseType(par1, par2, true); - } - - private void baseType(char par1, int par2, boolean base2){ - SignInputBox tf = base2?base2InputBox:base1InputBox; - String before = tf.getText(); - if(tf.textboxKeyTyped(par1, par2)&&!tf.getText().equals(before)){ - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()){ - return; - } - onTextChange(tf); - } - } - - @Override - public void onTextChange(SignInputBox box){ - boolean base2 = box==base2InputBox; - BaseInfo inf = PostHandler.getWSbyName(box.getText()); - Connection connect = tile.toPos().canConnectTo(inf); - if(inf==null||!connect.equals(Connection.VALID)){ - box.textColor = Color.red.getRGB(); - if(connect.equals(Connection.DIST)){ - - String out = LanguageRegistry.instance().getStringLocalization("signpost.guiTooFar"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.guiTooFar", "en_US"); - } - out = out.replaceAll("", ""+(int)tile.toPos().distance(inf.teleportPosition)+1); - out = out.replaceAll("", ""+ClientConfigStorage.INSTANCE.getMaxDist()); - if(base2){ - std1 = out; - col1 = Color.red.getRGB(); - go1 = false; - }else{ - std2 = out; - col2 = Color.red.getRGB(); - go2 = false; - } - - }else if(connect.equals(Connection.WORLD)){ - - String out = LanguageRegistry.instance().getStringLocalization("signpost.guiWorldDim"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.guiWorldDim", "en_US"); - } - if(base2){ - std1 = out; - col1 = Color.red.getRGB(); - go1 = false; - }else{ - std2 = out; - col2 = Color.red.getRGB(); - go2 = false; - } - - }else{ - if(base2){ - std1 = ""; - col1 = Color.red.getRGB(); - go1 = false; - }else{ - std2 = ""; - col2 = Color.red.getRGB(); - go2 = false; - } - } - }else{ - box.textColor = Color.black.getRGB(); - if(base2){ - col1 = Color.white.getRGB(); - go1 = true; - }else{ - col2 = Color.white.getRGB(); - go2 = true; - } - - if(!(ClientConfigStorage.INSTANCE.deactivateTeleportation()||ClientConfigStorage.INSTANCE.getCost()==null)){ - String out = LanguageRegistry.instance().getStringLocalization("signpost.guiPrev"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.guiPrev", "en_US"); - } - int distance = (int) tile.toPos().distance(inf.teleportPosition)+1; - out = out.replaceAll("", ""+distance); - out = out.replaceAll("", Integer.toString(PostHandler.getStackSize(tile.toPos(), inf.teleportPosition))); - out = out.replaceAll("", ConfigHandler.costName()); - if(base2){ - col1 = Color.white.getRGB(); - std1 = out; - }else{ - col2 = Color.white.getRGB(); - std2 = out; - } - } - } - } - - @Override - public void onGuiClosed() { - DoubleBaseInfo tilebases = tile.getBases(); - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()||go2){ - tilebases.sign1.base = PostHandler.getForceWSbyName(base1InputBox.getText()); - }else{ - tilebases.sign1.base = null; - } - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()||go1){ - tilebases.sign2.base = PostHandler.getForceWSbyName(base2InputBox.getText()); - }else{ - tilebases.sign2.base = null; - } - NetworkHandler.netWrap.sendToServer(new SendPostBasesMessage(tile, tilebases)); - } - + private SignInputBox base1InputBox; + private SignInputBox base2InputBox; + + private String std1 = ""; + private int col1 = Color.black.getRGB(); + private boolean go1; + + private String std2 = ""; + private int col2 = Color.black.getRGB(); + private boolean go2; + + private PostPostTile tile; + + private boolean resetMouse; + + public SignGuiPost(PostPostTile tile) { + this.tile = tile; + initGui(); + } + + @Override + public void initGui() { + setupInputBox1(); + setupInputBox2(); + resetMouse = true; + base1InputBox.setFocused(true); + } + + private void setupInputBox1() { + DoubleBaseInfo tilebases = tile.getBases(); + base1InputBox = new SignInputBox(this.fontRendererObj, this.width / 2 - 68, this.height / 2 - 46, 137, this); + base1InputBox.setText(tilebases.sign1.base == null ? "" : tilebases.sign1.base.toString()); + go1 = true; + } + + private void setupInputBox2() { + DoubleBaseInfo tilebases = tile.getBases(); + base2InputBox = new SignInputBox(this.fontRendererObj, this.width / 2 - 68, this.height / 2 + 40, 137, this); + base2InputBox.setText(tilebases.sign2.base == null ? "" : tilebases.sign2.base.toString()); + go2 = true; + } + + @Override + protected void mouseClicked(int x, int y, int bla) { + super.mouseClicked(x, y, bla); + base1InputBox.mouseClicked(x, y, bla); + base2InputBox.mouseClicked(x, y, bla); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + super.drawScreen(mouseX, mouseY, partialTicks); + try { + if (mc == null) { + mc = FMLClientHandler.instance() + .getClient(); + } + if (base1InputBox == null) { + setupInputBox1(); + } + if (base2InputBox == null) { + setupInputBox2(); + } + drawDefaultBackground(); + + base1InputBox.drawSignBox(fontRendererObj); + this.drawCenteredString( + fontRendererObj, + std2, + this.width / 2, + base1InputBox.y + base1InputBox.height + 10, + col2); + + base2InputBox.drawSignBox(fontRendererObj); + this.drawCenteredString( + fontRendererObj, + std1, + this.width / 2, + base2InputBox.y + base2InputBox.height + 10, + col1); + + if (resetMouse) { + resetMouse = false; + org.lwjgl.input.Mouse.setGrabbed(false); + } + } catch (Exception e) {} + } + + @Override + protected void keyTyped(char par1, int par2) { + super.keyTyped(par1, par2); + if (par1 == 13) { + if (base1InputBox.isFocused()) { + if (!go2) { + go2 = true; + base1InputBox.textColor = Color.orange.getRGB(); + } + base1InputBox.setFocused(false); + base2InputBox.setFocused(true); + } else if (base2InputBox.isFocused()) { + if (!go1) { + go1 = true; + base2InputBox.textColor = Color.orange.getRGB(); + } + this.mc.displayGuiScreen(null); + } else { + base1InputBox.setFocused(true); + } + return; + } else if (par1 == 9) { + if (base1InputBox.isFocused()) { + base1InputBox.setFocused(false); + base2InputBox.setFocused(true); + } else if (base2InputBox.isFocused()) { + base2InputBox.setFocused(false); + base1InputBox.setFocused(true); + } else { + base1InputBox.setFocused(true); + } + return; + } + baseType(par1, par2, false); + baseType(par1, par2, true); + } + + private void baseType(char par1, int par2, boolean base2) { + SignInputBox tf = base2 ? base2InputBox : base1InputBox; + String before = tf.getText(); + if (tf.textboxKeyTyped(par1, par2) && !tf.getText() + .equals(before)) { + if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + return; + } + onTextChange(tf); + } + } + + @Override + public void onTextChange(SignInputBox box) { + boolean base2 = box == base2InputBox; + BaseInfo inf = PostHandler.getWSbyName(box.getText()); + Connection connect = tile.toPos() + .canConnectTo(inf); + if (inf == null || !connect.equals(Connection.VALID)) { + box.textColor = Color.red.getRGB(); + if (connect.equals(Connection.DIST)) { + + String out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiTooFar"); + if (out.equals("")) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiTooFar", "en_US"); + } + out = out.replaceAll( + "", + "" + (int) tile.toPos() + .distance(inf.teleportPosition) + 1); + out = out.replaceAll("", "" + ClientConfigStorage.INSTANCE.getMaxDist()); + if (base2) { + std1 = out; + col1 = Color.red.getRGB(); + go1 = false; + } else { + std2 = out; + col2 = Color.red.getRGB(); + go2 = false; + } + + } else if (connect.equals(Connection.WORLD)) { + + String out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiWorldDim"); + if (out.equals("")) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiWorldDim", "en_US"); + } + if (base2) { + std1 = out; + col1 = Color.red.getRGB(); + go1 = false; + } else { + std2 = out; + col2 = Color.red.getRGB(); + go2 = false; + } + + } else { + if (base2) { + std1 = ""; + col1 = Color.red.getRGB(); + go1 = false; + } else { + std2 = ""; + col2 = Color.red.getRGB(); + go2 = false; + } + } + } else { + box.textColor = Color.black.getRGB(); + if (base2) { + col1 = Color.white.getRGB(); + go1 = true; + } else { + col2 = Color.white.getRGB(); + go2 = true; + } + + if (!(ClientConfigStorage.INSTANCE.deactivateTeleportation() + || ClientConfigStorage.INSTANCE.getCost() == null)) { + String out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiPrev"); + if (out.equals("")) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.guiPrev", "en_US"); + } + int distance = (int) tile.toPos() + .distance(inf.teleportPosition) + 1; + out = out.replaceAll("", "" + distance); + out = out.replaceAll( + "", + Integer.toString(PostHandler.getStackSize(tile.toPos(), inf.teleportPosition))); + out = out.replaceAll("", ConfigHandler.costName()); + if (base2) { + col1 = Color.white.getRGB(); + std1 = out; + } else { + col2 = Color.white.getRGB(); + std2 = out; + } + } + } + } + + @Override + public void onGuiClosed() { + DoubleBaseInfo tilebases = tile.getBases(); + if (ClientConfigStorage.INSTANCE.deactivateTeleportation() || go2) { + tilebases.sign1.base = PostHandler.getForceWSbyName(base1InputBox.getText()); + } else { + tilebases.sign1.base = null; + } + if (ClientConfigStorage.INSTANCE.deactivateTeleportation() || go1) { + tilebases.sign2.base = PostHandler.getForceWSbyName(base2InputBox.getText()); + } else { + tilebases.sign2.base = null; + } + NetworkHandler.netWrap.sendToServer(new SendPostBasesMessage(tile, tilebases)); + } + } diff --git a/src/main/java/gollorum/signpost/gui/SignGuiRotation.java b/src/main/java/gollorum/signpost/gui/SignGuiRotation.java index ab767e73..8e325454 100644 --- a/src/main/java/gollorum/signpost/gui/SignGuiRotation.java +++ b/src/main/java/gollorum/signpost/gui/SignGuiRotation.java @@ -2,191 +2,209 @@ import java.awt.Color; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiTextField; + import cpw.mods.fml.client.FMLClientHandler; import gollorum.signpost.blocks.SuperPostPost; import gollorum.signpost.blocks.tiles.SuperPostPostTile; import gollorum.signpost.util.Sign; import gollorum.signpost.util.math.tracking.DDDVector; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; public class SignGuiRotation extends GuiScreen { - private Sign sign; - private SuperPostPostTile tile; - - private GuiTextField degreesInputBox; - - private GuiTextField xInputBox; - private GuiTextField zInputBox; - - public SignGuiRotation(Sign sign, SuperPostPostTile tile){ - this.sign = sign; - this.tile = tile; - initGui(); - } - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - if(mc==null){ - mc = FMLClientHandler.instance().getClient(); - } - if(sign==null){ - this.mc.displayGuiScreen(null); - return; - } - if(degreesInputBox==null || xInputBox==null || zInputBox==null){ - initGui(); - } - drawDefaultBackground(); - if(degreesInputBox.getText() == null || degreesInputBox.getText().equals("null")){ - degreesInputBox.setText(""+sign.rotation); - } - String str = "Angle (degrees): "; - int stringwidth = fontRendererObj.getStringWidth(str); - fontRendererObj.drawString(str, degreesInputBox.xPosition-stringwidth, degreesInputBox.yPosition+(degreesInputBox.height-fontRendererObj.FONT_HEIGHT)/2, Color.white.getRGB()); - - str = "Block position to point to: X= "; - stringwidth = fontRendererObj.getStringWidth(str); - fontRendererObj.drawString(str, xInputBox.xPosition-stringwidth, xInputBox.yPosition+(xInputBox.height-fontRendererObj.FONT_HEIGHT)/2, Color.white.getRGB()); - - str = "Z= "; - stringwidth = fontRendererObj.getStringWidth(str); - fontRendererObj.drawString(str, zInputBox.xPosition-stringwidth, zInputBox.yPosition+(xInputBox.height-fontRendererObj.FONT_HEIGHT)/2, Color.white.getRGB()); - - degreesInputBox.drawTextBox(); - xInputBox.drawTextBox(); - zInputBox.drawTextBox(); - super.drawScreen(mouseX, mouseY, partialTicks); - } - - @Override - public boolean doesGuiPauseGame() { - return false; - } - - @Override - public void initGui() { - degreesInputBox = new GuiTextField(this.fontRendererObj, 140, this.height/2 - 46, this.width/2, 20); - degreesInputBox.setMaxStringLength(100); - xInputBox = new GuiTextField(this.fontRendererObj, this.width/2-20, this.height/2, 60, 20); - xInputBox.setMaxStringLength(100); - zInputBox = new GuiTextField(this.fontRendererObj, this.width/2+80, this.height/2, 60, 20); - zInputBox.setMaxStringLength(100); - if(mc==null){ - mc = FMLClientHandler.instance().getClient(); - } - if(sign==null){ - this.mc.displayGuiScreen(null); - return; - } - degreesInputBox.setText(""+sign.rotation); - degreesInputBox.setFocused(true); - xInputBox.setFocused(false); - zInputBox.setFocused(false); - } - - @Override - protected void keyTyped(char par1, int par2) { - if(par1==13){ - if(degreesInputBox.isFocused()){ - this.mc.displayGuiScreen(null); - }else if(xInputBox.isFocused()){ - xInputBox.setFocused(false); - zInputBox.setFocused(true); - }else if(zInputBox.isFocused()){ - try{ - double x = Double.parseDouble(xInputBox.getText()); - double z = Double.parseDouble(zInputBox.getText()); - double dx = x-tile.xCoord; - double dz = z-tile.zCoord; - double degree = Math.toDegrees(DDDVector.genAngle(dx, dz)+Math.toRadians(-90+(dx<0&&dz>0?180:0))); - degreesInputBox.setText(""+degree); - this.mc.displayGuiScreen(null); - }catch(Exception e2){} - } - return; - }else if(par1==9){ - if(degreesInputBox.isFocused()){ - degreesInputBox.setFocused(false); - xInputBox.setFocused(true); - }else if(xInputBox.isFocused()){ - xInputBox.setFocused(false); - zInputBox.setFocused(true); - }else{ - zInputBox.setFocused(false); - degreesInputBox.setFocused(true); - } - return; - } - super.keyTyped(par1, par2); - if(degreesInputBox.isFocused()){ - String txt = degreesInputBox.getText(); - this.degreesInputBox.textboxKeyTyped(par1, par2); - try{ - Double.parseDouble(degreesInputBox.getText()); - }catch(Exception e){ - try{ - Double.parseDouble(degreesInputBox.getText()+"0"); - }catch(Exception e2){ - degreesInputBox.setText(txt); - return; - } - } - return; - } - GuiTextField field; - if(xInputBox.isFocused()){ - field = xInputBox; - }else if(zInputBox.isFocused()){ - field = zInputBox; - }else{ - return; - } - String txt = field.getText(); - field.textboxKeyTyped(par1, par2); - try{ - Double.parseDouble(field.getText()); - try{ - double x = Double.parseDouble(xInputBox.getText()); - double z = Double.parseDouble(zInputBox.getText()); - double dx = x-tile.xCoord; - double dz = z-tile.zCoord; - double degree = Math.toDegrees(DDDVector.genAngle(dx, dz)+Math.toRadians(-90+(dx<0&&dz>0?180:0))); - degreesInputBox.setText(""+degree); - }catch(Exception e2){} - }catch(Exception e){ - try{ - Double.parseDouble(field.getText()+"0"); - }catch(Exception e2){ - field.setText(txt); - return; - } - } - } - - @Override - public void updateScreen() { - super.updateScreen(); - this.degreesInputBox.updateCursorCounter(); - this.xInputBox.updateCursorCounter(); - this.zInputBox.updateCursorCounter(); - } - - @Override - protected void mouseClicked(int x, int y, int btn) { - super.mouseClicked(x, y, btn); - this.degreesInputBox.mouseClicked(x, y, btn); - this.xInputBox.mouseClicked(x, y, btn); - this.zInputBox.mouseClicked(x, y, btn); - } - - @Override - public void onGuiClosed() { - try{ - sign.rotation = (int)Double.parseDouble(degreesInputBox.getText()); - ((SuperPostPost)tile.blockType).sendPostBasesToServer(tile); - }catch(Exception e){} - super.onGuiClosed(); - } + private Sign sign; + private SuperPostPostTile tile; + + private GuiTextField degreesInputBox; + + private GuiTextField xInputBox; + private GuiTextField zInputBox; + + public SignGuiRotation(Sign sign, SuperPostPostTile tile) { + this.sign = sign; + this.tile = tile; + initGui(); + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + if (mc == null) { + mc = FMLClientHandler.instance() + .getClient(); + } + if (sign == null) { + this.mc.displayGuiScreen(null); + return; + } + if (degreesInputBox == null || xInputBox == null || zInputBox == null) { + initGui(); + } + drawDefaultBackground(); + if (degreesInputBox.getText() == null || degreesInputBox.getText() + .equals("null")) { + degreesInputBox.setText("" + sign.rotation); + } + String str = "Angle (degrees): "; + int stringwidth = fontRendererObj.getStringWidth(str); + fontRendererObj.drawString( + str, + degreesInputBox.xPosition - stringwidth, + degreesInputBox.yPosition + (degreesInputBox.height - fontRendererObj.FONT_HEIGHT) / 2, + Color.white.getRGB()); + + str = "Block position to point to: X= "; + stringwidth = fontRendererObj.getStringWidth(str); + fontRendererObj.drawString( + str, + xInputBox.xPosition - stringwidth, + xInputBox.yPosition + (xInputBox.height - fontRendererObj.FONT_HEIGHT) / 2, + Color.white.getRGB()); + + str = "Z= "; + stringwidth = fontRendererObj.getStringWidth(str); + fontRendererObj.drawString( + str, + zInputBox.xPosition - stringwidth, + zInputBox.yPosition + (xInputBox.height - fontRendererObj.FONT_HEIGHT) / 2, + Color.white.getRGB()); + + degreesInputBox.drawTextBox(); + xInputBox.drawTextBox(); + zInputBox.drawTextBox(); + super.drawScreen(mouseX, mouseY, partialTicks); + } + + @Override + public boolean doesGuiPauseGame() { + return false; + } + + @Override + public void initGui() { + degreesInputBox = new GuiTextField(this.fontRendererObj, 140, this.height / 2 - 46, this.width / 2, 20); + degreesInputBox.setMaxStringLength(100); + xInputBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 20, this.height / 2, 60, 20); + xInputBox.setMaxStringLength(100); + zInputBox = new GuiTextField(this.fontRendererObj, this.width / 2 + 80, this.height / 2, 60, 20); + zInputBox.setMaxStringLength(100); + if (mc == null) { + mc = FMLClientHandler.instance() + .getClient(); + } + if (sign == null) { + this.mc.displayGuiScreen(null); + return; + } + degreesInputBox.setText("" + sign.rotation); + degreesInputBox.setFocused(true); + xInputBox.setFocused(false); + zInputBox.setFocused(false); + } + + @Override + protected void keyTyped(char par1, int par2) { + if (par1 == 13) { + if (degreesInputBox.isFocused()) { + this.mc.displayGuiScreen(null); + } else if (xInputBox.isFocused()) { + xInputBox.setFocused(false); + zInputBox.setFocused(true); + } else if (zInputBox.isFocused()) { + try { + double x = Double.parseDouble(xInputBox.getText()); + double z = Double.parseDouble(zInputBox.getText()); + double dx = x - tile.xCoord; + double dz = z - tile.zCoord; + double degree = Math + .toDegrees(DDDVector.genAngle(dx, dz) + Math.toRadians(-90 + (dx < 0 && dz > 0 ? 180 : 0))); + degreesInputBox.setText("" + degree); + this.mc.displayGuiScreen(null); + } catch (Exception e2) {} + } + return; + } else if (par1 == 9) { + if (degreesInputBox.isFocused()) { + degreesInputBox.setFocused(false); + xInputBox.setFocused(true); + } else if (xInputBox.isFocused()) { + xInputBox.setFocused(false); + zInputBox.setFocused(true); + } else { + zInputBox.setFocused(false); + degreesInputBox.setFocused(true); + } + return; + } + super.keyTyped(par1, par2); + if (degreesInputBox.isFocused()) { + String txt = degreesInputBox.getText(); + this.degreesInputBox.textboxKeyTyped(par1, par2); + try { + Double.parseDouble(degreesInputBox.getText()); + } catch (Exception e) { + try { + Double.parseDouble(degreesInputBox.getText() + "0"); + } catch (Exception e2) { + degreesInputBox.setText(txt); + return; + } + } + return; + } + GuiTextField field; + if (xInputBox.isFocused()) { + field = xInputBox; + } else if (zInputBox.isFocused()) { + field = zInputBox; + } else { + return; + } + String txt = field.getText(); + field.textboxKeyTyped(par1, par2); + try { + Double.parseDouble(field.getText()); + try { + double x = Double.parseDouble(xInputBox.getText()); + double z = Double.parseDouble(zInputBox.getText()); + double dx = x - tile.xCoord; + double dz = z - tile.zCoord; + double degree = Math + .toDegrees(DDDVector.genAngle(dx, dz) + Math.toRadians(-90 + (dx < 0 && dz > 0 ? 180 : 0))); + degreesInputBox.setText("" + degree); + } catch (Exception e2) {} + } catch (Exception e) { + try { + Double.parseDouble(field.getText() + "0"); + } catch (Exception e2) { + field.setText(txt); + return; + } + } + } + + @Override + public void updateScreen() { + super.updateScreen(); + this.degreesInputBox.updateCursorCounter(); + this.xInputBox.updateCursorCounter(); + this.zInputBox.updateCursorCounter(); + } + + @Override + protected void mouseClicked(int x, int y, int btn) { + super.mouseClicked(x, y, btn); + this.degreesInputBox.mouseClicked(x, y, btn); + this.xInputBox.mouseClicked(x, y, btn); + this.zInputBox.mouseClicked(x, y, btn); + } + + @Override + public void onGuiClosed() { + try { + sign.rotation = (int) Double.parseDouble(degreesInputBox.getText()); + ((SuperPostPost) tile.blockType).sendPostBasesToServer(tile); + } catch (Exception e) {} + super.onGuiClosed(); + } } diff --git a/src/main/java/gollorum/signpost/gui/SignInput.java b/src/main/java/gollorum/signpost/gui/SignInput.java index 7850c951..52cb72cf 100644 --- a/src/main/java/gollorum/signpost/gui/SignInput.java +++ b/src/main/java/gollorum/signpost/gui/SignInput.java @@ -2,6 +2,6 @@ public interface SignInput { - public void onTextChange(SignInputBox box); - + public void onTextChange(SignInputBox box); + } diff --git a/src/main/java/gollorum/signpost/gui/SignInputBox.java b/src/main/java/gollorum/signpost/gui/SignInputBox.java index 81e91a72..c26c0411 100644 --- a/src/main/java/gollorum/signpost/gui/SignInputBox.java +++ b/src/main/java/gollorum/signpost/gui/SignInputBox.java @@ -4,12 +4,6 @@ import java.util.ArrayList; import java.util.Collection; -import org.lwjgl.opengl.GL11; - -import cpw.mods.fml.client.FMLClientHandler; -import gollorum.signpost.management.PostHandler; -import gollorum.signpost.modIntegration.SignpostAdapter; -import gollorum.signpost.util.BaseInfo; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiScreen; @@ -17,201 +11,210 @@ import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.ResourceLocation; -public class SignInputBox extends Gui{ - - private static final double pWidth = 25.0; - private static final double pHeight = 6.0; - private static final double verh = pWidth/pHeight; - - public int x; - public int y; - public int width; - public int height; - private boolean isFocused = false; +import org.lwjgl.opengl.GL11; + +import cpw.mods.fml.client.FMLClientHandler; +import gollorum.signpost.management.PostHandler; + +public class SignInputBox extends Gui { + + private static final double pWidth = 25.0; + private static final double pHeight = 6.0; + private static final double verh = pWidth / pHeight; + + public int x; + public int y; + public int width; + public int height; + private boolean isFocused = false; private int cursorPosition; - + private ArrayList possible = new ArrayList(); private int cycleTime = 1000; private long lastSystemTime; private int possibleIndex = 0; - + public int textColor = 0; private int cursorCycleTime = 500; public int drawXat; public double scc; - public float[] boxColor = {1f, 1f, 1f, 1f}; - + public float[] boxColor = { 1f, 1f, 1f, 1f }; + private static final ResourceLocation texture = new ResourceLocation("signpost:textures/gui/sign_gui.png"); - - private FontRenderer fontRenderer; - - public String text = ""; - - private final SignInput PARENT; - - public SignInputBox(FontRenderer p_i1032_1_, int x, int y, int width, SignInput parent) { - this.fontRenderer = p_i1032_1_; - this.x = x; - this.y = y; - this.width = width; - this.height = (int) (width/verh); - PARENT = parent; - setText(""); - lastSystemTime = System.currentTimeMillis(); - } - - public void setFocused(boolean bool){ - isFocused = bool; - cursorPosition = getText().length(); - } - - public boolean isFocused(){ - return isFocused; - } - - public void drawSignBox(FontRenderer fontRend){ - this.fontRenderer = fontRend; - GL11.glColor4f(boxColor[0], boxColor[1], boxColor[2], boxColor[3]); - FMLClientHandler.instance().getClient().renderEngine.bindTexture(texture); - drawTexturedModalRect(this.x, this.y, 0, 0, width, height); - if(fontRend!=null){ - drawText(); - } - } - - @Override - public void drawTexturedModalRect(int x, int y, int u, int v, int width, int height){ + + private FontRenderer fontRenderer; + + public String text = ""; + + private final SignInput PARENT; + + public SignInputBox(FontRenderer p_i1032_1_, int x, int y, int width, SignInput parent) { + this.fontRenderer = p_i1032_1_; + this.x = x; + this.y = y; + this.width = width; + this.height = (int) (width / verh); + PARENT = parent; + setText(""); + lastSystemTime = System.currentTimeMillis(); + } + + public void setFocused(boolean bool) { + isFocused = bool; + cursorPosition = getText().length(); + } + + public boolean isFocused() { + return isFocused; + } + + public void drawSignBox(FontRenderer fontRend) { + this.fontRenderer = fontRend; + GL11.glColor4f(boxColor[0], boxColor[1], boxColor[2], boxColor[3]); + FMLClientHandler.instance() + .getClient().renderEngine.bindTexture(texture); + drawTexturedModalRect(this.x, this.y, 0, 0, width, height); + if (fontRend != null) { + drawText(); + } + } + + @Override + public void drawTexturedModalRect(int x, int y, int u, int v, int width, int height) { float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)(x), (double)(y+height), (double)this.zLevel, 0.0, 1.0); - tessellator.addVertexWithUV((double)(x+width), (double)(y+height), (double)this.zLevel, 1.0, 1.0); - tessellator.addVertexWithUV((double)(x+width), (double)(y), (double)this.zLevel, 1.0, 0.0); - tessellator.addVertexWithUV((double)(x), (double)(y), (double)this.zLevel, 0.0, 0.0); + tessellator.addVertexWithUV((double) (x), (double) (y + height), (double) this.zLevel, 0.0, 1.0); + tessellator.addVertexWithUV((double) (x + width), (double) (y + height), (double) this.zLevel, 1.0, 1.0); + tessellator.addVertexWithUV((double) (x + width), (double) (y), (double) this.zLevel, 1.0, 0.0); + tessellator.addVertexWithUV((double) (x), (double) (y), (double) this.zLevel, 0.0, 0.0); tessellator.draw(); } - - public void drawText(){ - String txt; - if(drawCursor() && isFocused){ - txt = getText().substring(0, cursorPosition)+"|"+getText().substring(cursorPosition); - }else{ - txt = getText(); - } - double scale = this.width/pWidth; - double x = this.x+(this.width)/2.0-scale; - double y = this.y+(this.height)/2.0+scale/4; - double sc2 = 100d/fontRenderer.getStringWidth(txt); - if(sc2>=1){ - sc2 = 1; - } - scc = sc2; - GL11.glPushMatrix(); - GL11.glScaled(sc2, sc2, 1); - if(sc2==1.0){ - drawXat = (int) (x = (x-fontRenderer.getStringWidth(txt)/2.0)); - }else{ - drawXat = (int) (x-50); - x = (x-50)/sc2; - } -// sc2*=2.0; - fontRenderer.drawString(txt, (int) x, (int) ((y-fontRenderer.FONT_HEIGHT/2.0*sc2)/sc2), textColor); - GL11.glPopMatrix(); - - if(isFocused && possible.size()>0){ - if(cycleTimeHasPassed()){ - possibleIndex = possibleIndex+1; - } - lastSystemTime = System.currentTimeMillis(); - possibleIndex = possibleIndex%possible.size(); - fontRenderer.drawString(possible.get(possibleIndex), (int)(this.x+width+5), (int)(this.y+(scale*pHeight-fontRenderer.FONT_HEIGHT)/2.0), Color.WHITE.getRGB()); - } - } - - private boolean drawCursor(){ - return (System.currentTimeMillis() / cursorCycleTime) % 2 == 0; - } - - private boolean cycleTimeHasPassed() { - return (System.currentTimeMillis() % cycleTime) <= System.currentTimeMillis() - lastSystemTime; - } - - public void setText(String text){ - this.text = text; - possible = new ArrayList(); - for(String name: getAllPossibilities()){ - if(name.contains(getText()) || getText().equals("")){ - possible.add(name); - } - } - } - - public static Collection getAllPossibilities(){ - return PostHandler.getAllWaystoneNames(); - } - - public String getText(){ - if(text==null){ - text = ""; - } - return text; - } - - public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_){ - if (!this.isFocused){ + + public void drawText() { + String txt; + if (drawCursor() && isFocused) { + txt = getText().substring(0, cursorPosition) + "|" + getText().substring(cursorPosition); + } else { + txt = getText(); + } + double scale = this.width / pWidth; + double x = this.x + (this.width) / 2.0 - scale; + double y = this.y + (this.height) / 2.0 + scale / 4; + double sc2 = 100d / fontRenderer.getStringWidth(txt); + if (sc2 >= 1) { + sc2 = 1; + } + scc = sc2; + GL11.glPushMatrix(); + GL11.glScaled(sc2, sc2, 1); + if (sc2 == 1.0) { + drawXat = (int) (x = (x - fontRenderer.getStringWidth(txt) / 2.0)); + } else { + drawXat = (int) (x - 50); + x = (x - 50) / sc2; + } + // sc2*=2.0; + fontRenderer.drawString(txt, (int) x, (int) ((y - fontRenderer.FONT_HEIGHT / 2.0 * sc2) / sc2), textColor); + GL11.glPopMatrix(); + + if (isFocused && possible.size() > 0) { + if (cycleTimeHasPassed()) { + possibleIndex = possibleIndex + 1; + } + lastSystemTime = System.currentTimeMillis(); + possibleIndex = possibleIndex % possible.size(); + fontRenderer.drawString( + possible.get(possibleIndex), + (int) (this.x + width + 5), + (int) (this.y + (scale * pHeight - fontRenderer.FONT_HEIGHT) / 2.0), + Color.WHITE.getRGB()); + } + } + + private boolean drawCursor() { + return (System.currentTimeMillis() / cursorCycleTime) % 2 == 0; + } + + private boolean cycleTimeHasPassed() { + return (System.currentTimeMillis() % cycleTime) <= System.currentTimeMillis() - lastSystemTime; + } + + public void setText(String text) { + this.text = text; + possible = new ArrayList(); + for (String name : getAllPossibilities()) { + if (name.contains(getText()) || getText().equals("")) { + possible.add(name); + } + } + } + + public static Collection getAllPossibilities() { + return PostHandler.getAllWaystoneNames(); + } + + public String getText() { + if (text == null) { + text = ""; + } + return text; + } + + public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_) { + if (!this.isFocused) { return false; - }else{ - switch (p_146201_1_){ + } else { + switch (p_146201_1_) { case 1: - cursorPosition = getText().length(); + cursorPosition = getText().length(); return true; case 22: this.writeText(GuiScreen.getClipboardString()); return true; default: - switch (p_146201_2_){ - case 14: - if (GuiScreen.isCtrlKeyDown()){ - this.deleteWords(-1); - }else{ - this.deleteFromCursor(-1); - } - return true; + switch (p_146201_2_) { + case 14: + if (GuiScreen.isCtrlKeyDown()) { + this.deleteWords(-1); + } else { + this.deleteFromCursor(-1); + } + return true; case 199: cursorPosition = 0; return true; case 203: - if (GuiScreen.isCtrlKeyDown()){ + if (GuiScreen.isCtrlKeyDown()) { this.setCursorPosition(this.getNthWordFromCursor(-1)); - }else{ + } else { this.moveCursorBy(-1); } return true; case 205: - if (GuiScreen.isCtrlKeyDown()){ + if (GuiScreen.isCtrlKeyDown()) { this.setCursorPosition(this.getNthWordFromCursor(1)); - }else{ + } else { this.moveCursorBy(1); } return true; case 207: - cursorPosition = getText().length(); + cursorPosition = getText().length(); return true; case 211: - if (GuiScreen.isCtrlKeyDown()){ + if (GuiScreen.isCtrlKeyDown()) { this.deleteWords(1); - } - else{ - this.deleteFromCursor(1); + } else { + this.deleteFromCursor(1); } return true; default: - if (ChatAllowedCharacters.isAllowedCharacter(p_146201_1_)){ - this.writeText(Character.toString(p_146201_1_)); + if (ChatAllowedCharacters.isAllowedCharacter(p_146201_1_)) { + this.writeText(Character.toString(p_146201_1_)); return true; - }else{ + } else { return false; } } @@ -219,97 +222,100 @@ public boolean textboxKeyTyped(char p_146201_1_, int p_146201_2_){ } } - public void writeText(String p_146191_1_){ + public void writeText(String p_146191_1_) { String s2 = ChatAllowedCharacters.filerAllowedCharacters(p_146191_1_); - this.setText(getText().substring(0, cursorPosition)+s2+getText().substring(cursorPosition)); + this.setText(getText().substring(0, cursorPosition) + s2 + getText().substring(cursorPosition)); this.moveCursorBy(s2.length()); } - public void moveCursorBy(int p_146182_1_){ + public void moveCursorBy(int p_146182_1_) { this.setCursorPosition(cursorPosition + p_146182_1_); } - public void setCursorPosition(int p_146190_1_){ + public void setCursorPosition(int p_146190_1_) { this.cursorPosition = p_146190_1_; - int j = this.getText().length(); + int j = this.getText() + .length(); - if (this.cursorPosition < 0){ + if (this.cursorPosition < 0) { this.cursorPosition = 0; - }else if (this.cursorPosition > j){ + } else if (this.cursorPosition > j) { this.cursorPosition = j; } } - public void deleteFromCursor(int p_146175_1_){ - if (this.getText().length() != 0){ - boolean flag = p_146175_1_ < 0; - int j = flag ? this.cursorPosition + p_146175_1_ : this.cursorPosition; - int k = flag ? this.cursorPosition : this.cursorPosition + p_146175_1_; - String s = ""; - - if (j >= 0){ - s = this.getText().substring(0, j); - } - - if (k < this.getText().length()){ - s = s + this.getText().substring(k); - } - - this.setText(s); - - if (flag){ - this.moveCursorBy(p_146175_1_); - } + public void deleteFromCursor(int p_146175_1_) { + if (this.getText() + .length() != 0) { + boolean flag = p_146175_1_ < 0; + int j = flag ? this.cursorPosition + p_146175_1_ : this.cursorPosition; + int k = flag ? this.cursorPosition : this.cursorPosition + p_146175_1_; + String s = ""; + + if (j >= 0) { + s = this.getText() + .substring(0, j); + } + + if (k < this.getText() + .length()) { + s = s + this.getText() + .substring(k); + } + + this.setText(s); + + if (flag) { + this.moveCursorBy(p_146175_1_); + } } } - public void deleteWords(int p_146177_1_){ - if (this.getText().length() != 0){ + public void deleteWords(int p_146177_1_) { + if (this.getText() + .length() != 0) { this.deleteFromCursor(this.getNthWordFromCursor(p_146177_1_) - this.cursorPosition); } } - public int getNthWordFromCursor(int p_146187_1_){ + public int getNthWordFromCursor(int p_146187_1_) { return this.getNthWordFromPos(p_146187_1_, this.cursorPosition); } - public int getNthWordFromPos(int p_146183_1_, int p_146183_2_){ + public int getNthWordFromPos(int p_146183_1_, int p_146183_2_) { return this.func_146197_a(p_146183_1_, this.cursorPosition, true); } - public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_){ + public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_) { int k = p_146197_2_; boolean flag1 = p_146197_1_ < 0; int l = Math.abs(p_146197_1_); - for (int i1 = 0; i1 < l; ++i1) - { - if (flag1) - { - while (p_146197_3_ && k > 0 && this.getText().charAt(k - 1) == 32) - { + for (int i1 = 0; i1 < l; ++i1) { + if (flag1) { + while (p_146197_3_ && k > 0 + && this.getText() + .charAt(k - 1) == 32) { --k; } - while (k > 0 && this.getText().charAt(k - 1) != 32) - { + while (k > 0 && this.getText() + .charAt(k - 1) != 32) { --k; } - } - else - { - int j1 = this.getText().length(); - k = this.getText().indexOf(32, k); + } else { + int j1 = this.getText() + .length(); + k = this.getText() + .indexOf(32, k); - if (k == -1) - { + if (k == -1) { k = j1; - } - else - { - while (p_146197_3_ && k < j1 && this.getText().charAt(k) == 32) - { + } else { + while (p_146197_3_ && k < j1 + && this.getText() + .charAt(k) == 32) { ++k; } } @@ -317,48 +323,46 @@ public int func_146197_a(int p_146197_1_, int p_146197_2_, boolean p_146197_3_){ } return k; - } - - public void mouseClicked(int x, int y, int p_146192_3_){ - isFocused = (x >= this.x && - x < this.x + this.width && - y >= this.y && - y < this.y + this.height); - - double scale = this.width/pWidth; - try{ - if(x >= (this.x+width+5) && - x < (this.x+width+5+fontRenderer.getStringWidth(possible.get(possibleIndex))) && - y >= (this.y+(scale*pHeight-fontRenderer.FONT_HEIGHT)/2.0) && - y < (this.y+(scale*pHeight-fontRenderer.FONT_HEIGHT)/2.0)+fontRenderer.FONT_HEIGHT){ - this.setText(possible.get(possibleIndex)); - PARENT.onTextChange(this); - isFocused = true; - } - }catch(Exception e){} - - if (this.isFocused && p_146192_3_ == 0){ + } + + public void mouseClicked(int x, int y, int p_146192_3_) { + isFocused = (x >= this.x && x < this.x + this.width && y >= this.y && y < this.y + this.height); + + double scale = this.width / pWidth; + try { + if (x >= (this.x + width + 5) + && x < (this.x + width + 5 + fontRenderer.getStringWidth(possible.get(possibleIndex))) + && y >= (this.y + (scale * pHeight - fontRenderer.FONT_HEIGHT) / 2.0) + && y < (this.y + (scale * pHeight - fontRenderer.FONT_HEIGHT) / 2.0) + fontRenderer.FONT_HEIGHT) { + this.setText(possible.get(possibleIndex)); + PARENT.onTextChange(this); + isFocused = true; + } + } catch (Exception e) {} + + if (this.isFocused && p_146192_3_ == 0) { int l = x - drawXat; - this.setCursorPosition(correctTrim((int) (l/scc)).length()); + this.setCursorPosition(correctTrim((int) (l / scc)).length()); } } - - public String correctTrim(int width){ - int l = this.fontRenderer.trimStringToWidth(getText(), width).length(); - if(getText().length() == l){ - return getText(); - } - int l1 = this.fontRenderer.getStringWidth(getText().substring(0, l)); - int l2 = this.fontRenderer.getStringWidth(getText().substring(0, l+1)); - if(width-l1 posts = new ConcurrentHashMap<>(); - private static final Map bigPosts = new ConcurrentHashMap<>(); - //ServerSide - private static final Map awaiting = new ConcurrentHashMap<>(); - - /** - * UUID = the player; - * StringSet = the discovered waystones; - */ - static final Map playerKnownWaystones = new ConcurrentHashMap<>(); - - public static StringSet getPlayerKnownWaystoneNames(UUID player){ - return playerKnownWaystones.computeIfAbsent(player, x -> new StringSet()); - } - - static final Map playerKnownWaystonePositions = new ConcurrentHashMap<>(); - - public static PlayerRestrictions getPlayerKnownWaystonePositions(UUID player){ - return playerKnownWaystonePositions.computeIfAbsent(player, x -> new PlayerRestrictions()); - } - - public static boolean doesPlayerKnowWaystone(EntityPlayerMP player, BaseInfo waystone){ - if(ClientConfigStorage.INSTANCE.isDisableDiscovery()){ - return true; - }else{ - return doesPlayerKnowNativeWaystone(player, waystone) || getPlayerKnownWaystones(player).contains(waystone); - } - } - - public static boolean doesPlayerKnowNativeWaystone(EntityPlayerMP player, BaseInfo waystone){ - UUID playerID = player.getUniqueID(); - if(ClientConfigStorage.INSTANCE.isDisableDiscovery()){ - return true; - }else if(getPlayerKnownWaystonePositions(playerID).discoveredWastones.contains(waystone.blockPosition)){ - getPlayerKnownWaystoneNames(playerID).remove(waystone.getName()); - return true; - }else{ - StringSet known = getPlayerKnownWaystoneNames(playerID); - if(!known.contains(waystone.getName())) return false; - known.remove(waystone.getName()); - getPlayerKnownWaystonePositions(playerID).discoveredWastones.add(waystone.blockPosition); - return true; - } - } - - public static void init(){allWaystones.clear(); - playerKnownWaystones.clear(); - playerKnownWaystonePositions.clear(); - posts.clear(); - bigPosts.clear(); - awaiting.clear(); - } - - public static Map getPosts() { - return posts; - } - - public static void setPosts(Map posts) { - PostHandler.posts.clear(); - PostHandler.posts.putAll(posts); - refreshDoublePosts(); - } - - public static Map getBigPosts() { - return bigPosts; - } - - public static void setBigPosts(Map bigPosts) { - PostHandler.bigPosts.clear(); - PostHandler.bigPosts.putAll(bigPosts); - refreshBigPosts(); - } - - public static List getSigns(MyBlockPos pos){ - List ret = new LinkedList(); - - DoubleBaseInfo doubleBase = getPosts().get(pos); - if(doubleBase != null){ - ret.add(doubleBase.sign1); - ret.add(doubleBase.sign2); - }else{ - BigBaseInfo bigBase = getBigPosts().get(pos); - if(bigBase != null){ - ret.add(bigBase.sign); - } - } - - return ret; - } - - public static Paintable getPost(MyBlockPos pos){ - Paintable ret = getPosts().get(pos); - if(ret == null){ - ret = getBigPosts().get(pos); - } - if(ret == null){ - pos.getTile(); - ret = getPosts().get(pos); - if(ret == null){ - ret = getBigPosts().get(pos); - } - } - return ret; - } - - public static void refreshDoublePosts(){ - for(Entry now: posts.entrySet()){ - PostPostTile tile = (PostPostTile) now.getKey().getTile(); - if(tile!=null){ - tile.isWaystone(); - tile.getBases(); - } - } - } - - public static void refreshBigPosts(){ - for(Entry now: bigPosts.entrySet()){ - BigPostPostTile tile = (BigPostPostTile) now.getKey().getTile(); - if(tile!=null){ - tile.isWaystone(); - tile.getBases(); - } - } - } - - public static BaseInfo getWSbyName(String name){ - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()){ - return new BaseInfo(name, null, null); - }else{ - for(BaseInfo now:getAllWaystones()){ - if(name.equals(now.getName())){ - return now; - } - } - return null; - } - } - - public static BaseInfo getForceWSbyName(String name){ - if(name==null || name.equals("null")){ - return null; - } - for(BaseInfo now:getAllWaystones()){ - if(name.equals(now.getName())){ - return now; - } - } - return new BaseInfo(name, null, null); - } - - public static class TeleportInformation{ - public final BaseInfo destination; - public final int stackSize; - public final WorldServer world; - public final BoolRun boolRun; - public TeleportInformation(BaseInfo destination, int stackSize, WorldServer world, BoolRun boolRun) { - this.destination = destination; - this.stackSize = stackSize; - this.world = world; - this.boolRun = boolRun; - } - } - - /** - * @return whether the player could pay - */ - public static boolean pay(EntityPlayer player, MyBlockPos origin, MyBlockPos destination){ - if(canPay(player, origin, destination)){ - doPay(player, origin, destination); - return true; - }else{ - return false; - } - } - - public static boolean canPay(EntityPlayer player, MyBlockPos origin, MyBlockPos destination){ - if(ClientConfigStorage.INSTANCE.getCost() == null || ConfigHandler.isCreative(player)){ - return true; - }else{ - int playerItemCount = 0; - for(ItemStack now: player.inventory.mainInventory){ - if(now != null && now.getItem() !=null && now.getItem().getClass() == ClientConfigStorage.INSTANCE.getCost().getClass()){ - playerItemCount += now.stackSize; - } - } - return playerItemCount >= getStackSize(origin, destination); - } - } - - public static void doPay(EntityPlayer player, MyBlockPos origin, MyBlockPos destination){ - if(ClientConfigStorage.INSTANCE.getCost() == null || ConfigHandler.isCreative(player)){ - return; - }else{ - int stackSize = getStackSize(origin, destination); - while(stackSize-- > 0){ - player.inventory.consumeInventoryItem(ClientConfigStorage.INSTANCE.getCost()); - } - } - } - - public static int getStackSize(MyBlockPos origin, MyBlockPos destination){ - return getStackSize((float) origin.distance(destination)); - } - - public static int getStackSize(float distance){ - if(ClientConfigStorage.INSTANCE.getCostMult()==0){ - return ClientConfigStorage.INSTANCE.getCostBase(); - }else{ - return (int) (distance / ClientConfigStorage.INSTANCE.getCostMult() + ClientConfigStorage.INSTANCE.getCostBase()); - } - } - - public static void confirm(final EntityPlayerMP player){ - final TeleportInformation info = awaiting.get(player.getUniqueID()); - SPEventHandler.scheduleTask(() -> { - if(info==null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.noConfirm"), player); - return; - }else{ - doPay(player, new MyBlockPos(player), info.destination.teleportPosition); - SPEventHandler.cancelTask(info.boolRun); - ServerConfigurationManager manager = player.mcServer.getConfigurationManager(); - if(!(player.dimension==info.destination.teleportPosition.dim)){ - manager.transferPlayerToDimension(player, info.destination.teleportPosition.dim, new SignTeleporter(info.world)); - } - player.setPositionAndUpdate(info.destination.teleportPosition.x+0.5, info.destination.teleportPosition.y+1, info.destination.teleportPosition.z+0.5); - } - }, 1); - } - - public static void teleportMe(BaseInfo destination, final EntityPlayerMP player, int stackSize){ - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()){ - return; - } - if(canTeleport(player, destination)){ - WorldServer world = (WorldServer) destination.teleportPosition.getWorld(); - if(world == null){ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.errorWorld", "", ""+destination.teleportPosition.dim), player); - }else{ - UUID uuid = player.getUniqueID(); - TeleportInformation teleportInformation = new TeleportInformation(destination, stackSize, world, new BoolRun(){ - private short ticksLeft = 2400; - @Override - public boolean run() { - if(ticksLeft--<=0){ - awaiting.remove(player.getUniqueID()); - return true; - } - return false; - } - }); - awaiting.put(uuid, teleportInformation); - SPEventHandler.scheduleTask(teleportInformation.boolRun); - NetworkHandler.netWrap.sendTo(new TeleportRequestMessage(stackSize, destination.getName()), player); - } - } - } - - public static boolean addAllDiscoveredByName(UUID player, StringSet ws){ - MyBlockPosSet set = new MyBlockPosSet(); - StringSet newStrs = new StringSet(); - newStrs.addAll(ws); - for(String now: ws){ - for(BaseInfo base: getAllWaystones()){ - if(base.getName().equals(now)){ - set.add(base.blockPosition); - newStrs.remove(now); - } - } - } - ws = newStrs; - boolean ret = false; - if(!ws.isEmpty()) { - ret = getPlayerKnownWaystoneNames(player).addAll(ws); - } - return ret | getPlayerKnownWaystonePositions(player).discoveredWastones.addAll(set); - } - - public static boolean addAllDiscoveredByPos(UUID player, MyBlockPosSet ws){ - return getPlayerKnownWaystonePositions(player).discoveredWastones.addAll(ws); - } - - public static boolean addDiscovered(UUID player, BaseInfo ws){ - if(ws==null){ - return false; - } - boolean ret = getPlayerKnownWaystonePositions(player).discoveredWastones.add(ws.blockPosition); - ret = ret |! getPlayerKnownWaystoneNames(player).remove(ws.getName()); - return ret; - } - - public static void refreshDiscovered(){ - HashSet toDelete = new HashSet(); - HashMap toAdd = new HashMap(); - for(Entry now: playerKnownWaystones.entrySet()){ - StringSet newSet = new StringSet(); - MyBlockPosSet newPosSet = new MyBlockPosSet(); - for(String str: now.getValue()){ - for(BaseInfo base: allWaystones){ - if(base.hasName() && base.getName().equals(str)){ - newPosSet.add(base.blockPosition); - newSet.add(str); - } - } - } - toAdd.put(now.getKey(), newPosSet); - now.getValue().removeAll(newSet); - if(now.getValue().isEmpty()){ - toDelete.add(now.getKey()); - } - } - - for(UUID now: toDelete){ - playerKnownWaystones.remove(now); - } - - for(Entry now: toAdd.entrySet()){ - addAllDiscoveredByPos(now.getKey(), now.getValue()); - } - } - - public static boolean canTeleport(EntityPlayerMP player, BaseInfo target){ - if(doesPlayerKnowWaystone(player, target)){ - if(new MyBlockPos(player).checkInterdimensional(target.blockPosition)){ - return true; - }else{ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.guiWorldDim"), player); - } - }else{ - NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.notDiscovered", "", target.getName()), player); - } - return false; - } - - public static EntityPlayer getPlayerByName(String name){ - for(Object player : MinecraftServer.getServer().getConfigurationManager().playerEntityList){ - if(player instanceof EntityPlayer && ((EntityPlayer)player).getCommandSenderName().equals(name)){ - return (EntityPlayer) player; - } - } - return null; - } - - private static class SignTeleporter extends Teleporter{ - - public SignTeleporter(WorldServer worldIn) {super(worldIn);} - - @Override - public void placeInPortal(Entity entityIn, double p_77185_2_, double p_77185_4_, double p_77185_6_, float p_77185_8_){} - - @Override - public boolean placeInExistingPortal(Entity entityIn, double p_77185_2_, double p_77185_4_, double p_77185_6_, float p_77185_8_){return true;} - - @Override - public boolean makePortal(Entity entityIn){return true;} - - @Override - public void removeStalePortalLocations(long worldTime){} - } - - public static StonedHashSet getAllWaystones() { - StonedHashSet ret = SignpostAdapter.INSTANCE.getExternalBaseInfos(); - ret.addAll(allWaystones); - return ret; - } - - public static Collection getAllWaystoneNames(){ - Collection ret = getAllWaystones().select(BaseInfo::getName); - if(FMLCommonHandler.instance().getEffectiveSide().equals(Side.CLIENT)) { - ret.addAll(SendAllWaystoneNamesHandler.cachedWaystoneNames); - } - return ret; - } - - public static StonedHashSet getNativeWaystones(){ - return allWaystones; - } - - public static void setNativeWaystones(StonedHashSet set){ - allWaystones.clear(); - allWaystones.addAll(set); - } - - public static StonedHashSet getPlayerKnownWaystones(EntityPlayerMP player){ - StonedHashSet ret = SignpostAdapter.INSTANCE.getExternalPlayerBaseInfos(player); - for(BaseInfo now: allWaystones){ - if(doesPlayerKnowNativeWaystone(player, now)){ - ret.add(now); - } - } - return ret; - } - - public static boolean addWaystone(BaseInfo baseInfo){ - return allWaystones.add(baseInfo); - } + private static final StonedHashSet allWaystones = new StonedHashSet(); + private static final Map posts = new ConcurrentHashMap<>(); + private static final Map bigPosts = new ConcurrentHashMap<>(); + // ServerSide + private static final Map awaiting = new ConcurrentHashMap<>(); + + /** + * UUID = the player; + * StringSet = the discovered waystones; + */ + static final Map playerKnownWaystones = new ConcurrentHashMap<>(); + + public static StringSet getPlayerKnownWaystoneNames(UUID player) { + return playerKnownWaystones.computeIfAbsent(player, x -> new StringSet()); + } + + static final Map playerKnownWaystonePositions = new ConcurrentHashMap<>(); + + public static PlayerRestrictions getPlayerKnownWaystonePositions(UUID player) { + return playerKnownWaystonePositions.computeIfAbsent(player, x -> new PlayerRestrictions()); + } + + public static boolean doesPlayerKnowWaystone(EntityPlayerMP player, BaseInfo waystone) { + if (ClientConfigStorage.INSTANCE.isDisableDiscovery()) { + return true; + } else { + return doesPlayerKnowNativeWaystone(player, waystone) || getPlayerKnownWaystones(player).contains(waystone); + } + } + + public static boolean doesPlayerKnowNativeWaystone(EntityPlayerMP player, BaseInfo waystone) { + UUID playerID = player.getUniqueID(); + if (ClientConfigStorage.INSTANCE.isDisableDiscovery()) { + return true; + } else if (getPlayerKnownWaystonePositions(playerID).discoveredWastones.contains(waystone.blockPosition)) { + getPlayerKnownWaystoneNames(playerID).remove(waystone.getName()); + return true; + } else { + StringSet known = getPlayerKnownWaystoneNames(playerID); + if (!known.contains(waystone.getName())) return false; + known.remove(waystone.getName()); + getPlayerKnownWaystonePositions(playerID).discoveredWastones.add(waystone.blockPosition); + return true; + } + } + + public static void init() { + allWaystones.clear(); + playerKnownWaystones.clear(); + playerKnownWaystonePositions.clear(); + posts.clear(); + bigPosts.clear(); + awaiting.clear(); + } + + public static Map getPosts() { + return posts; + } + + public static void setPosts(Map posts) { + PostHandler.posts.clear(); + PostHandler.posts.putAll(posts); + refreshDoublePosts(); + } + + public static Map getBigPosts() { + return bigPosts; + } + + public static void setBigPosts(Map bigPosts) { + PostHandler.bigPosts.clear(); + PostHandler.bigPosts.putAll(bigPosts); + refreshBigPosts(); + } + + public static List getSigns(MyBlockPos pos) { + List ret = new LinkedList(); + + DoubleBaseInfo doubleBase = getPosts().get(pos); + if (doubleBase != null) { + ret.add(doubleBase.sign1); + ret.add(doubleBase.sign2); + } else { + BigBaseInfo bigBase = getBigPosts().get(pos); + if (bigBase != null) { + ret.add(bigBase.sign); + } + } + + return ret; + } + + public static Paintable getPost(MyBlockPos pos) { + Paintable ret = getPosts().get(pos); + if (ret == null) { + ret = getBigPosts().get(pos); + } + if (ret == null) { + pos.getTile(); + ret = getPosts().get(pos); + if (ret == null) { + ret = getBigPosts().get(pos); + } + } + return ret; + } + + public static void refreshDoublePosts() { + for (Entry now : posts.entrySet()) { + PostPostTile tile = (PostPostTile) now.getKey() + .getTile(); + if (tile != null) { + tile.isWaystone(); + tile.getBases(); + } + } + } + + public static void refreshBigPosts() { + for (Entry now : bigPosts.entrySet()) { + BigPostPostTile tile = (BigPostPostTile) now.getKey() + .getTile(); + if (tile != null) { + tile.isWaystone(); + tile.getBases(); + } + } + } + + public static BaseInfo getWSbyName(String name) { + if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + return new BaseInfo(name, null, null); + } else { + for (BaseInfo now : getAllWaystones()) { + if (name.equals(now.getName())) { + return now; + } + } + return null; + } + } + + public static BaseInfo getForceWSbyName(String name) { + if (name == null || name.equals("null")) { + return null; + } + for (BaseInfo now : getAllWaystones()) { + if (name.equals(now.getName())) { + return now; + } + } + return new BaseInfo(name, null, null); + } + + public static class TeleportInformation { + + public final BaseInfo destination; + public final int stackSize; + public final WorldServer world; + public final BoolRun boolRun; + + public TeleportInformation(BaseInfo destination, int stackSize, WorldServer world, BoolRun boolRun) { + this.destination = destination; + this.stackSize = stackSize; + this.world = world; + this.boolRun = boolRun; + } + } + + /** + * @return whether the player could pay + */ + public static boolean pay(EntityPlayer player, MyBlockPos origin, MyBlockPos destination) { + if (canPay(player, origin, destination)) { + doPay(player, origin, destination); + return true; + } else { + return false; + } + } + + public static boolean canPay(EntityPlayer player, MyBlockPos origin, MyBlockPos destination) { + if (ClientConfigStorage.INSTANCE.getCost() == null || ConfigHandler.isCreative(player)) { + return true; + } else { + int playerItemCount = 0; + for (ItemStack now : player.inventory.mainInventory) { + if (now != null && now.getItem() != null + && now.getItem() + .getClass() + == ClientConfigStorage.INSTANCE.getCost() + .getClass()) { + playerItemCount += now.stackSize; + } + } + return playerItemCount >= getStackSize(origin, destination); + } + } + + public static void doPay(EntityPlayer player, MyBlockPos origin, MyBlockPos destination) { + if (ClientConfigStorage.INSTANCE.getCost() == null || ConfigHandler.isCreative(player)) { + return; + } else { + int stackSize = getStackSize(origin, destination); + while (stackSize-- > 0) { + player.inventory.consumeInventoryItem(ClientConfigStorage.INSTANCE.getCost()); + } + } + } + + public static int getStackSize(MyBlockPos origin, MyBlockPos destination) { + return getStackSize((float) origin.distance(destination)); + } + + public static int getStackSize(float distance) { + if (ClientConfigStorage.INSTANCE.getCostMult() == 0) { + return ClientConfigStorage.INSTANCE.getCostBase(); + } else { + return (int) (distance / ClientConfigStorage.INSTANCE.getCostMult() + + ClientConfigStorage.INSTANCE.getCostBase()); + } + } + + public static void confirm(final EntityPlayerMP player) { + final TeleportInformation info = awaiting.get(player.getUniqueID()); + SPEventHandler.scheduleTask(() -> { + if (info == null) { + NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.noConfirm"), player); + return; + } else { + doPay(player, new MyBlockPos(player), info.destination.teleportPosition); + SPEventHandler.cancelTask(info.boolRun); + ServerConfigurationManager manager = player.mcServer.getConfigurationManager(); + if (!(player.dimension == info.destination.teleportPosition.dim)) { + manager.transferPlayerToDimension( + player, + info.destination.teleportPosition.dim, + new SignTeleporter(info.world)); + } + player.setPositionAndUpdate( + info.destination.teleportPosition.x + 0.5, + info.destination.teleportPosition.y + 1, + info.destination.teleportPosition.z + 0.5); + } + }, 1); + } + + public static void teleportMe(BaseInfo destination, final EntityPlayerMP player, int stackSize) { + if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + return; + } + if (canTeleport(player, destination)) { + WorldServer world = (WorldServer) destination.teleportPosition.getWorld(); + if (world == null) { + NetworkHandler.netWrap.sendTo( + new ChatMessage("signpost.errorWorld", "", "" + destination.teleportPosition.dim), + player); + } else { + UUID uuid = player.getUniqueID(); + TeleportInformation teleportInformation = new TeleportInformation( + destination, + stackSize, + world, + new BoolRun() { + + private short ticksLeft = 2400; + + @Override + public boolean run() { + if (ticksLeft-- <= 0) { + awaiting.remove(player.getUniqueID()); + return true; + } + return false; + } + }); + awaiting.put(uuid, teleportInformation); + SPEventHandler.scheduleTask(teleportInformation.boolRun); + NetworkHandler.netWrap.sendTo(new TeleportRequestMessage(stackSize, destination.getName()), player); + } + } + } + + public static boolean addAllDiscoveredByName(UUID player, StringSet ws) { + MyBlockPosSet set = new MyBlockPosSet(); + StringSet newStrs = new StringSet(); + newStrs.addAll(ws); + for (String now : ws) { + for (BaseInfo base : getAllWaystones()) { + if (base.getName() + .equals(now)) { + set.add(base.blockPosition); + newStrs.remove(now); + } + } + } + ws = newStrs; + boolean ret = false; + if (!ws.isEmpty()) { + ret = getPlayerKnownWaystoneNames(player).addAll(ws); + } + return ret | getPlayerKnownWaystonePositions(player).discoveredWastones.addAll(set); + } + + public static boolean addAllDiscoveredByPos(UUID player, MyBlockPosSet ws) { + return getPlayerKnownWaystonePositions(player).discoveredWastones.addAll(ws); + } + + public static boolean addDiscovered(UUID player, BaseInfo ws) { + if (ws == null) { + return false; + } + boolean ret = getPlayerKnownWaystonePositions(player).discoveredWastones.add(ws.blockPosition); + ret = ret | !getPlayerKnownWaystoneNames(player).remove(ws.getName()); + return ret; + } + + public static void refreshDiscovered() { + HashSet toDelete = new HashSet(); + HashMap toAdd = new HashMap(); + for (Entry now : playerKnownWaystones.entrySet()) { + StringSet newSet = new StringSet(); + MyBlockPosSet newPosSet = new MyBlockPosSet(); + for (String str : now.getValue()) { + for (BaseInfo base : allWaystones) { + if (base.hasName() && base.getName() + .equals(str)) { + newPosSet.add(base.blockPosition); + newSet.add(str); + } + } + } + toAdd.put(now.getKey(), newPosSet); + now.getValue() + .removeAll(newSet); + if (now.getValue() + .isEmpty()) { + toDelete.add(now.getKey()); + } + } + + for (UUID now : toDelete) { + playerKnownWaystones.remove(now); + } + + for (Entry now : toAdd.entrySet()) { + addAllDiscoveredByPos(now.getKey(), now.getValue()); + } + } + + public static boolean canTeleport(EntityPlayerMP player, BaseInfo target) { + if (doesPlayerKnowWaystone(player, target)) { + if (new MyBlockPos(player).checkInterdimensional(target.blockPosition)) { + return true; + } else { + NetworkHandler.netWrap.sendTo(new ChatMessage("signpost.guiWorldDim"), player); + } + } else { + NetworkHandler.netWrap + .sendTo(new ChatMessage("signpost.notDiscovered", "", target.getName()), player); + } + return false; + } + + public static EntityPlayer getPlayerByName(String name) { + for (Object player : MinecraftServer.getServer() + .getConfigurationManager().playerEntityList) { + if (player instanceof EntityPlayer && ((EntityPlayer) player).getCommandSenderName() + .equals(name)) { + return (EntityPlayer) player; + } + } + return null; + } + + private static class SignTeleporter extends Teleporter { + + public SignTeleporter(WorldServer worldIn) { + super(worldIn); + } + + @Override + public void placeInPortal(Entity entityIn, double p_77185_2_, double p_77185_4_, double p_77185_6_, + float p_77185_8_) {} + + @Override + public boolean placeInExistingPortal(Entity entityIn, double p_77185_2_, double p_77185_4_, double p_77185_6_, + float p_77185_8_) { + return true; + } + + @Override + public boolean makePortal(Entity entityIn) { + return true; + } + + @Override + public void removeStalePortalLocations(long worldTime) {} + } + + public static StonedHashSet getAllWaystones() { + StonedHashSet ret = SignpostAdapter.INSTANCE.getExternalBaseInfos(); + ret.addAll(allWaystones); + return ret; + } + + public static Collection getAllWaystoneNames() { + Collection ret = getAllWaystones().select(BaseInfo::getName); + if (FMLCommonHandler.instance() + .getEffectiveSide() + .equals(Side.CLIENT)) { + ret.addAll(SendAllWaystoneNamesHandler.cachedWaystoneNames); + } + return ret; + } + + public static StonedHashSet getNativeWaystones() { + return allWaystones; + } + + public static void setNativeWaystones(StonedHashSet set) { + allWaystones.clear(); + allWaystones.addAll(set); + } + + public static StonedHashSet getPlayerKnownWaystones(EntityPlayerMP player) { + StonedHashSet ret = SignpostAdapter.INSTANCE.getExternalPlayerBaseInfos(player); + for (BaseInfo now : allWaystones) { + if (doesPlayerKnowNativeWaystone(player, now)) { + ret.add(now); + } + } + return ret; + } + + public static boolean addWaystone(BaseInfo baseInfo) { + return allWaystones.add(baseInfo); + } } diff --git a/src/main/java/gollorum/signpost/management/WorldSigns.java b/src/main/java/gollorum/signpost/management/WorldSigns.java index c93c185a..6c6236a7 100644 --- a/src/main/java/gollorum/signpost/management/WorldSigns.java +++ b/src/main/java/gollorum/signpost/management/WorldSigns.java @@ -1,78 +1,81 @@ package gollorum.signpost.management; -import gollorum.signpost.Signpost; -import gollorum.signpost.util.BaseInfo; -import gollorum.signpost.util.StonedHashSet; -import gollorum.signpost.worldGen.villages.VillageLibrary; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; import net.minecraft.world.storage.MapStorage; -public class WorldSigns extends WorldSavedData{ +import gollorum.signpost.util.BaseInfo; +import gollorum.signpost.util.StonedHashSet; +import gollorum.signpost.worldGen.villages.VillageLibrary; + +public class WorldSigns extends WorldSavedData { + + final static String key = "Signpost.WorldSigns"; + private World world; + + public WorldSigns(String tagName) { + super(tagName); + } - final static String key = "Signpost.WorldSigns"; - private World world; - - public WorldSigns(String tagName) { - super(tagName); - } - - public WorldSigns() { - super(key); - } + public WorldSigns() { + super(key); + } - public static WorldSigns worldSigns(World world){ - MapStorage storage = world.perWorldStorage; - WorldSigns ret = (WorldSigns) storage.loadData(WorldSigns.class, key); - if(ret == null){ - ret = new WorldSigns(); - storage.setData(key, ret); - } - ret.world = world; - ret.markDirty(); - return ret; - } + public static WorldSigns worldSigns(World world) { + MapStorage storage = world.perWorldStorage; + WorldSigns ret = (WorldSigns) storage.loadData(WorldSigns.class, key); + if (ret == null) { + ret = new WorldSigns(); + storage.setData(key, ret); + } + ret.world = world; + ret.markDirty(); + return ret; + } - @Override - public void readFromNBT(NBTTagCompound tC) { - NBTTagCompound info = (NBTTagCompound) tC.getTag("SignInfo"); - if(info!=null){ - int infoSize = info.getInteger("infoSize"); - StonedHashSet bases = new StonedHashSet(); - for(int i = 0; i getAllBaseInfos(); - Set getAllBaseInfosByPlayer(EntityPlayer player); - + /** + * use BaseInfo.fromExternal() + */ + Set getAllBaseInfos(); + + Set getAllBaseInfosByPlayer(EntityPlayer player); + } diff --git a/src/main/java/gollorum/signpost/modIntegration/SignpostAdapter.java b/src/main/java/gollorum/signpost/modIntegration/SignpostAdapter.java index bc6bf804..880e3c0c 100644 --- a/src/main/java/gollorum/signpost/modIntegration/SignpostAdapter.java +++ b/src/main/java/gollorum/signpost/modIntegration/SignpostAdapter.java @@ -1,49 +1,50 @@ package gollorum.signpost.modIntegration; -import cpw.mods.fml.common.Loader; -import gollorum.signpost.util.StonedHashSet; -import net.minecraft.entity.player.EntityPlayer; - import java.util.HashSet; import java.util.Set; +import net.minecraft.entity.player.EntityPlayer; + +import cpw.mods.fml.common.Loader; +import gollorum.signpost.util.StonedHashSet; + public class SignpostAdapter { - - public static final SignpostAdapter INSTANCE = new SignpostAdapter(); - - public static final String WAYSTONES_MOD_ID = "waystones"; - - private final Set handlers; - - private SignpostAdapter(){ - handlers = new HashSet<>(); - - if(Loader.isModLoaded(WAYSTONES_MOD_ID)){ - registerModHandler(new WaystonesModHandler()); - } - } - - public boolean registerModHandler(ModHandler handler){ - return handlers.add(handler); - } - - public boolean removeModHandler(ModHandler handler){ - return handlers.remove(handler); - } - - public StonedHashSet getExternalBaseInfos(){ - StonedHashSet ret = new StonedHashSet(); - for(ModHandler now: handlers){ - ret.addAll(now.getAllBaseInfos()); - } - return ret; - } - - public StonedHashSet getExternalPlayerBaseInfos(EntityPlayer player){ - StonedHashSet ret = new StonedHashSet(); - for(ModHandler now: handlers){ - ret.addAll(now.getAllBaseInfosByPlayer(player)); - } - return ret; - } + + public static final SignpostAdapter INSTANCE = new SignpostAdapter(); + + public static final String WAYSTONES_MOD_ID = "waystones"; + + private final Set handlers; + + private SignpostAdapter() { + handlers = new HashSet<>(); + + if (Loader.isModLoaded(WAYSTONES_MOD_ID)) { + registerModHandler(new WaystonesModHandler()); + } + } + + public boolean registerModHandler(ModHandler handler) { + return handlers.add(handler); + } + + public boolean removeModHandler(ModHandler handler) { + return handlers.remove(handler); + } + + public StonedHashSet getExternalBaseInfos() { + StonedHashSet ret = new StonedHashSet(); + for (ModHandler now : handlers) { + ret.addAll(now.getAllBaseInfos()); + } + return ret; + } + + public StonedHashSet getExternalPlayerBaseInfos(EntityPlayer player) { + StonedHashSet ret = new StonedHashSet(); + for (ModHandler now : handlers) { + ret.addAll(now.getAllBaseInfosByPlayer(player)); + } + return ret; + } } diff --git a/src/main/java/gollorum/signpost/modIntegration/WaystonesModHandler.java b/src/main/java/gollorum/signpost/modIntegration/WaystonesModHandler.java index 0b48de35..c1365d5a 100644 --- a/src/main/java/gollorum/signpost/modIntegration/WaystonesModHandler.java +++ b/src/main/java/gollorum/signpost/modIntegration/WaystonesModHandler.java @@ -1,11 +1,9 @@ package gollorum.signpost.modIntegration; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.relauncher.Side; -import gollorum.signpost.Signpost; -import gollorum.signpost.util.BaseInfo; -import gollorum.signpost.util.StonedHashSet; +import java.io.File; +import java.io.FileInputStream; +import java.util.Set; + import net.blay09.mods.waystones.PlayerWaystoneData; import net.blay09.mods.waystones.WaystoneManager; import net.blay09.mods.waystones.Waystones; @@ -22,135 +20,165 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.BlockEvent.BreakEvent; -import java.io.File; -import java.io.FileInputStream; -import java.util.Set; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.relauncher.Side; +import gollorum.signpost.Signpost; +import gollorum.signpost.util.BaseInfo; +import gollorum.signpost.util.StonedHashSet; public class WaystonesModHandler implements ModHandler { - public WaystonesModHandler() { - MinecraftForge.EVENT_BUS.register(this); - } - - @SubscribeEvent - public void onBlockBreak(BreakEvent event) { - if (event.block instanceof BlockWaystone) { - TileWaystone tile = ((BlockWaystone) event.block).getTileWaystone(event.world, event.x, event.y, event.z); - WaystoneEntry entry = new WaystoneEntry(tile); - WaystoneManager.removeServerWaystone(entry); - for (EntityPlayer player : Signpost.proxy.getAllPlayers()) { - WaystoneManager.sendPlayerWaystones(player); - } - } - } - - @Override - public Set getAllBaseInfos() { - Set ret = getGlobal(); - ret.addAll(getNotGlobalByAllPlayers()); - return ret; - } - - @Override - public Set getAllBaseInfosByPlayer(EntityPlayer player) { - Set ret = getGlobal(); - ret.addAll(getNotGlobalByPlayer(player)); - return ret; - } - - private Set getGlobal(){ - StonedHashSet ret = new StonedHashSet(); - for(WaystoneEntry entry: WaystoneManager.getServerWaystones()){ - if (validateWaystone(entry)) { - ret.add(baseInfoFromWaystoneEntry(entry)); - } - } - return ret; - } - - private Set getNotGlobalByPlayer(EntityPlayer player){ - StonedHashSet ret = new StonedHashSet(); - try{ - NBTTagCompound tagCompound = PlayerWaystoneData.getWaystonesTag(player); - ret.addAll(getNotGlobalByTagCompound(tagCompound)); - }catch(Exception e){} - return ret; - } - - private Set getNotGlobalByAllPlayers(){ - Set ret = new StonedHashSet(); - for(EntityPlayer player: Signpost.proxy.getAllPlayers()){ - ret.addAll(getNotGlobalByPlayer(player)); - } - if(FMLCommonHandler.instance().getEffectiveSide().equals(Side.CLIENT)){ - return ret; - }else{ - File playerDirectory = new File(DimensionManager.getWorld(0).getSaveHandler().getWorldDirectory(), "playerdata"); - if(playerDirectory.isDirectory()){ - for(File file: playerDirectory.listFiles()){ - try{ - FileInputStream stream = new FileInputStream(file); - NBTTagCompound tagCompound = CompressedStreamTools.readCompressed(stream); - tagCompound = tagCompound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted").getCompoundTag("Waystones"); - stream.close(); - Set bases = getNotGlobalByTagCompound(tagCompound); - ret.addAll(bases); - }catch(Exception e){} - } - } - return ret; - } - } - - private Set getNotGlobalByTagCompound(NBTTagCompound tagCompound){ - Set ret = new StonedHashSet(); - NBTTagList tagList = tagCompound.getTagList("WaystoneList", 10); - for (int i = 0; i < tagList.tagCount(); ++i) { - NBTTagCompound entryCompound = tagList.getCompoundTagAt(i); - WaystoneEntry entry = WaystoneEntry.read(entryCompound); - if (validateWaystone(entry)) { - BaseInfo wrappedWaystone = baseInfoFromWaystoneEntry(entry); - ret.add(wrappedWaystone); - } - } - return ret; - } - - private boolean validateWaystone(WaystoneEntry entry) { - try { - if (FMLCommonHandler.instance().getEffectiveSide().equals(Side.SERVER)) { - World world = FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(entry.getDimensionId()); - Block block = world.getBlock(entry.getPos().getX(), entry.getPos().getY(), entry.getPos().getZ()); - return block instanceof BlockWaystone; - } else { - World world = Signpost.proxy.getWorlds()[0]; - if (world.provider.dimensionId == entry.getDimensionId()) { - Block block = world.getBlock(entry.getPos().getX(), entry.getPos().getY(), entry.getPos().getZ()); - return block instanceof BlockWaystone; - } else { - return true; - } - } - } catch (Exception e) { - return true; - } - } - - private BaseInfo baseInfoFromWaystoneEntry(WaystoneEntry entry) { - if (entry == null) { - return null; - } - String name = entry.getName(); - - int blockX = entry.getPos().getX(); - int blockY = entry.getPos().getY(); - int blockZ = entry.getPos().getZ(); - - int teleX = blockX+1; - int teleY = blockY; - int teleZ = blockZ; - - int dim = entry.getDimensionId(); - return BaseInfo.fromExternal(name, blockX, blockY, blockZ, teleX, teleY, teleZ, dim, Waystones.MOD_ID); - } -} \ No newline at end of file + public WaystonesModHandler() { + MinecraftForge.EVENT_BUS.register(this); + } + + @SubscribeEvent + public void onBlockBreak(BreakEvent event) { + if (event.block instanceof BlockWaystone) { + TileWaystone tile = ((BlockWaystone) event.block).getTileWaystone(event.world, event.x, event.y, event.z); + WaystoneEntry entry = new WaystoneEntry(tile); + WaystoneManager.removeServerWaystone(entry); + for (EntityPlayer player : Signpost.proxy.getAllPlayers()) { + WaystoneManager.sendPlayerWaystones(player); + } + } + } + + @Override + public Set getAllBaseInfos() { + Set ret = getGlobal(); + ret.addAll(getNotGlobalByAllPlayers()); + return ret; + } + + @Override + public Set getAllBaseInfosByPlayer(EntityPlayer player) { + Set ret = getGlobal(); + ret.addAll(getNotGlobalByPlayer(player)); + return ret; + } + + private Set getGlobal() { + StonedHashSet ret = new StonedHashSet(); + for (WaystoneEntry entry : WaystoneManager.getServerWaystones()) { + if (validateWaystone(entry)) { + ret.add(baseInfoFromWaystoneEntry(entry)); + } + } + return ret; + } + + private Set getNotGlobalByPlayer(EntityPlayer player) { + StonedHashSet ret = new StonedHashSet(); + try { + NBTTagCompound tagCompound = PlayerWaystoneData.getWaystonesTag(player); + ret.addAll(getNotGlobalByTagCompound(tagCompound)); + } catch (Exception e) {} + return ret; + } + + private Set getNotGlobalByAllPlayers() { + Set ret = new StonedHashSet(); + for (EntityPlayer player : Signpost.proxy.getAllPlayers()) { + ret.addAll(getNotGlobalByPlayer(player)); + } + if (FMLCommonHandler.instance() + .getEffectiveSide() + .equals(Side.CLIENT)) { + return ret; + } else { + File playerDirectory = new File( + DimensionManager.getWorld(0) + .getSaveHandler() + .getWorldDirectory(), + "playerdata"); + if (playerDirectory.isDirectory()) { + for (File file : playerDirectory.listFiles()) { + try { + FileInputStream stream = new FileInputStream(file); + NBTTagCompound tagCompound = CompressedStreamTools.readCompressed(stream); + tagCompound = tagCompound.getCompoundTag("ForgeData") + .getCompoundTag("PlayerPersisted") + .getCompoundTag("Waystones"); + stream.close(); + Set bases = getNotGlobalByTagCompound(tagCompound); + ret.addAll(bases); + } catch (Exception e) {} + } + } + return ret; + } + } + + private Set getNotGlobalByTagCompound(NBTTagCompound tagCompound) { + Set ret = new StonedHashSet(); + NBTTagList tagList = tagCompound.getTagList("WaystoneList", 10); + for (int i = 0; i < tagList.tagCount(); ++i) { + NBTTagCompound entryCompound = tagList.getCompoundTagAt(i); + WaystoneEntry entry = WaystoneEntry.read(entryCompound); + if (validateWaystone(entry)) { + BaseInfo wrappedWaystone = baseInfoFromWaystoneEntry(entry); + ret.add(wrappedWaystone); + } + } + return ret; + } + + private boolean validateWaystone(WaystoneEntry entry) { + try { + if (FMLCommonHandler.instance() + .getEffectiveSide() + .equals(Side.SERVER)) { + World world = FMLCommonHandler.instance() + .getMinecraftServerInstance() + .worldServerForDimension(entry.getDimensionId()); + Block block = world.getBlock( + entry.getPos() + .getX(), + entry.getPos() + .getY(), + entry.getPos() + .getZ()); + return block instanceof BlockWaystone; + } else { + World world = Signpost.proxy.getWorlds()[0]; + if (world.provider.dimensionId == entry.getDimensionId()) { + Block block = world.getBlock( + entry.getPos() + .getX(), + entry.getPos() + .getY(), + entry.getPos() + .getZ()); + return block instanceof BlockWaystone; + } else { + return true; + } + } + } catch (Exception e) { + return true; + } + } + + private BaseInfo baseInfoFromWaystoneEntry(WaystoneEntry entry) { + if (entry == null) { + return null; + } + String name = entry.getName(); + + int blockX = entry.getPos() + .getX(); + int blockY = entry.getPos() + .getY(); + int blockZ = entry.getPos() + .getZ(); + + int teleX = blockX + 1; + int teleY = blockY; + int teleZ = blockZ; + + int dim = entry.getDimensionId(); + return BaseInfo.fromExternal(name, blockX, blockY, blockZ, teleX, teleY, teleZ, dim, Waystones.MOD_ID); + } +} diff --git a/src/main/java/gollorum/signpost/network/NetworkHandler.java b/src/main/java/gollorum/signpost/network/NetworkHandler.java index 9a7e28c6..68ea531d 100644 --- a/src/main/java/gollorum/signpost/network/NetworkHandler.java +++ b/src/main/java/gollorum/signpost/network/NetworkHandler.java @@ -3,7 +3,7 @@ import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; -import gollorum.signpost.Signpost; +import gollorum.signpost.Tags; import gollorum.signpost.network.handlers.BaseUpdateClientHandler; import gollorum.signpost.network.handlers.BaseUpdateServerHandler; import gollorum.signpost.network.handlers.ChatHandler; @@ -35,26 +35,27 @@ public class NetworkHandler { - public static final SimpleNetworkWrapper netWrap = NetworkRegistry.INSTANCE.newSimpleChannel(Signpost.MODID); - - public static void register(){ - netWrap.registerMessage(BaseUpdateServerHandler.class, BaseUpdateServerMessage.class, 0, Side.SERVER); - netWrap.registerMessage(BaseUpdateClientHandler.class, BaseUpdateClientMessage.class, 1, Side.CLIENT); - netWrap.registerMessage(SendDiscoveredToServerHandler.class, SendDiscoveredToServerMessage.class, 2, Side.SERVER); - netWrap.registerMessage(InitPlayerResponseHandler.class, InitPlayerResponseMessage.class, 3, Side.CLIENT); - netWrap.registerMessage(SendPostBasesHandler.class, SendPostBasesMessage.class, 4, Side.CLIENT); - netWrap.registerMessage(SendPostBasesHandler.class, SendPostBasesMessage.class, 5, Side.SERVER); - netWrap.registerMessage(SendAllPostBasesHandler.class, SendAllPostBasesMessage.class, 6, Side.CLIENT); - netWrap.registerMessage(SendBigPostBasesHandler.class, SendBigPostBasesMessage.class, 7, Side.CLIENT); - netWrap.registerMessage(SendBigPostBasesHandler.class, SendBigPostBasesMessage.class, 8, Side.SERVER); - netWrap.registerMessage(SendAllBigPostBasesHandler.class, SendAllBigPostBasesMessage.class, 9, Side.CLIENT); - netWrap.registerMessage(TeleportMeHandler.class, TeleportMeMessage.class, 10, Side.SERVER); - netWrap.registerMessage(ChatHandler.class, ChatMessage.class, 11, Side.CLIENT); - netWrap.registerMessage(OpenGuiHandler.class, OpenGuiMessage.class, 12, Side.CLIENT); - netWrap.registerMessage(TeleportRequestHandler.class, TeleportRequestMessage.class, 13, Side.CLIENT); - netWrap.registerMessage(TeleportRequestHandler.class, TeleportRequestMessage.class, 14, Side.SERVER); - netWrap.registerMessage(RequestTextureHandler.class, RequestTextureMessage.class, 15, Side.CLIENT); - netWrap.registerMessage(SendAllWaystoneNamesHandler.class, SendAllWaystoneNamesMessage.class, 16, Side.CLIENT); - } - + public static final SimpleNetworkWrapper netWrap = NetworkRegistry.INSTANCE.newSimpleChannel(Tags.MODID); + + public static void register() { + netWrap.registerMessage(BaseUpdateServerHandler.class, BaseUpdateServerMessage.class, 0, Side.SERVER); + netWrap.registerMessage(BaseUpdateClientHandler.class, BaseUpdateClientMessage.class, 1, Side.CLIENT); + netWrap + .registerMessage(SendDiscoveredToServerHandler.class, SendDiscoveredToServerMessage.class, 2, Side.SERVER); + netWrap.registerMessage(InitPlayerResponseHandler.class, InitPlayerResponseMessage.class, 3, Side.CLIENT); + netWrap.registerMessage(SendPostBasesHandler.class, SendPostBasesMessage.class, 4, Side.CLIENT); + netWrap.registerMessage(SendPostBasesHandler.class, SendPostBasesMessage.class, 5, Side.SERVER); + netWrap.registerMessage(SendAllPostBasesHandler.class, SendAllPostBasesMessage.class, 6, Side.CLIENT); + netWrap.registerMessage(SendBigPostBasesHandler.class, SendBigPostBasesMessage.class, 7, Side.CLIENT); + netWrap.registerMessage(SendBigPostBasesHandler.class, SendBigPostBasesMessage.class, 8, Side.SERVER); + netWrap.registerMessage(SendAllBigPostBasesHandler.class, SendAllBigPostBasesMessage.class, 9, Side.CLIENT); + netWrap.registerMessage(TeleportMeHandler.class, TeleportMeMessage.class, 10, Side.SERVER); + netWrap.registerMessage(ChatHandler.class, ChatMessage.class, 11, Side.CLIENT); + netWrap.registerMessage(OpenGuiHandler.class, OpenGuiMessage.class, 12, Side.CLIENT); + netWrap.registerMessage(TeleportRequestHandler.class, TeleportRequestMessage.class, 13, Side.CLIENT); + netWrap.registerMessage(TeleportRequestHandler.class, TeleportRequestMessage.class, 14, Side.SERVER); + netWrap.registerMessage(RequestTextureHandler.class, RequestTextureMessage.class, 15, Side.CLIENT); + netWrap.registerMessage(SendAllWaystoneNamesHandler.class, SendAllWaystoneNamesMessage.class, 16, Side.CLIENT); + } + } diff --git a/src/main/java/gollorum/signpost/network/handlers/BaseUpdateClientHandler.java b/src/main/java/gollorum/signpost/network/handlers/BaseUpdateClientHandler.java index 5bca786c..aac6b306 100644 --- a/src/main/java/gollorum/signpost/network/handlers/BaseUpdateClientHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/BaseUpdateClientHandler.java @@ -2,6 +2,8 @@ import java.util.Map.Entry; +import net.minecraft.tileentity.TileEntity; + import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; @@ -13,49 +15,62 @@ import gollorum.signpost.util.BigBaseInfo; import gollorum.signpost.util.DoubleBaseInfo; import gollorum.signpost.util.MyBlockPos; -import net.minecraft.tileentity.TileEntity; public class BaseUpdateClientHandler implements IMessageHandler { - @Override - public IMessage onMessage(BaseUpdateClientMessage message, MessageContext ctx) { - for(Entry now: PostHandler.getPosts().entrySet()){ - TileEntity tile = FMLClientHandler.instance().getWorldClient().getTileEntity(now.getKey().x, now.getKey().y, now.getKey().z); - if(tile instanceof SuperPostPostTile){ - ((SuperPostPostTile)tile).isWaystone=false; - } - } - for(Entry now: PostHandler.getBigPosts().entrySet()){ - TileEntity tile = FMLClientHandler.instance().getWorldClient().getTileEntity(now.getKey().x, now.getKey().y, now.getKey().z); - if(tile instanceof SuperPostPostTile){ - ((SuperPostPostTile)tile).isWaystone=false; - } - } - PostHandler.setNativeWaystones(message.waystones); - for(BaseInfo now: PostHandler.getNativeWaystones()){ - TileEntity tile = FMLClientHandler.instance().getWorldClient().getTileEntity(now.blockPosition.x, now.blockPosition.y, now.blockPosition.z); - if(tile instanceof SuperPostPostTile){ - ((SuperPostPostTile)tile).isWaystone=true; - } - } - for(Entry now: PostHandler.getPosts().entrySet()){ - BaseInfo base = now.getValue().sign1.base; - if(base!=null &&!(base.teleportPosition ==null && base.owner==null)){ - now.getValue().sign1.base = PostHandler.getAllWaystones().getByPos(base.blockPosition); - } - base = now.getValue().sign2.base; - if(base!=null &&!(base.teleportPosition ==null && base.owner==null)){ - now.getValue().sign2.base = PostHandler.getAllWaystones().getByPos(base.blockPosition); - } - } - for(Entry now: PostHandler.getBigPosts().entrySet()){ - BaseInfo base = now.getValue().sign.base; - if(base!=null &&!(base.teleportPosition ==null && base.owner==null)){ - now.getValue().sign.base = PostHandler.getAllWaystones().getByPos(base.blockPosition); - } - TileEntity tile = now.getKey().getTile(); - } - return null; - } + @Override + public IMessage onMessage(BaseUpdateClientMessage message, MessageContext ctx) { + for (Entry now : PostHandler.getPosts() + .entrySet()) { + TileEntity tile = FMLClientHandler.instance() + .getWorldClient() + .getTileEntity(now.getKey().x, now.getKey().y, now.getKey().z); + if (tile instanceof SuperPostPostTile) { + ((SuperPostPostTile) tile).isWaystone = false; + } + } + for (Entry now : PostHandler.getBigPosts() + .entrySet()) { + TileEntity tile = FMLClientHandler.instance() + .getWorldClient() + .getTileEntity(now.getKey().x, now.getKey().y, now.getKey().z); + if (tile instanceof SuperPostPostTile) { + ((SuperPostPostTile) tile).isWaystone = false; + } + } + PostHandler.setNativeWaystones(message.waystones); + for (BaseInfo now : PostHandler.getNativeWaystones()) { + TileEntity tile = FMLClientHandler.instance() + .getWorldClient() + .getTileEntity(now.blockPosition.x, now.blockPosition.y, now.blockPosition.z); + if (tile instanceof SuperPostPostTile) { + ((SuperPostPostTile) tile).isWaystone = true; + } + } + for (Entry now : PostHandler.getPosts() + .entrySet()) { + BaseInfo base = now.getValue().sign1.base; + if (base != null && !(base.teleportPosition == null && base.owner == null)) { + now.getValue().sign1.base = PostHandler.getAllWaystones() + .getByPos(base.blockPosition); + } + base = now.getValue().sign2.base; + if (base != null && !(base.teleportPosition == null && base.owner == null)) { + now.getValue().sign2.base = PostHandler.getAllWaystones() + .getByPos(base.blockPosition); + } + } + for (Entry now : PostHandler.getBigPosts() + .entrySet()) { + BaseInfo base = now.getValue().sign.base; + if (base != null && !(base.teleportPosition == null && base.owner == null)) { + now.getValue().sign.base = PostHandler.getAllWaystones() + .getByPos(base.blockPosition); + } + TileEntity tile = now.getKey() + .getTile(); + } + return null; + } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/network/handlers/BaseUpdateServerHandler.java b/src/main/java/gollorum/signpost/network/handlers/BaseUpdateServerHandler.java index e2efc4fe..b3c197f5 100644 --- a/src/main/java/gollorum/signpost/network/handlers/BaseUpdateServerHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/BaseUpdateServerHandler.java @@ -1,5 +1,7 @@ package gollorum.signpost.network.handlers; +import net.minecraftforge.common.MinecraftForge; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; @@ -9,21 +11,27 @@ import gollorum.signpost.network.messages.BaseUpdateClientMessage; import gollorum.signpost.network.messages.BaseUpdateServerMessage; import gollorum.signpost.util.BaseInfo; -import net.minecraftforge.common.MinecraftForge; public class BaseUpdateServerHandler implements IMessageHandler { - @Override - public IMessage onMessage(BaseUpdateServerMessage message, MessageContext ctx) { - if (message.destroyed) { - } else { - PostHandler.addDiscovered(ctx.getServerHandler().playerEntity.getUniqueID(), message.wayStone); - } - BaseInfo waystone = PostHandler.getAllWaystones().getByPos(message.wayStone.blockPosition); - waystone.setAll(message.wayStone); - NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); - MinecraftForge.EVENT_BUS.post(new UpdateWaystoneEvent(UpdateWaystoneEvent.WaystoneEventType.NAMECHANGED, ctx.getServerHandler().playerEntity.worldObj, waystone.teleportPosition.x, waystone.teleportPosition.y, waystone.teleportPosition.z, waystone.getName())); - return null; - } + @Override + public IMessage onMessage(BaseUpdateServerMessage message, MessageContext ctx) { + if (message.destroyed) {} else { + PostHandler.addDiscovered(ctx.getServerHandler().playerEntity.getUniqueID(), message.wayStone); + } + BaseInfo waystone = PostHandler.getAllWaystones() + .getByPos(message.wayStone.blockPosition); + waystone.setAll(message.wayStone); + NetworkHandler.netWrap.sendToAll(new BaseUpdateClientMessage()); + MinecraftForge.EVENT_BUS.post( + new UpdateWaystoneEvent( + UpdateWaystoneEvent.WaystoneEventType.NAMECHANGED, + ctx.getServerHandler().playerEntity.worldObj, + waystone.teleportPosition.x, + waystone.teleportPosition.y, + waystone.teleportPosition.z, + waystone.getName())); + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/ChatHandler.java b/src/main/java/gollorum/signpost/network/handlers/ChatHandler.java index a32bcafa..2a83e7b7 100644 --- a/src/main/java/gollorum/signpost/network/handlers/ChatHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/ChatHandler.java @@ -1,37 +1,42 @@ package gollorum.signpost.network.handlers; +import net.minecraft.client.Minecraft; +import net.minecraft.util.ChatComponentText; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.registry.LanguageRegistry; import gollorum.signpost.network.messages.ChatMessage; -import net.minecraft.client.Minecraft; -import net.minecraft.util.ChatComponentText; public class ChatHandler implements IMessageHandler { - @Override - public IMessage onMessage(ChatMessage message, MessageContext ctx) { - String out = LanguageRegistry.instance().getStringLocalization(message.message); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization(message.message, "en_US"); - } - for(int i=0; i{ +public class InitPlayerResponseHandler implements IMessageHandler { - @Override - public IMessage onMessage(InitPlayerResponseMessage message, MessageContext ctx) { - if(!message.deactivateTeleportation){ - PostHandler.setNativeWaystones(message.allWaystones); - } - ClientConfigStorage.INSTANCE.setDeactivateTeleportation(message.deactivateTeleportation); - ClientConfigStorage.INSTANCE.setInterdimensional(message.interdimensional); - ClientConfigStorage.INSTANCE.setMaxDist(message.maxDist); - ClientConfigStorage.INSTANCE.setPaymentItem(message.paymentItem); - ClientConfigStorage.INSTANCE.setCostMult(message.costMult); - ClientConfigStorage.INSTANCE.setCostBase(message.costBase); - ClientConfigStorage.INSTANCE.setSignRec(message.signRec); - ClientConfigStorage.INSTANCE.setWaysRec(message.waysRec); - ClientConfigStorage.INSTANCE.setSecurityLevelWaystone(message.securityLevelWaystone); - ClientConfigStorage.INSTANCE.setSecurityLevelSignpost(message.securityLevelSignpost); - ClientConfigStorage.INSTANCE.setDisableVillageGeneration(message.disableVillageGeneration); - ClientConfigStorage.INSTANCE.setVillageMaxSignposts(message.villageMaxSignposts); - ClientConfigStorage.INSTANCE.setVillageSignpostsWeight(message.villageSignpostsWeight); - ClientConfigStorage.INSTANCE.setVillageWaystonesWeight(message.villageWaystonesWeight); - ClientConfigStorage.INSTANCE.setOnlyVillageTargets(message.onlyVillageTargets); - ClientConfigStorage.INSTANCE.setAllowedCraftingModels(message.allowedCraftingModels); - ClientConfigStorage.INSTANCE.setAllowedVillageModels(message.allowedVillageModels); - ClientConfigStorage.INSTANCE.postInit(); - return null; - } + @Override + public IMessage onMessage(InitPlayerResponseMessage message, MessageContext ctx) { + if (!message.deactivateTeleportation) { + PostHandler.setNativeWaystones(message.allWaystones); + } + ClientConfigStorage.INSTANCE.setDeactivateTeleportation(message.deactivateTeleportation); + ClientConfigStorage.INSTANCE.setInterdimensional(message.interdimensional); + ClientConfigStorage.INSTANCE.setMaxDist(message.maxDist); + ClientConfigStorage.INSTANCE.setPaymentItem(message.paymentItem); + ClientConfigStorage.INSTANCE.setCostMult(message.costMult); + ClientConfigStorage.INSTANCE.setCostBase(message.costBase); + ClientConfigStorage.INSTANCE.setSignRec(message.signRec); + ClientConfigStorage.INSTANCE.setWaysRec(message.waysRec); + ClientConfigStorage.INSTANCE.setSecurityLevelWaystone(message.securityLevelWaystone); + ClientConfigStorage.INSTANCE.setSecurityLevelSignpost(message.securityLevelSignpost); + ClientConfigStorage.INSTANCE.setDisableVillageGeneration(message.disableVillageGeneration); + ClientConfigStorage.INSTANCE.setVillageMaxSignposts(message.villageMaxSignposts); + ClientConfigStorage.INSTANCE.setVillageSignpostsWeight(message.villageSignpostsWeight); + ClientConfigStorage.INSTANCE.setVillageWaystonesWeight(message.villageWaystonesWeight); + ClientConfigStorage.INSTANCE.setOnlyVillageTargets(message.onlyVillageTargets); + ClientConfigStorage.INSTANCE.setAllowedCraftingModels(message.allowedCraftingModels); + ClientConfigStorage.INSTANCE.setAllowedVillageModels(message.allowedVillageModels); + ClientConfigStorage.INSTANCE.postInit(); + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/OpenGuiHandler.java b/src/main/java/gollorum/signpost/network/handlers/OpenGuiHandler.java index 277bd766..f3ae28dd 100644 --- a/src/main/java/gollorum/signpost/network/handlers/OpenGuiHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/OpenGuiHandler.java @@ -1,18 +1,20 @@ package gollorum.signpost.network.handlers; +import net.minecraft.client.Minecraft; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import gollorum.signpost.Signpost; import gollorum.signpost.network.messages.OpenGuiMessage; -import net.minecraft.client.Minecraft; public class OpenGuiHandler implements IMessageHandler { - @Override - public IMessage onMessage(OpenGuiMessage message, MessageContext ctx) { - Minecraft.getMinecraft().thePlayer.openGui(Signpost.instance, message.guiID, Signpost.proxy.getWorld(ctx), message.x, message.y, message.z); - return null; - } + @Override + public IMessage onMessage(OpenGuiMessage message, MessageContext ctx) { + Minecraft.getMinecraft().thePlayer + .openGui(Signpost.instance, message.guiID, Signpost.proxy.getWorld(ctx), message.x, message.y, message.z); + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/RequestTextureHandler.java b/src/main/java/gollorum/signpost/network/handlers/RequestTextureHandler.java index 67824f71..886a97dd 100644 --- a/src/main/java/gollorum/signpost/network/handlers/RequestTextureHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/RequestTextureHandler.java @@ -6,12 +6,13 @@ import gollorum.signpost.network.messages.RequestTextureMessage; import gollorum.signpost.util.TextureHelper; -public class RequestTextureHandler implements IMessageHandler{ +public class RequestTextureHandler implements IMessageHandler { - @Override - public IMessage onMessage(RequestTextureMessage message, MessageContext ctx) { - TextureHelper.instance().setTexture(message.x, message.y, message.z); - return null; - } + @Override + public IMessage onMessage(RequestTextureMessage message, MessageContext ctx) { + TextureHelper.instance() + .setTexture(message.x, message.y, message.z); + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/SendAllBigPostBasesHandler.java b/src/main/java/gollorum/signpost/network/handlers/SendAllBigPostBasesHandler.java index 6119ee19..003c198a 100644 --- a/src/main/java/gollorum/signpost/network/handlers/SendAllBigPostBasesHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/SendAllBigPostBasesHandler.java @@ -2,6 +2,8 @@ import java.util.Map.Entry; +import net.minecraft.tileentity.TileEntity; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; @@ -11,35 +13,35 @@ import gollorum.signpost.network.messages.SendAllBigPostBasesMessage.BigStringInt; import gollorum.signpost.util.BigBaseInfo; import gollorum.signpost.util.MyBlockPos; -import net.minecraft.tileentity.TileEntity; public class SendAllBigPostBasesHandler implements IMessageHandler { - @Override - public IMessage onMessage(SendAllBigPostBasesMessage message, MessageContext ctx) { - PostHandler.setBigPosts(message.toPostMap()); - for(Entry now: message.bigPosts.entrySet()){ - TileEntity tileEntity = now.getKey().getTile(); - if(tileEntity instanceof BigPostPostTile){ - BigPostPostTile postTile = (BigPostPostTile) tileEntity; - BigBaseInfo bases = postTile.getBases(); - switch(now.getValue().paintObjectIndex){ - case 1: - bases.paintObject = bases; - bases.awaitingPaint = true; - break; - case 2: - bases.paintObject = bases.sign; - bases.awaitingPaint = true; - break; - default: - bases.paintObject = null; - bases.awaitingPaint = false; - break; - } - } - } - return null; - } - -} \ No newline at end of file + @Override + public IMessage onMessage(SendAllBigPostBasesMessage message, MessageContext ctx) { + PostHandler.setBigPosts(message.toPostMap()); + for (Entry now : message.bigPosts.entrySet()) { + TileEntity tileEntity = now.getKey() + .getTile(); + if (tileEntity instanceof BigPostPostTile) { + BigPostPostTile postTile = (BigPostPostTile) tileEntity; + BigBaseInfo bases = postTile.getBases(); + switch (now.getValue().paintObjectIndex) { + case 1: + bases.paintObject = bases; + bases.awaitingPaint = true; + break; + case 2: + bases.paintObject = bases.sign; + bases.awaitingPaint = true; + break; + default: + bases.paintObject = null; + bases.awaitingPaint = false; + break; + } + } + } + return null; + } + +} diff --git a/src/main/java/gollorum/signpost/network/handlers/SendAllPostBasesHandler.java b/src/main/java/gollorum/signpost/network/handlers/SendAllPostBasesHandler.java index a54563d5..a60c2c42 100644 --- a/src/main/java/gollorum/signpost/network/handlers/SendAllPostBasesHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/SendAllPostBasesHandler.java @@ -2,6 +2,8 @@ import java.util.Map.Entry; +import net.minecraft.tileentity.TileEntity; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; @@ -11,39 +13,39 @@ import gollorum.signpost.network.messages.SendAllPostBasesMessage.DoubleStringInt; import gollorum.signpost.util.DoubleBaseInfo; import gollorum.signpost.util.MyBlockPos; -import net.minecraft.tileentity.TileEntity; public class SendAllPostBasesHandler implements IMessageHandler { - @Override - public IMessage onMessage(SendAllPostBasesMessage message, MessageContext ctx) { - PostHandler.setPosts(message.toPostMap()); - for(Entry now: message.posts.entrySet()){ - TileEntity tileEntity = now.getKey().getTile(); - if(tileEntity instanceof PostPostTile){ - PostPostTile postTile = (PostPostTile) tileEntity; - DoubleBaseInfo bases = postTile.getBases(); - switch(now.getValue().paintObjectIndex){ - case 1: - bases.paintObject = bases; - bases.awaitingPaint = true; - break; - case 2: - bases.paintObject = bases.sign1; - bases.awaitingPaint = true; - break; - case 3: - bases.paintObject = bases.sign2; - bases.awaitingPaint = true; - break; - default: - bases.paintObject = null; - bases.awaitingPaint = false; - break; - } - } - } - return null; - } - -} \ No newline at end of file + @Override + public IMessage onMessage(SendAllPostBasesMessage message, MessageContext ctx) { + PostHandler.setPosts(message.toPostMap()); + for (Entry now : message.posts.entrySet()) { + TileEntity tileEntity = now.getKey() + .getTile(); + if (tileEntity instanceof PostPostTile) { + PostPostTile postTile = (PostPostTile) tileEntity; + DoubleBaseInfo bases = postTile.getBases(); + switch (now.getValue().paintObjectIndex) { + case 1: + bases.paintObject = bases; + bases.awaitingPaint = true; + break; + case 2: + bases.paintObject = bases.sign1; + bases.awaitingPaint = true; + break; + case 3: + bases.paintObject = bases.sign2; + bases.awaitingPaint = true; + break; + default: + bases.paintObject = null; + bases.awaitingPaint = false; + break; + } + } + } + return null; + } + +} diff --git a/src/main/java/gollorum/signpost/network/handlers/SendAllWaystoneNamesHandler.java b/src/main/java/gollorum/signpost/network/handlers/SendAllWaystoneNamesHandler.java index a89150ad..931909c4 100644 --- a/src/main/java/gollorum/signpost/network/handlers/SendAllWaystoneNamesHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/SendAllWaystoneNamesHandler.java @@ -8,14 +8,14 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import gollorum.signpost.network.messages.SendAllWaystoneNamesMessage; -public class SendAllWaystoneNamesHandler implements IMessageHandler{ - - public static Collection cachedWaystoneNames = new HashSet(); +public class SendAllWaystoneNamesHandler implements IMessageHandler { - @Override - public IMessage onMessage(SendAllWaystoneNamesMessage message, MessageContext ctx) { - cachedWaystoneNames = message.waystones; - return null; - } + public static Collection cachedWaystoneNames = new HashSet(); -} \ No newline at end of file + @Override + public IMessage onMessage(SendAllWaystoneNamesMessage message, MessageContext ctx) { + cachedWaystoneNames = message.waystones; + return null; + } + +} diff --git a/src/main/java/gollorum/signpost/network/handlers/SendBigPostBasesHandler.java b/src/main/java/gollorum/signpost/network/handlers/SendBigPostBasesHandler.java index 1f22bebc..cd1a73e9 100644 --- a/src/main/java/gollorum/signpost/network/handlers/SendBigPostBasesHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/SendBigPostBasesHandler.java @@ -1,5 +1,7 @@ package gollorum.signpost.network.handlers; +import net.minecraft.tileentity.TileEntity; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; @@ -11,53 +13,55 @@ import gollorum.signpost.util.BigBaseInfo; import gollorum.signpost.util.Sign; import gollorum.signpost.util.Sign.OverlayType; -import net.minecraft.tileentity.TileEntity; -public class SendBigPostBasesHandler implements IMessageHandler{ +public class SendBigPostBasesHandler implements IMessageHandler { + + @Override + public IMessage onMessage(SendBigPostBasesMessage message, MessageContext ctx) { + TileEntity tile = message.pos.getTile(); + BigBaseInfo bases; + if (tile instanceof BigPostPostTile) { + BigPostPostTile postTile = (BigPostPostTile) tile; + postTile.isWaystone(); + bases = postTile.getBases(); + } else { + bases = PostHandler.getBigPosts() + .get(message.pos); + if (bases == null) { + bases = new BigBaseInfo(new Sign(null), null); + PostHandler.getBigPosts() + .put(message.pos, bases); + } + } + bases.sign.rotation = message.baserot; + bases.sign.flip = message.flip; + bases.sign.base = PostHandler.getForceWSbyName(message.base); + bases.sign.overlay = OverlayType.get(message.overlay); + bases.sign.point = message.point; + bases.description = message.description; + bases.sign.paint = message.paint; + bases.postPaint = message.postPaint; - @Override - public IMessage onMessage(SendBigPostBasesMessage message, MessageContext ctx) { - TileEntity tile = message.pos.getTile(); - BigBaseInfo bases; - if(tile instanceof BigPostPostTile){ - BigPostPostTile postTile = (BigPostPostTile) tile; - postTile.isWaystone(); - bases = postTile.getBases(); - }else{ - bases = PostHandler.getBigPosts().get(message.pos); - if(bases==null){ - bases = new BigBaseInfo(new Sign(null), null); - PostHandler.getBigPosts().put(message.pos, bases); - } - } - bases.sign.rotation = message.baserot; - bases.sign.flip = message.flip; - bases.sign.base = PostHandler.getForceWSbyName(message.base); - bases.sign.overlay = OverlayType.get(message.overlay); - bases.sign.point = message.point; - bases.description = message.description; - bases.sign.paint = message.paint; - bases.postPaint = message.postPaint; - - switch(message.paintObjectIndex){ - case 1: - bases.paintObject = bases; - bases.awaitingPaint = true; - break; - case 2: - bases.paintObject = bases.sign; - bases.awaitingPaint = true; - break; - default: - bases.paintObject = null; - bases.awaitingPaint = false; - break; - } - if(ctx.side.equals(Side.SERVER)){ - ctx.getServerHandler().playerEntity.worldObj.getTileEntity(message.pos.x, message.pos.y, message.pos.z).markDirty(); - NetworkHandler.netWrap.sendToAll(message); - } - return null; - } + switch (message.paintObjectIndex) { + case 1: + bases.paintObject = bases; + bases.awaitingPaint = true; + break; + case 2: + bases.paintObject = bases.sign; + bases.awaitingPaint = true; + break; + default: + bases.paintObject = null; + bases.awaitingPaint = false; + break; + } + if (ctx.side.equals(Side.SERVER)) { + ctx.getServerHandler().playerEntity.worldObj.getTileEntity(message.pos.x, message.pos.y, message.pos.z) + .markDirty(); + NetworkHandler.netWrap.sendToAll(message); + } + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/SendDiscoveredToServerHandler.java b/src/main/java/gollorum/signpost/network/handlers/SendDiscoveredToServerHandler.java index 57a8f1a2..539ce69a 100644 --- a/src/main/java/gollorum/signpost/network/handlers/SendDiscoveredToServerHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/SendDiscoveredToServerHandler.java @@ -8,10 +8,12 @@ public class SendDiscoveredToServerHandler implements IMessageHandler { - @Override - public IMessage onMessage(SendDiscoveredToServerMessage message, MessageContext ctx) { - PostHandler.addDiscovered(ctx.getServerHandler().playerEntity.getUniqueID(), PostHandler.getWSbyName(message.waystone)); - return null; - } + @Override + public IMessage onMessage(SendDiscoveredToServerMessage message, MessageContext ctx) { + PostHandler.addDiscovered( + ctx.getServerHandler().playerEntity.getUniqueID(), + PostHandler.getWSbyName(message.waystone)); + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/SendPostBasesHandler.java b/src/main/java/gollorum/signpost/network/handlers/SendPostBasesHandler.java index bc8e3fb4..91301e4d 100644 --- a/src/main/java/gollorum/signpost/network/handlers/SendPostBasesHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/SendPostBasesHandler.java @@ -1,5 +1,7 @@ package gollorum.signpost.network.handlers; +import net.minecraft.tileentity.TileEntity; + import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; @@ -11,66 +13,68 @@ import gollorum.signpost.network.messages.SendPostBasesMessage; import gollorum.signpost.util.DoubleBaseInfo; import gollorum.signpost.util.Sign.OverlayType; -import net.minecraft.tileentity.TileEntity; -public class SendPostBasesHandler implements IMessageHandler{ +public class SendPostBasesHandler implements IMessageHandler { + + @Override + public IMessage onMessage(SendPostBasesMessage message, MessageContext ctx) { + TileEntity tile = message.pos.getTile(); + DoubleBaseInfo bases; + if (tile instanceof PostPostTile) { + PostPostTile postTile = (PostPostTile) tile; + postTile.isWaystone(); + bases = postTile.getBases(); + } else { + bases = PostHandler.getPosts() + .get(message.pos); + if (bases == null) { + bases = new DoubleBaseInfo(null, null); + PostHandler.getPosts() + .put(message.pos, bases); + } + } + bases.sign1.rotation = message.base1rot; + bases.sign2.rotation = message.base2rot; + bases.sign1.flip = message.flip1; + bases.sign2.flip = message.flip2; + bases.sign1.base = PostHandler.getForceWSbyName(message.base1); + bases.sign2.base = PostHandler.getForceWSbyName(message.base2); + + bases.sign1.overlay = OverlayType.get(message.overlay1); + bases.sign2.overlay = OverlayType.get(message.overlay2); + + bases.sign1.point = message.point1; + bases.sign2.point = message.point2; + bases.sign1.paint = SuperPostPostTile.stringToLoc(message.paint1); + bases.sign2.paint = SuperPostPostTile.stringToLoc(message.paint2); - @Override - public IMessage onMessage(SendPostBasesMessage message, MessageContext ctx) { - TileEntity tile = message.pos.getTile(); - DoubleBaseInfo bases; - if(tile instanceof PostPostTile){ - PostPostTile postTile = (PostPostTile) tile; - postTile.isWaystone(); - bases = postTile.getBases(); - }else{ - bases = PostHandler.getPosts().get(message.pos); - if(bases==null){ - bases = new DoubleBaseInfo(null, null); - PostHandler.getPosts().put(message.pos, bases); - } - } - bases.sign1.rotation = message.base1rot; - bases.sign2.rotation = message.base2rot; - bases.sign1.flip = message.flip1; - bases.sign2.flip = message.flip2; - bases.sign1.base = PostHandler.getForceWSbyName(message.base1); - bases.sign2.base = PostHandler.getForceWSbyName(message.base2); - - bases.sign1.overlay = OverlayType.get(message.overlay1); - bases.sign2.overlay = OverlayType.get(message.overlay2); - - bases.sign1.point = message.point1; - bases.sign2.point = message.point2; - bases.sign1.paint = SuperPostPostTile.stringToLoc(message.paint1); - bases.sign2.paint = SuperPostPostTile.stringToLoc(message.paint2); - - bases.postPaint = SuperPostPostTile.stringToLoc(message.postPaint); + bases.postPaint = SuperPostPostTile.stringToLoc(message.postPaint); - switch(message.paintObjectIndex){ - case 1: - bases.paintObject = bases; - bases.awaitingPaint = true; - break; - case 2: - bases.paintObject = bases.sign1; - bases.awaitingPaint = true; - break; - case 3: - bases.paintObject = bases.sign2; - bases.awaitingPaint = true; - break; - default: - bases.paintObject = null; - bases.awaitingPaint = false; - break; - } + switch (message.paintObjectIndex) { + case 1: + bases.paintObject = bases; + bases.awaitingPaint = true; + break; + case 2: + bases.paintObject = bases.sign1; + bases.awaitingPaint = true; + break; + case 3: + bases.paintObject = bases.sign2; + bases.awaitingPaint = true; + break; + default: + bases.paintObject = null; + bases.awaitingPaint = false; + break; + } - if(ctx.side.equals(Side.SERVER)){ - ctx.getServerHandler().playerEntity.worldObj.getTileEntity(message.pos.x, message.pos.y, message.pos.z).markDirty(); - NetworkHandler.netWrap.sendToAll(message); - } - return null; - } + if (ctx.side.equals(Side.SERVER)) { + ctx.getServerHandler().playerEntity.worldObj.getTileEntity(message.pos.x, message.pos.y, message.pos.z) + .markDirty(); + NetworkHandler.netWrap.sendToAll(message); + } + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/TeleportMeHandler.java b/src/main/java/gollorum/signpost/network/handlers/TeleportMeHandler.java index f80a6ee8..d98ce053 100644 --- a/src/main/java/gollorum/signpost/network/handlers/TeleportMeHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/TeleportMeHandler.java @@ -1,5 +1,11 @@ package gollorum.signpost.network.handlers; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.management.ServerConfigurationManager; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; + import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; @@ -8,37 +14,38 @@ import gollorum.signpost.management.PostHandler; import gollorum.signpost.network.messages.ChatMessage; import gollorum.signpost.network.messages.TeleportMeMessage; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.management.ServerConfigurationManager; -import net.minecraft.world.World; -import net.minecraft.world.WorldServer; public class TeleportMeHandler implements IMessageHandler { - @Override - public IMessage onMessage(TeleportMeMessage message, MessageContext ctx) { - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()){ - return null; - } - if(PostHandler.canTeleport(ctx.getServerHandler().playerEntity, message.base)){ - World world = message.base.teleportPosition.getWorld(); - if(world == null){ - return new ChatMessage("signpost.errorWorld", "", ""+message.base.teleportPosition.dim); - }else{ - ServerConfigurationManager manager = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager(); - EntityPlayerMP player = ctx.getServerHandler().playerEntity; - if(!player.worldObj.equals(world)){ - manager.transferEntityToWorld(player, 1, (WorldServer)player.worldObj, (WorldServer)world); - } - if(!(player.dimension==message.base.teleportPosition.dim)){ - WorldServer minecraftserver = MinecraftServer.getServer().worldServerForDimension(message.base.teleportPosition.dim); - manager.transferEntityToWorld(player, 1, (WorldServer)player.worldObj, minecraftserver); - } - ctx.getServerHandler().playerEntity.setPositionAndUpdate(message.base.teleportPosition.x, message.base.teleportPosition.y, message.base.teleportPosition.z); - } - } - return null; - } + @Override + public IMessage onMessage(TeleportMeMessage message, MessageContext ctx) { + if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + return null; + } + if (PostHandler.canTeleport(ctx.getServerHandler().playerEntity, message.base)) { + World world = message.base.teleportPosition.getWorld(); + if (world == null) { + return new ChatMessage("signpost.errorWorld", "", "" + message.base.teleportPosition.dim); + } else { + ServerConfigurationManager manager = FMLCommonHandler.instance() + .getMinecraftServerInstance() + .getConfigurationManager(); + EntityPlayerMP player = ctx.getServerHandler().playerEntity; + if (!player.worldObj.equals(world)) { + manager.transferEntityToWorld(player, 1, (WorldServer) player.worldObj, (WorldServer) world); + } + if (!(player.dimension == message.base.teleportPosition.dim)) { + WorldServer minecraftserver = MinecraftServer.getServer() + .worldServerForDimension(message.base.teleportPosition.dim); + manager.transferEntityToWorld(player, 1, (WorldServer) player.worldObj, minecraftserver); + } + ctx.getServerHandler().playerEntity.setPositionAndUpdate( + message.base.teleportPosition.x, + message.base.teleportPosition.y, + message.base.teleportPosition.z); + } + } + return null; + } } diff --git a/src/main/java/gollorum/signpost/network/handlers/TeleportRequestHandler.java b/src/main/java/gollorum/signpost/network/handlers/TeleportRequestHandler.java index 05bfa253..bb8a348a 100644 --- a/src/main/java/gollorum/signpost/network/handlers/TeleportRequestHandler.java +++ b/src/main/java/gollorum/signpost/network/handlers/TeleportRequestHandler.java @@ -1,5 +1,7 @@ package gollorum.signpost.network.handlers; +import net.minecraft.util.ChatComponentText; + import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; @@ -10,48 +12,54 @@ import gollorum.signpost.management.ConfigHandler; import gollorum.signpost.management.PostHandler; import gollorum.signpost.network.messages.TeleportRequestMessage; -import net.minecraft.util.ChatComponentText; public class TeleportRequestHandler implements IMessageHandler { - @Override - public IMessage onMessage(TeleportRequestMessage message, MessageContext ctx) { - if(ctx.side.equals(Side.SERVER)){ - PostHandler.confirm(ctx.getServerHandler().playerEntity); - }else{ - if(ClientConfigStorage.INSTANCE.skipTeleportConfirm()){ - return message; - }else{ - String out; - if(ClientConfigStorage.INSTANCE.getCost()!=null){ - out = LanguageRegistry.instance().getStringLocalization("signpost.confirmTeleport"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.confirmTeleport", "en_US"); - } - out = out.replaceAll("", message.waystoneName) - .replaceAll("", Integer.toString(message.stackSize)) - .replaceAll("", ConfigHandler.costName()); - }else{ - out = LanguageRegistry.instance().getStringLocalization("signpost.confirmTeleportNoCost"); - if(out.equals("")){ - out = LanguageRegistry.instance().getStringLocalization("signpost.confirmTeleportNoCost", "en_US"); - } - out = out.replaceAll("", message.waystoneName); - } - FMLClientHandler.instance().getClient().thePlayer.addChatMessage(new ChatComponentText(out)); - } - } - return null; - } + @Override + public IMessage onMessage(TeleportRequestMessage message, MessageContext ctx) { + if (ctx.side.equals(Side.SERVER)) { + PostHandler.confirm(ctx.getServerHandler().playerEntity); + } else { + if (ClientConfigStorage.INSTANCE.skipTeleportConfirm()) { + return message; + } else { + String out; + if (ClientConfigStorage.INSTANCE.getCost() != null) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.confirmTeleport"); + if (out.equals("")) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.confirmTeleport", "en_US"); + } + out = out.replaceAll("", message.waystoneName) + .replaceAll("", Integer.toString(message.stackSize)) + .replaceAll("", ConfigHandler.costName()); + } else { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.confirmTeleportNoCost"); + if (out.equals("")) { + out = LanguageRegistry.instance() + .getStringLocalization("signpost.confirmTeleportNoCost", "en_US"); + } + out = out.replaceAll("", message.waystoneName); + } + FMLClientHandler.instance() + .getClient().thePlayer.addChatMessage(new ChatComponentText(out)); + } + } + return null; + } - public String getReplacement(String replace){ - String ret = LanguageRegistry.instance().getStringLocalization(replace); - if(!ret.equals("")){ - return ret; - } - if(!(ret = LanguageRegistry.instance().getStringLocalization(replace, "en_US")).equals("")){ - return ret; - } - return replace; - } + public String getReplacement(String replace) { + String ret = LanguageRegistry.instance() + .getStringLocalization(replace); + if (!ret.equals("")) { + return ret; + } + if (!(ret = LanguageRegistry.instance() + .getStringLocalization(replace, "en_US")).equals("")) { + return ret; + } + return replace; + } } diff --git a/src/main/java/gollorum/signpost/network/messages/BaseUpdateClientMessage.java b/src/main/java/gollorum/signpost/network/messages/BaseUpdateClientMessage.java index 14b286ce..fd1f0c2e 100644 --- a/src/main/java/gollorum/signpost/network/messages/BaseUpdateClientMessage.java +++ b/src/main/java/gollorum/signpost/network/messages/BaseUpdateClientMessage.java @@ -8,27 +8,27 @@ public class BaseUpdateClientMessage implements IMessage { - public StonedHashSet waystones = new StonedHashSet(); - - public BaseUpdateClientMessage(){ - waystones = PostHandler.getNativeWaystones(); - } - - @Override - public void toBytes(ByteBuf buf) { - buf.writeInt(waystones.size()); - for(BaseInfo now: waystones){ - now.toBytes(buf); - } - } + public StonedHashSet waystones = new StonedHashSet(); - @Override - public void fromBytes(ByteBuf buf) { - waystones = new StonedHashSet(); - int c = buf.readInt(); - for(int i = 0; i bigPosts = new HashMap(); -public class SendAllBigPostBasesMessage implements IMessage{ + public Map toPostMap() { + Map postMap = new HashMap<>(); + for (Entry now : bigPosts.entrySet()) { + BaseInfo base = PostHandler.getForceWSbyName(now.getValue().string); + postMap.put( + now.getKey(), + new BigBaseInfo( + new Sign( + base, + now.getValue().datInt, + now.getValue().bool, + now.getValue().overlay, + now.getValue().bool2, + now.getValue().paint), + now.getValue().strings, + now.getValue().postPaint)); + } + return postMap; + } - public class BigStringInt{ - public String string; - public int datInt; - public boolean bool; - public OverlayType overlay; - public boolean bool2; - public String[] strings; - public ResourceLocation paint; - public ResourceLocation postPaint; + public SendAllBigPostBasesMessage() {} - public byte paintObjectIndex; - - public BigStringInt(String string, int datInt, boolean bool, OverlayType overlay, boolean bool2, String[] strings, ResourceLocation paint, ResourceLocation postPaint, byte paintObjectIndex) { - this.string = string; - this.datInt = datInt; - this.bool = bool; - this.overlay = overlay; - this.bool2 = bool2; - this.strings = strings; - this.paint = paint; - this.postPaint = postPaint; - this.paintObjectIndex = paintObjectIndex; - } - } - - public HashMap bigPosts = new HashMap(); + @Override + public void toBytes(ByteBuf buf) { + buf.writeInt( + PostHandler.getBigPosts() + .size()); + for (Entry now : PostHandler.getBigPosts() + .entrySet()) { + now.getKey() + .toBytes(buf); + ByteBufUtils.writeUTF8String(buf, "" + now.getValue().sign.base); + buf.writeInt(now.getValue().sign.rotation); + buf.writeBoolean(now.getValue().sign.flip); + ByteBufUtils.writeUTF8String(buf, "" + now.getValue().sign.overlay); + buf.writeBoolean(now.getValue().sign.point); + buf.writeInt(now.getValue().description.length); + for (String now2 : now.getValue().description) { + ByteBufUtils.writeUTF8String(buf, now2); + } + ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().sign.paint)); + ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().postPaint)); + BigPostPostTile tile = (BigPostPostTile) now.getKey() + .getTile(); + if (tile != null) { + if (now.getValue() + .equals(tile.getPaintObject())) { + buf.writeByte(1); + } else if (now.getValue().sign.equals(tile.getPaintObject())) { + buf.writeByte(2); + } else { + buf.writeByte(0); + } + } else { + buf.writeByte(0); + } + } + } - public Map toPostMap(){ - Map postMap = new HashMap<>(); - for(Entry now: bigPosts.entrySet()){ - BaseInfo base = PostHandler.getForceWSbyName(now.getValue().string); - postMap.put(now.getKey(), new BigBaseInfo(new Sign( - base, - now.getValue().datInt, - now.getValue().bool, - now.getValue().overlay, - now.getValue().bool2, - now.getValue().paint), - now.getValue().strings, - now.getValue().postPaint)); - } - return postMap; - } - - public SendAllBigPostBasesMessage(){} + @Override + public void fromBytes(ByteBuf buf) { + int c = buf.readInt(); + for (int i = 0; i < c; i++) { + bigPosts.put( + MyBlockPos.fromBytes(buf), + new BigStringInt( + ByteBufUtils.readUTF8String(buf), + buf.readInt(), + buf.readBoolean(), + OverlayType.get(ByteBufUtils.readUTF8String(buf)), + buf.readBoolean(), + readDescription(buf), + SuperPostPostTile.stringToLoc(ByteBufUtils.readUTF8String(buf)), + SuperPostPostTile.stringToLoc(ByteBufUtils.readUTF8String(buf)), + buf.readByte())); + } + } - @Override - public void toBytes(ByteBuf buf) { - buf.writeInt(PostHandler.getBigPosts().size()); - for(Entry now: PostHandler.getBigPosts().entrySet()){ - now.getKey().toBytes(buf); - ByteBufUtils.writeUTF8String(buf, ""+now.getValue().sign.base); - buf.writeInt(now.getValue().sign.rotation); - buf.writeBoolean(now.getValue().sign.flip); - ByteBufUtils.writeUTF8String(buf, ""+now.getValue().sign.overlay); - buf.writeBoolean(now.getValue().sign.point); - buf.writeInt(now.getValue().description.length); - for(String now2: now.getValue().description){ - ByteBufUtils.writeUTF8String(buf, now2); - } - ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().sign.paint)); - ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().postPaint)); - BigPostPostTile tile = (BigPostPostTile) now.getKey().getTile(); - if(tile!=null){ - if(now.getValue().equals(tile.getPaintObject())){ - buf.writeByte(1); - }else if(now.getValue().sign.equals(tile.getPaintObject())){ - buf.writeByte(2); - }else{ - buf.writeByte(0); - } - }else{ - buf.writeByte(0); - } - } - } - - @Override - public void fromBytes(ByteBuf buf) { - int c = buf.readInt(); - for(int i = 0; i posts = new HashMap<>(); + + public Map toPostMap() { + Map postMap = new HashMap<>(); + for (Entry now : posts.entrySet()) { + BaseInfo base1 = PostHandler.getForceWSbyName(now.getValue().string1); + BaseInfo base2 = PostHandler.getForceWSbyName(now.getValue().string2); + ResourceLocation paint1 = SuperPostPostTile.stringToLoc(now.getValue().paint1); + ResourceLocation paint2 = SuperPostPostTile.stringToLoc(now.getValue().paint2); + ResourceLocation postPaint = SuperPostPostTile.stringToLoc(now.getValue().postPaint); + DoubleBaseInfo neu = postMap.put( + now.getKey(), + new DoubleBaseInfo( + new Sign( + base1, + now.getValue().int1, + now.getValue().bool1, + now.getValue().overlay1, + now.getValue().bool3, + paint1), + new Sign( + base2, + now.getValue().int2, + now.getValue().bool2, + now.getValue().overlay2, + now.getValue().bool4, + paint2), + postPaint)); + } + return postMap; + } + + public SendAllPostBasesMessage() {} + + @Override + public void toBytes(ByteBuf buf) { + buf.writeInt( + PostHandler.getPosts() + .size()); + for (Entry now : PostHandler.getPosts() + .entrySet()) { + now.getKey() + .toBytes(buf); + ByteBufUtils.writeUTF8String(buf, "" + now.getValue().sign1.base); + ByteBufUtils.writeUTF8String(buf, "" + now.getValue().sign2.base); + buf.writeInt(now.getValue().sign1.rotation); + buf.writeInt(now.getValue().sign2.rotation); + buf.writeBoolean(now.getValue().sign1.flip); + buf.writeBoolean(now.getValue().sign2.flip); + ByteBufUtils.writeUTF8String(buf, "" + now.getValue().sign1.overlay); + ByteBufUtils.writeUTF8String(buf, "" + now.getValue().sign2.overlay); + buf.writeBoolean(now.getValue().sign1.point); + buf.writeBoolean(now.getValue().sign2.point); + ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().sign1.paint)); + ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().sign2.paint)); + ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().postPaint)); + PostPostTile tile = (PostPostTile) now.getKey() + .getTile(); + if (tile != null) { + if (now.getValue() + .equals(tile.getPaintObject())) { + buf.writeByte(1); + } else if (now.getValue().sign1.equals(tile.getPaintObject())) { + buf.writeByte(2); + } else if (now.getValue().sign2.equals(tile.getPaintObject())) { + buf.writeByte(3); + } else { + buf.writeByte(0); + } + } else { + buf.writeByte(0); + } + } + } -public class SendAllPostBasesMessage implements IMessage{ - - public class DoubleStringInt{ - public String string1; - public String string2; - - public int int1; - public int int2; - - public boolean bool1; - public boolean bool2; - - public OverlayType overlay1; - public OverlayType overlay2; - - public boolean bool3; - public boolean bool4; - - public String paint1; - public String paint2; - - public String postPaint; - - public byte paintObjectIndex; - - public DoubleStringInt( - String string1, String string2, - int int1, int int2, - boolean bool1, boolean bool2, - OverlayType overlay1, OverlayType overlay2, - boolean bool3, boolean bool4, - String paint1, String paint2, - String postPaint, - byte paintObjectIndex - ) { - this.string1 = string1; - this.string2 = string2; - this.int1 = int1; - this.int2 = int2; - this.bool1 = bool1; - this.bool2 = bool2; - this.overlay1 = overlay1; - this.overlay2 = overlay2; - this.bool3 = bool3; - this.bool4 = bool4; - this.paint1 = paint1; - this.paint2 = paint2; - this.postPaint = postPaint; - this.paintObjectIndex = paintObjectIndex; - } - } - - public HashMap posts = new HashMap<>(); - - public Map toPostMap(){ - Map postMap = new HashMap<>(); - for(Entry now: posts.entrySet()){ - BaseInfo base1 = PostHandler.getForceWSbyName(now.getValue().string1); - BaseInfo base2 = PostHandler.getForceWSbyName(now.getValue().string2); - ResourceLocation paint1 = SuperPostPostTile.stringToLoc(now.getValue().paint1); - ResourceLocation paint2 = SuperPostPostTile.stringToLoc(now.getValue().paint2); - ResourceLocation postPaint = SuperPostPostTile.stringToLoc(now.getValue().postPaint); - DoubleBaseInfo neu = postMap.put( - now.getKey(), - new DoubleBaseInfo( - new Sign( - base1, - now.getValue().int1, - now.getValue().bool1, - now.getValue().overlay1, - now.getValue().bool3, - paint1 - ), - new Sign( - base2, - now.getValue().int2, - now.getValue().bool2, - now.getValue().overlay2, - now.getValue().bool4, - paint2 - ), - postPaint)); - } - return postMap; - } - - public SendAllPostBasesMessage(){} - - @Override - public void toBytes(ByteBuf buf) { - buf.writeInt(PostHandler.getPosts().size()); - for(Entry now: PostHandler.getPosts().entrySet()){ - now.getKey().toBytes(buf); - ByteBufUtils.writeUTF8String(buf, ""+now.getValue().sign1.base); - ByteBufUtils.writeUTF8String(buf, ""+now.getValue().sign2.base); - buf.writeInt(now.getValue().sign1.rotation); - buf.writeInt(now.getValue().sign2.rotation); - buf.writeBoolean(now.getValue().sign1.flip); - buf.writeBoolean(now.getValue().sign2.flip); - ByteBufUtils.writeUTF8String(buf, ""+now.getValue().sign1.overlay); - ByteBufUtils.writeUTF8String(buf, ""+now.getValue().sign2.overlay); - buf.writeBoolean(now.getValue().sign1.point); - buf.writeBoolean(now.getValue().sign2.point); - ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().sign1.paint)); - ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().sign2.paint)); - ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(now.getValue().postPaint)); - PostPostTile tile = (PostPostTile) now.getKey().getTile(); - if(tile!=null){ - if(now.getValue().equals(tile.getPaintObject())){ - buf.writeByte(1); - }else if(now.getValue().sign1.equals(tile.getPaintObject())){ - buf.writeByte(2); - }else if(now.getValue().sign2.equals(tile.getPaintObject())){ - buf.writeByte(3); - }else{ - buf.writeByte(0); - } - }else{ - buf.writeByte(0); - } - } - } - - @Override - public void fromBytes(ByteBuf buf) { - int c = buf.readInt(); - for(int i = 0; i waystones; - - public SendAllWaystoneNamesMessage(Collection waystones) { - this.waystones = waystones; - } - - public SendAllWaystoneNamesMessage() { - } - - @Override - public void fromBytes(ByteBuf buf) { - int count = buf.readInt(); - waystones = new HashSet(count); - for (int i = 0; i < count; i++) { - String name = ByteBufUtils.readUTF8String(buf); - waystones.add(name); - System.out.println("FromBytes: "+name); - } - } - - @Override - public void toBytes(ByteBuf buf) { - buf.writeInt(waystones.size()); - for (String name : waystones) { - ByteBufUtils.writeUTF8String(buf, name); - System.out.println("ToBytes: "+name); - } - } - -} \ No newline at end of file + public Collection waystones; + + public SendAllWaystoneNamesMessage(Collection waystones) { + this.waystones = waystones; + } + + public SendAllWaystoneNamesMessage() {} + + @Override + public void fromBytes(ByteBuf buf) { + int count = buf.readInt(); + waystones = new HashSet(count); + for (int i = 0; i < count; i++) { + String name = ByteBufUtils.readUTF8String(buf); + waystones.add(name); + System.out.println("FromBytes: " + name); + } + } + + @Override + public void toBytes(ByteBuf buf) { + buf.writeInt(waystones.size()); + for (String name : waystones) { + ByteBufUtils.writeUTF8String(buf, name); + System.out.println("ToBytes: " + name); + } + } + +} diff --git a/src/main/java/gollorum/signpost/network/messages/SendBigPostBasesMessage.java b/src/main/java/gollorum/signpost/network/messages/SendBigPostBasesMessage.java index 8bf071e7..43649739 100644 --- a/src/main/java/gollorum/signpost/network/messages/SendBigPostBasesMessage.java +++ b/src/main/java/gollorum/signpost/network/messages/SendBigPostBasesMessage.java @@ -1,5 +1,7 @@ package gollorum.signpost.network.messages; +import net.minecraft.util.ResourceLocation; + import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import gollorum.signpost.blocks.tiles.BigPostPostTile; @@ -7,77 +9,78 @@ import gollorum.signpost.util.BigBaseInfo; import gollorum.signpost.util.MyBlockPos; import io.netty.buffer.ByteBuf; -import net.minecraft.util.ResourceLocation; public class SendBigPostBasesMessage implements IMessage { - public MyBlockPos pos; - public String base; - public int baserot; - public boolean flip; - public String overlay; - public boolean point; - public String[] description; - public ResourceLocation paint; - public ResourceLocation postPaint; + public MyBlockPos pos; + public String base; + public int baserot; + public boolean flip; + public String overlay; + public boolean point; + public String[] description; + public ResourceLocation paint; + public ResourceLocation postPaint; + + public byte paintObjectIndex; + + public SendBigPostBasesMessage() {} - public byte paintObjectIndex; + public SendBigPostBasesMessage(BigPostPostTile tile, BigBaseInfo base) { + tile.markDirty(); + this.pos = tile.toPos(); + this.base = "" + base.sign.base; + baserot = base.sign.rotation; + flip = base.sign.flip; + overlay = "" + base.sign.overlay; + point = base.sign.point; + description = base.description; + paint = base.sign.paint; + postPaint = base.postPaint; - public SendBigPostBasesMessage(){} - - public SendBigPostBasesMessage(BigPostPostTile tile, BigBaseInfo base) { - tile.markDirty(); - this.pos = tile.toPos(); - this.base = ""+base.sign.base; - baserot = base.sign.rotation; - flip = base.sign.flip; - overlay = ""+base.sign.overlay; - point = base.sign.point; - description = base.description; - paint = base.sign.paint; - postPaint = base.postPaint; - - if(base.equals(tile.getPaintObject())){ - paintObjectIndex = 1; - }else if(base.sign.equals(tile.getPaintObject())){ - paintObjectIndex = 2; - }else{ - paintObjectIndex = 0; - } - } + if (base.equals(tile.getPaintObject())) { + paintObjectIndex = 1; + } else if (base.sign.equals(tile.getPaintObject())) { + paintObjectIndex = 2; + } else { + paintObjectIndex = 0; + } + } - @Override - public void toBytes(ByteBuf buf) { - pos.toBytes(buf); - ByteBufUtils.writeUTF8String(buf, base); - buf.writeInt(baserot); - buf.writeBoolean(flip); - ByteBufUtils.writeUTF8String(buf, overlay); - buf.writeBoolean(point); - buf.writeInt(description.length); - for(String now: description){ - ByteBufUtils.writeUTF8String(buf, now); - } - ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(paint)); - ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(postPaint)); - buf.writeByte(paintObjectIndex); - } + @Override + public void toBytes(ByteBuf buf) { + pos.toBytes(buf); + ByteBufUtils.writeUTF8String(buf, base); + buf.writeInt(baserot); + buf.writeBoolean(flip); + ByteBufUtils.writeUTF8String(buf, overlay); + buf.writeBoolean(point); + buf.writeInt(description.length); + for (String now : description) { + ByteBufUtils.writeUTF8String(buf, now); + } + ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(paint)); + ByteBufUtils.writeUTF8String(buf, SuperPostPostTile.locToString(postPaint)); + buf.writeByte(paintObjectIndex); + } - @Override - public void fromBytes(ByteBuf buf) { - pos = MyBlockPos.fromBytes(buf); - base = ByteBufUtils.readUTF8String(buf); - baserot = buf.readInt(); - flip = buf.readBoolean(); - overlay = ByteBufUtils.readUTF8String(buf); - point = buf.readBoolean(); - description = new String[buf.readInt()]; - for(int i=0; i=1){ - sc2 = 1; - } - double lurch = (tilebases.sign.flip?-0.1:0.1)-fontrenderer.getStringWidth(s)*sc*sc2/2; - double alpha = Math.atan(lurch*16/3.001); - double d = Math.sqrt(Math.pow(3.001/16, 2)+Math.pow(lurch, 2)); - double beta = alpha + rotation; - double dx = Math.sin(beta)*d; - double dz = -Math.cos(beta)*d; - GL11.glPushMatrix(); - GL11.glTranslated(dx, 0, dz); - GL11.glScaled(sc, sc, sc); - GL11.glRotated(-Math.toDegrees(rotation), 0, 1, 0); - GL11.glScaled(sc2, sc2, sc2); - fontrenderer.drawString(s, 0, 0, color); - GL11.glPopMatrix(); - } - } + GL11.glTranslated(0, 1.12, 0); + GL11.glRotated(180, 0, 0, 1); + GL11.glRotated(180, 0, 1, 0); + double sc = 0.013d; + + int color = 0; + + if (!tile.isItem) { + if (tilebases.sign.base != null && !tilebases.sign.base.getName() + .equals("null") + && !tilebases.sign.base.getName() + .equals("")) { + GL11.glTranslated(0, 0.1, 0); + for (String s : tilebases.description) { + GL11.glTranslated(0, 0.165, 0); + if (s == null) { + continue; + } + double sc2 = 90d / fontrenderer.getStringWidth(s); + if (sc2 >= 1) { + sc2 = 1; + } + double lurch = (tilebases.sign.flip ? -0.1 : 0.1) - fontrenderer.getStringWidth(s) * sc * sc2 / 2; + double alpha = Math.atan(lurch * 16 / 3.001); + double d = Math.sqrt(Math.pow(3.001 / 16, 2) + Math.pow(lurch, 2)); + double beta = alpha + rotation; + double dx = Math.sin(beta) * d; + double dz = -Math.cos(beta) * d; + GL11.glPushMatrix(); + GL11.glTranslated(dx, 0, dz); + GL11.glScaled(sc, sc, sc); + GL11.glRotated(-Math.toDegrees(rotation), 0, 1, 0); + GL11.glScaled(sc2, sc2, sc2); + fontrenderer.drawString(s, 0, 0, color); + GL11.glPopMatrix(); + } + } } GL11.glPopMatrix(); GL11.glPopMatrix(); - } + } } diff --git a/src/main/java/gollorum/signpost/render/BlockItemRenderer.java b/src/main/java/gollorum/signpost/render/BlockItemRenderer.java index 827a8132..c32c4fff 100644 --- a/src/main/java/gollorum/signpost/render/BlockItemRenderer.java +++ b/src/main/java/gollorum/signpost/render/BlockItemRenderer.java @@ -1,40 +1,38 @@ package gollorum.signpost.render; -import org.lwjgl.opengl.GL11; - import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.client.IItemRenderer; -import net.minecraftforge.client.IItemRenderer.ItemRenderType; -import net.minecraftforge.client.IItemRenderer.ItemRendererHelper; - -public class BlockItemRenderer implements IItemRenderer{ - - private final TileEntity tile; - private final TileEntitySpecialRenderer renderer; - - public BlockItemRenderer(TileEntity tile, TileEntitySpecialRenderer renderer) { - this.tile = tile; - this.renderer = renderer; - } - - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - return true; - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - return true; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - GL11.glPushMatrix(); - TileEntityRendererDispatcher.instance.renderTileEntityAt(tile, 0, 0, 0, 0); - GL11.glPopMatrix(); - } + +import org.lwjgl.opengl.GL11; + +public class BlockItemRenderer implements IItemRenderer { + + private final TileEntity tile; + private final TileEntitySpecialRenderer renderer; + + public BlockItemRenderer(TileEntity tile, TileEntitySpecialRenderer renderer) { + this.tile = tile; + this.renderer = renderer; + } + + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + GL11.glPushMatrix(); + TileEntityRendererDispatcher.instance.renderTileEntityAt(tile, 0, 0, 0, 0); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/gollorum/signpost/render/Board.java b/src/main/java/gollorum/signpost/render/Board.java index 99e21bf6..d49641ea 100644 --- a/src/main/java/gollorum/signpost/render/Board.java +++ b/src/main/java/gollorum/signpost/render/Board.java @@ -3,65 +3,65 @@ import net.minecraft.client.model.ModelRenderer; public class Board { - - private ModelRenderer baseNotFlipped; - private ModelRenderer baseFlipped; - public Board(ModelPost modelPost, int heightOffset) { - - //Not flipped - ModelRenderer ltnf = new ModelRenderer(modelPost, 12, 9); - ltnf.addBox(-9, heightOffset+2f, 2, 1, 4, 1, 0f); - baseNotFlipped = new ModelRenderer(modelPost, -1, 0); - baseNotFlipped.addBox(-8, heightOffset+1, 2, 20, 6, 1, 0.0F); - baseNotFlipped.addChild(ltnf); - - int i = 2; - while(i<4){ - ModelRenderer now = new ModelRenderer(modelPost, 6*i-12 , 7+i); - now.addBox(8+i*2, heightOffset+i, 2, 2, 8-2*i, 1, 0f); - now.rotationPointX += 18+i*4; - now.rotationPointZ += 5f; - now.rotateAngleY = (float) Math.PI; - baseNotFlipped.addChild(now); - i++; - } - - //flipped - ModelRenderer ltf = new ModelRenderer(modelPost, 12, 9); - ltf.addBox(8, heightOffset+2f, 2, 1, 4, 1, 0f); - baseFlipped = new ModelRenderer(modelPost, -1, 0); - baseFlipped.addBox(-12, heightOffset+1, 2, 20, 6, 1, 0.0F); - baseFlipped.addChild(ltf); - - i = 2; - while(i<4){ - ModelRenderer now = new ModelRenderer(modelPost, 6*i-12 , 7+i); - now.addBox(-10-i*2, heightOffset+i, 2, 2, 8-2*i, 1, 0f); - baseFlipped.addChild(now); - i++; - } - } + private ModelRenderer baseNotFlipped; + private ModelRenderer baseFlipped; - public void render(float f5, boolean flipped) { - if(!flipped){ - baseFlipped.render(f5); - }else{ - baseNotFlipped.render(f5); - } - } + public Board(ModelPost modelPost, int heightOffset) { - public void setRotation(float rot){ - baseNotFlipped.rotateAngleY = baseFlipped.rotateAngleY = (float) Math.toRadians(rot); + // Not flipped + ModelRenderer ltnf = new ModelRenderer(modelPost, 12, 9); + ltnf.addBox(-9, heightOffset + 2f, 2, 1, 4, 1, 0f); + baseNotFlipped = new ModelRenderer(modelPost, -1, 0); + baseNotFlipped.addBox(-8, heightOffset + 1, 2, 20, 6, 1, 0.0F); + baseNotFlipped.addChild(ltnf); + + int i = 2; + while (i < 4) { + ModelRenderer now = new ModelRenderer(modelPost, 6 * i - 12, 7 + i); + now.addBox(8 + i * 2, heightOffset + i, 2, 2, 8 - 2 * i, 1, 0f); + now.rotationPointX += 18 + i * 4; + now.rotationPointZ += 5f; + now.rotateAngleY = (float) Math.PI; + baseNotFlipped.addChild(now); + i++; + } + + // flipped + ModelRenderer ltf = new ModelRenderer(modelPost, 12, 9); + ltf.addBox(8, heightOffset + 2f, 2, 1, 4, 1, 0f); + baseFlipped = new ModelRenderer(modelPost, -1, 0); + baseFlipped.addBox(-12, heightOffset + 1, 2, 20, 6, 1, 0.0F); + baseFlipped.addChild(ltf); + + i = 2; + while (i < 4) { + ModelRenderer now = new ModelRenderer(modelPost, 6 * i - 12, 7 + i); + now.addBox(-10 - i * 2, heightOffset + i, 2, 2, 8 - 2 * i, 1, 0f); + baseFlipped.addChild(now); + i++; + } } - - public void setTextureOffset(int u, int v){ - baseNotFlipped.setTextureOffset(u, v); - baseFlipped.setTextureOffset(u, v); + + public void render(float f5, boolean flipped) { + if (!flipped) { + baseFlipped.render(f5); + } else { + baseNotFlipped.render(f5); + } } - - public void setTextureSize(int u, int v){ - baseNotFlipped.setTextureSize(u, v); - baseFlipped.setTextureSize(u, v); + + public void setRotation(float rot) { + baseNotFlipped.rotateAngleY = baseFlipped.rotateAngleY = (float) Math.toRadians(rot); + } + + public void setTextureOffset(int u, int v) { + baseNotFlipped.setTextureOffset(u, v); + baseFlipped.setTextureOffset(u, v); + } + + public void setTextureSize(int u, int v) { + baseNotFlipped.setTextureSize(u, v); + baseFlipped.setTextureSize(u, v); } } diff --git a/src/main/java/gollorum/signpost/render/ModelBigPost.java b/src/main/java/gollorum/signpost/render/ModelBigPost.java index ad01c37c..d90a8309 100644 --- a/src/main/java/gollorum/signpost/render/ModelBigPost.java +++ b/src/main/java/gollorum/signpost/render/ModelBigPost.java @@ -1,53 +1,55 @@ package gollorum.signpost.render; +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.util.ResourceLocation; + import org.lwjgl.opengl.GL11; import gollorum.signpost.blocks.BigPostPost; import gollorum.signpost.blocks.tiles.BigPostPostTile; import gollorum.signpost.util.BigBaseInfo; -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.model.ModelRenderer; -import net.minecraft.util.ResourceLocation; public class ModelBigPost extends ModelBase { - public ModelRenderer post; - - public ModelRenderer waystone; - public static final ResourceLocation BASETEXTURE = new ResourceLocation("minecraft:textures/blocks/stone.png"); - // public static final ResourceLocation BASETEXTURE = new ResourceLocation("signpost:textures/blocks/base.png"); - - public ModelBigPost() { - - textureWidth = 16; - textureHeight = 16; - - post = new ModelRenderer(this, 0, -4); - post.addBox(-2F, 0F, -2F, 4, 16, 4, 0F); - - waystone = new ModelRenderer(this, 4, 4); - waystone.addBox(-4f, 0f, -4f, 8, 8, 8); - } - - public void render(BigPostRenderer postRenderer, float f1, float f5, BigBaseInfo tilebases, BigPostPostTile tile, double rotation) { - if (tile.isItem) { - postRenderer.setTexture(((BigPostPost) tile.blockType).type.resLocMain); - } else { - if (tile.isAwaitingPaint() && tile.getPaintObject() instanceof BigBaseInfo) { - postRenderer.setTexture(tilebases.POST_PAINT); - } else { - postRenderer.setTexture(tilebases.postPaint); - } - } - GL11.glPushMatrix(); - GL11.glRotated(180, 1, 0, 0); - GL11.glTranslated(0, -1, 0); - post.render(f5); - GL11.glPopMatrix(); - if (tile.isWaystone) { - postRenderer.setTexture(BASETEXTURE); - waystone.render(f5); - } - } + public ModelRenderer post; + + public ModelRenderer waystone; + public static final ResourceLocation BASETEXTURE = new ResourceLocation("minecraft:textures/blocks/stone.png"); + // public static final ResourceLocation BASETEXTURE = new ResourceLocation("signpost:textures/blocks/base.png"); + + public ModelBigPost() { + + textureWidth = 16; + textureHeight = 16; + + post = new ModelRenderer(this, 0, -4); + post.addBox(-2F, 0F, -2F, 4, 16, 4, 0F); + + waystone = new ModelRenderer(this, 4, 4); + waystone.addBox(-4f, 0f, -4f, 8, 8, 8); + } + + public void render(BigPostRenderer postRenderer, float f1, float f5, BigBaseInfo tilebases, BigPostPostTile tile, + double rotation) { + if (tile.isItem) { + postRenderer.setTexture(((BigPostPost) tile.blockType).type.resLocMain); + } else { + if (tile.isAwaitingPaint() && tile.getPaintObject() instanceof BigBaseInfo) { + postRenderer.setTexture(tilebases.POST_PAINT); + } else { + postRenderer.setTexture(tilebases.postPaint); + } + } + GL11.glPushMatrix(); + GL11.glRotated(180, 1, 0, 0); + GL11.glTranslated(0, -1, 0); + post.render(f5); + GL11.glPopMatrix(); + if (tile.isWaystone) { + postRenderer.setTexture(BASETEXTURE); + waystone.render(f5); + } + } } diff --git a/src/main/java/gollorum/signpost/render/ModelBigSign.java b/src/main/java/gollorum/signpost/render/ModelBigSign.java index 5c04fd2b..252bcbea 100644 --- a/src/main/java/gollorum/signpost/render/ModelBigSign.java +++ b/src/main/java/gollorum/signpost/render/ModelBigSign.java @@ -1,56 +1,59 @@ package gollorum.signpost.render; +import net.minecraft.client.model.ModelBase; + import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import gollorum.signpost.blocks.tiles.BigPostPostTile; import gollorum.signpost.util.BigBaseInfo; -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.model.ModelRenderer; @SideOnly(Side.CLIENT) public class ModelBigSign extends ModelBase { - - public BigBoard board; - private static final String __OBFID = "CL_00000854"; - - public ModelBigSign(boolean is16) { - - if(is16){ - textureWidth = 16; - textureHeight = 16; - }else{ - textureWidth = 16; - textureHeight = 32; - } - - board = new BigBoard(this); - - } - - public void render(BigPostRenderer postRenderer, float f1, float f5, BigBaseInfo tilebases, BigPostPostTile tile, double rotation) { - super.render(null, 0, f1, 0, 0, 0, f5); - if (tile.isItem || (tilebases.sign.base != null&&!tilebases.sign.base.getName().equals("null")&&!tilebases.sign.base.getName().equals(""))) { - GL11.glPushMatrix(); - GL11.glRotated(180, 0, 0, 1); - GL11.glTranslated(0, -1, 0); - GL11.glRotated(-Math.toDegrees(rotation), 0, 1, 0); - board.render(f5, tile.isItem ? false : tilebases.sign.flip); - GL11.glPopMatrix(); - } - } - - public void renderOverlay(BigBaseInfo tilebases, float f5, double rotation) { - GL11.glPushMatrix(); - GL11.glRotated(Math.toDegrees(rotation), 0, 1, 0); - GL11.glTranslated(0, 0.25, 2.5/16.0); - GL11.glScaled(1.01, 1.01, 1.1); - GL11.glTranslated(0, -0.75, -2.5/16.0); - GL11.glRotated(180, 0, 0, 1); - GL11.glTranslated(0, -1.5, 0); - board.render(f5, tilebases.sign.flip); - GL11.glPopMatrix(); - } - -} \ No newline at end of file + + public BigBoard board; + + public ModelBigSign(boolean is16) { + + if (is16) { + textureWidth = 16; + textureHeight = 16; + } else { + textureWidth = 16; + textureHeight = 32; + } + + board = new BigBoard(this); + + } + + public void render(BigPostRenderer postRenderer, float f1, float f5, BigBaseInfo tilebases, BigPostPostTile tile, + double rotation) { + super.render(null, 0, f1, 0, 0, 0, f5); + if (tile.isItem || (tilebases.sign.base != null && !tilebases.sign.base.getName() + .equals("null") + && !tilebases.sign.base.getName() + .equals(""))) { + GL11.glPushMatrix(); + GL11.glRotated(180, 0, 0, 1); + GL11.glTranslated(0, -1, 0); + GL11.glRotated(-Math.toDegrees(rotation), 0, 1, 0); + board.render(f5, tile.isItem ? false : tilebases.sign.flip); + GL11.glPopMatrix(); + } + } + + public void renderOverlay(BigBaseInfo tilebases, float f5, double rotation) { + GL11.glPushMatrix(); + GL11.glRotated(Math.toDegrees(rotation), 0, 1, 0); + GL11.glTranslated(0, 0.25, 2.5 / 16.0); + GL11.glScaled(1.01, 1.01, 1.1); + GL11.glTranslated(0, -0.75, -2.5 / 16.0); + GL11.glRotated(180, 0, 0, 1); + GL11.glTranslated(0, -1.5, 0); + board.render(f5, tilebases.sign.flip); + GL11.glPopMatrix(); + } + +} diff --git a/src/main/java/gollorum/signpost/render/ModelPost.java b/src/main/java/gollorum/signpost/render/ModelPost.java index 22cff9a4..b655db01 100644 --- a/src/main/java/gollorum/signpost/render/ModelPost.java +++ b/src/main/java/gollorum/signpost/render/ModelPost.java @@ -1,5 +1,9 @@ package gollorum.signpost.render; +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.model.ModelRenderer; +import net.minecraft.util.ResourceLocation; + import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; @@ -7,132 +11,130 @@ import gollorum.signpost.blocks.PostPost; import gollorum.signpost.blocks.tiles.PostPostTile; import gollorum.signpost.util.DoubleBaseInfo; -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.model.ModelRenderer; -import net.minecraft.util.ResourceLocation; @SideOnly(Side.CLIENT) public class ModelPost extends ModelBase { - public Board board1; - public Board board2; - public ModelRenderer post; - public ModelRenderer waystone; - public static final ResourceLocation BASETEXTURE = new ResourceLocation("minecraft:textures/blocks/stone.png"); -// public static final ResourceLocation BASETEXTURE = new ResourceLocation("signpost:textures/blocks/base.png"); - private static final String __OBFID = "CL_00000854"; - - public ModelPost() { - - textureWidth = 16; - textureHeight = 16; - - board1 = new Board(this, 8); - board2 = new Board(this, 0); - - post = new ModelRenderer(this, 0, -4); - post.addBox(-2F, 0F, -2F, 4, 16, 4, 0F); - - waystone = new ModelRenderer(this, 4, 4); - waystone.addBox(-4f, 0f, -4f, 8, 8, 8); - } - - public void render(PostRenderer postRenderer, float f1, float f5, DoubleBaseInfo tilebases, PostPostTile tile, double rotation1, double rotation2) { - super.render(null, 0, f1, 0, 0, 0, f5); - - //Post - - if(tile.isItem){ - postRenderer.setTexture(((PostPost)tile.blockType).type.resLocMain); - }else{ - if(tile.isAwaitingPaint() && tile.getPaintObject() instanceof DoubleBaseInfo){ - postRenderer.setTexture(tilebases.POST_PAINT); - }else{ - postRenderer.setTexture(tilebases.postPaint); - } - } - - GL11.glPushMatrix(); - GL11.glTranslated(0, 1, 0); - GL11.glRotated(180, 1, 0, 0); - post.render(f5); - GL11.glPopMatrix(); - - //Waystone - - if(!tile.isItem){ - if(tile.isWaystone){ - postRenderer.setTexture(BASETEXTURE); - waystone.render(f5); - } - } - - //Signs - - ResourceLocation mainLoc = tile.type.texture; - if (tile.isItem || tilebases.sign1.isValid()) { - GL11.glPushMatrix(); - GL11.glRotated(180, 0, 0, 1); - GL11.glTranslated(0, -1.5, 0); - GL11.glRotated(-Math.toDegrees(rotation1), 0, 1, 0); - if(tile.isItem){ - postRenderer.setTexture(tile.type.texture); - board1.render(f5, false); - }else if(tile.isAwaitingPaint() && tilebases.sign1.equals(tile.getPaintObject())){ - postRenderer.setTexture(tilebases.sign1.SIGN_PAINT); - board1.render(f5, tilebases.sign1.flip); - }else if(tilebases.sign1.paint!=null){ - postRenderer.setTexture(tilebases.sign1.paint); - board1.render(f5, tilebases.sign1.flip); - }else{ - postRenderer.setTexture(mainLoc); - board1.render(f5, tilebases.sign1.flip); - } - GL11.glPopMatrix(); - } - if (tile.isItem || tilebases.sign2.isValid()) { - GL11.glPushMatrix(); - GL11.glRotated(180, 0, 0, 1); - GL11.glTranslated(0, -0.5, 0); - GL11.glRotated(-Math.toDegrees(rotation2), 0, 1, 0); - if(tile.isItem){ - postRenderer.setTexture(tile.type.texture); - board2.render(f5, false); - }else if(tile.isAwaitingPaint() && tilebases.sign2.equals(tile.getPaintObject())){ - postRenderer.setTexture(tilebases.sign2.SIGN_PAINT); - board2.render(f5, tilebases.sign2.flip); - }else if(tilebases.sign2.paint!=null){ - postRenderer.setTexture(tilebases.sign2.paint); - board2.render(f5, tilebases.sign2.flip); - }else{ - postRenderer.setTexture(mainLoc); - board2.render(f5, tilebases.sign2.flip); - } - GL11.glPopMatrix(); - } - } - - public void renderOverlay1(DoubleBaseInfo tilebases, float f5, double rotation) { - GL11.glPushMatrix(); - GL11.glRotated(Math.toDegrees(rotation), 0, 1, 0); - GL11.glTranslated(0, 0.75, 2.5/16.0); - GL11.glScaled(1.01, 1.01, 1.1); - GL11.glTranslated(0, -0.75, -2.5/16.0); - GL11.glRotated(180, 0, 0, 1); - GL11.glTranslated(0, -1.5, 0); - board1.render(f5, tilebases.sign1.flip); - GL11.glPopMatrix(); - } - - public void renderOverlay2(DoubleBaseInfo tilebases, float f5, double rotation) { - GL11.glPushMatrix(); - GL11.glRotated(Math.toDegrees(rotation), 0, 1, 0); - GL11.glTranslated(0, 0.25, 2.5/16.0); - GL11.glScaled(1.01, 1.01, 1.1); - GL11.glTranslated(0, -0.25, -2.5/16.0); - GL11.glRotated(180, 0, 0, 1); - GL11.glTranslated(0, -0.5, 0); - board2.render(f5, tilebases.sign2.flip); - GL11.glPopMatrix(); - } - -} \ No newline at end of file + + public Board board1; + public Board board2; + public ModelRenderer post; + public ModelRenderer waystone; + public static final ResourceLocation BASETEXTURE = new ResourceLocation("minecraft:textures/blocks/stone.png"); + // public static final ResourceLocation BASETEXTURE = new ResourceLocation("signpost:textures/blocks/base.png"); + + public ModelPost() { + + textureWidth = 16; + textureHeight = 16; + + board1 = new Board(this, 8); + board2 = new Board(this, 0); + + post = new ModelRenderer(this, 0, -4); + post.addBox(-2F, 0F, -2F, 4, 16, 4, 0F); + + waystone = new ModelRenderer(this, 4, 4); + waystone.addBox(-4f, 0f, -4f, 8, 8, 8); + } + + public void render(PostRenderer postRenderer, float f1, float f5, DoubleBaseInfo tilebases, PostPostTile tile, + double rotation1, double rotation2) { + super.render(null, 0, f1, 0, 0, 0, f5); + + // Post + + if (tile.isItem) { + postRenderer.setTexture(((PostPost) tile.blockType).type.resLocMain); + } else { + if (tile.isAwaitingPaint() && tile.getPaintObject() instanceof DoubleBaseInfo) { + postRenderer.setTexture(tilebases.POST_PAINT); + } else { + postRenderer.setTexture(tilebases.postPaint); + } + } + + GL11.glPushMatrix(); + GL11.glTranslated(0, 1, 0); + GL11.glRotated(180, 1, 0, 0); + post.render(f5); + GL11.glPopMatrix(); + + // Waystone + + if (!tile.isItem) { + if (tile.isWaystone) { + postRenderer.setTexture(BASETEXTURE); + waystone.render(f5); + } + } + + // Signs + + ResourceLocation mainLoc = tile.type.texture; + if (tile.isItem || tilebases.sign1.isValid()) { + GL11.glPushMatrix(); + GL11.glRotated(180, 0, 0, 1); + GL11.glTranslated(0, -1.5, 0); + GL11.glRotated(-Math.toDegrees(rotation1), 0, 1, 0); + if (tile.isItem) { + postRenderer.setTexture(tile.type.texture); + board1.render(f5, false); + } else if (tile.isAwaitingPaint() && tilebases.sign1.equals(tile.getPaintObject())) { + postRenderer.setTexture(tilebases.sign1.SIGN_PAINT); + board1.render(f5, tilebases.sign1.flip); + } else if (tilebases.sign1.paint != null) { + postRenderer.setTexture(tilebases.sign1.paint); + board1.render(f5, tilebases.sign1.flip); + } else { + postRenderer.setTexture(mainLoc); + board1.render(f5, tilebases.sign1.flip); + } + GL11.glPopMatrix(); + } + if (tile.isItem || tilebases.sign2.isValid()) { + GL11.glPushMatrix(); + GL11.glRotated(180, 0, 0, 1); + GL11.glTranslated(0, -0.5, 0); + GL11.glRotated(-Math.toDegrees(rotation2), 0, 1, 0); + if (tile.isItem) { + postRenderer.setTexture(tile.type.texture); + board2.render(f5, false); + } else if (tile.isAwaitingPaint() && tilebases.sign2.equals(tile.getPaintObject())) { + postRenderer.setTexture(tilebases.sign2.SIGN_PAINT); + board2.render(f5, tilebases.sign2.flip); + } else if (tilebases.sign2.paint != null) { + postRenderer.setTexture(tilebases.sign2.paint); + board2.render(f5, tilebases.sign2.flip); + } else { + postRenderer.setTexture(mainLoc); + board2.render(f5, tilebases.sign2.flip); + } + GL11.glPopMatrix(); + } + } + + public void renderOverlay1(DoubleBaseInfo tilebases, float f5, double rotation) { + GL11.glPushMatrix(); + GL11.glRotated(Math.toDegrees(rotation), 0, 1, 0); + GL11.glTranslated(0, 0.75, 2.5 / 16.0); + GL11.glScaled(1.01, 1.01, 1.1); + GL11.glTranslated(0, -0.75, -2.5 / 16.0); + GL11.glRotated(180, 0, 0, 1); + GL11.glTranslated(0, -1.5, 0); + board1.render(f5, tilebases.sign1.flip); + GL11.glPopMatrix(); + } + + public void renderOverlay2(DoubleBaseInfo tilebases, float f5, double rotation) { + GL11.glPushMatrix(); + GL11.glRotated(Math.toDegrees(rotation), 0, 1, 0); + GL11.glTranslated(0, 0.25, 2.5 / 16.0); + GL11.glScaled(1.01, 1.01, 1.1); + GL11.glTranslated(0, -0.25, -2.5 / 16.0); + GL11.glRotated(180, 0, 0, 1); + GL11.glTranslated(0, -0.5, 0); + board2.render(f5, tilebases.sign2.flip); + GL11.glPopMatrix(); + } + +} diff --git a/src/main/java/gollorum/signpost/render/PostRenderer.java b/src/main/java/gollorum/signpost/render/PostRenderer.java index 24d65334..976b7835 100644 --- a/src/main/java/gollorum/signpost/render/PostRenderer.java +++ b/src/main/java/gollorum/signpost/render/PostRenderer.java @@ -1,125 +1,135 @@ package gollorum.signpost.render; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ResourceLocation; + import org.lwjgl.opengl.GL11; -import gollorum.signpost.Signpost; +import gollorum.signpost.Tags; import gollorum.signpost.blocks.PostPost.PostType; import gollorum.signpost.blocks.tiles.PostPostTile; import gollorum.signpost.util.DoubleBaseInfo; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ResourceLocation; -public class PostRenderer extends TileEntitySpecialRenderer{ - - private static final ModelPost model = new ModelPost(); - - public PostRenderer(){} - - void setTexture(ResourceLocation loc){ - try{ - bindTexture(loc); - }catch(Exception e){ - if(loc==null){ - }else if(loc.equals(new ResourceLocation("signpost:textures/blocks/sign.png"))){ - bindTexture(new ResourceLocation("signpost:textures/blocks/sign_oak.png")); - }else if(loc.equals(new ResourceLocation("signpost:textures/blocks/bigsign.png"))){ - bindTexture(new ResourceLocation("signpost:textures/blocks/bigsign_oak.png")); - } - } - } - - @Override - public void renderTileEntityAt(TileEntity ti, double x, double y, double z, float scale) { - PostPostTile tile = (PostPostTile)ti; - DoubleBaseInfo tilebases = tile.bases; - double rotation1 = 0; - double rotation2 = 0; - if(tilebases==null&&!tile.isItem){ - tilebases = tile.getBases(); - } - if(!tile.isItem){ - rotation1 = tilebases.sign1.calcRot(tile.xCoord, tile.zCoord); - rotation2 = tilebases.sign2.calcRot(tile.xCoord, tile.zCoord); - } - GL11.glPushMatrix(); - GL11.glTranslated(x+0.5, y, z+0.5); - if(tile.type == null) this.setTexture(PostType.OAK.texture); - else this.setTexture(tile.type.texture); - model.render(this, 0.1f, 0.0625f, tilebases, tile, rotation1, rotation2); - - //Overlays - if(!tile.isItem){ - if(tilebases.sign1.isValid() && tilebases.sign1.overlay!=null){ - setTexture(new ResourceLocation(Signpost.MODID + ":textures/blocks/sign_overlay_"+tilebases.sign1.overlay.texture+".png")); - model.renderOverlay1(tilebases, 0.0625f, rotation1); - } - if(tilebases.sign2.isValid() && tilebases.sign2.overlay!=null){ - setTexture(new ResourceLocation(Signpost.MODID + ":textures/blocks/sign_overlay_"+tilebases.sign2.overlay.texture+".png")); - model.renderOverlay2(tilebases, 0.0625f, rotation2); - } - } - +public class PostRenderer extends TileEntitySpecialRenderer { + + private static final ModelPost model = new ModelPost(); + + public PostRenderer() {} + + void setTexture(ResourceLocation loc) { + try { + bindTexture(loc); + } catch (Exception e) { + if (loc == null) {} else if (loc.equals(new ResourceLocation("signpost:textures/blocks/sign.png"))) { + bindTexture(new ResourceLocation("signpost:textures/blocks/sign_oak.png")); + } else if (loc.equals(new ResourceLocation("signpost:textures/blocks/bigsign.png"))) { + bindTexture(new ResourceLocation("signpost:textures/blocks/bigsign_oak.png")); + } + } + } + + @Override + public void renderTileEntityAt(TileEntity ti, double x, double y, double z, float scale) { + PostPostTile tile = (PostPostTile) ti; + DoubleBaseInfo tilebases = tile.bases; + double rotation1 = 0; + double rotation2 = 0; + if (tilebases == null && !tile.isItem) { + tilebases = tile.getBases(); + } + if (!tile.isItem) { + rotation1 = tilebases.sign1.calcRot(tile.xCoord, tile.zCoord); + rotation2 = tilebases.sign2.calcRot(tile.xCoord, tile.zCoord); + } + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y, z + 0.5); + if (tile.type == null) this.setTexture(PostType.OAK.texture); + else this.setTexture(tile.type.texture); + model.render(this, 0.1f, 0.0625f, tilebases, tile, rotation1, rotation2); + + // Overlays + if (!tile.isItem) { + if (tilebases.sign1.isValid() && tilebases.sign1.overlay != null) { + setTexture( + new ResourceLocation( + Tags.MODID + ":textures/blocks/sign_overlay_" + tilebases.sign1.overlay.texture + ".png")); + model.renderOverlay1(tilebases, 0.0625f, rotation1); + } + if (tilebases.sign2.isValid() && tilebases.sign2.overlay != null) { + setTexture( + new ResourceLocation( + Tags.MODID + ":textures/blocks/sign_overlay_" + tilebases.sign2.overlay.texture + ".png")); + model.renderOverlay2(tilebases, 0.0625f, rotation2); + } + } + FontRenderer fontrenderer = this.func_147498_b(); GL11.glPushMatrix(); - GL11.glTranslated(0, 0.8d, 0); - GL11.glRotated(180, 0, 0, 1); - GL11.glRotated(180, 0, 1, 0); - double sc = 0.013d; - double ys = 1.3d*sc; - - int color = 0; -// int color = (1<<16) + (1<<8); - - if(!tile.isItem){ - if(tilebases.sign1.base!=null&&!tilebases.sign1.base.getName().equals("null")&&!tilebases.sign1.base.getName().equals("")){ - String s = tilebases.sign1.base.getName(); - double sc2 = 100d/fontrenderer.getStringWidth(s); - if(sc2>=1){ - sc2 = 1; - } - double lurch = (tilebases.sign1.flip?-0.2:0.2)-fontrenderer.getStringWidth(s)*sc*sc2/2; - double alpha = Math.atan(lurch*16/3.001); - double d = Math.sqrt(Math.pow(3.001/16, 2)+Math.pow(lurch, 2)); - double beta = alpha + rotation1; - double dx = Math.sin(beta)*d; - double dz = -Math.cos(beta)*d; - GL11.glPushMatrix(); - GL11.glTranslated(dx, 0, dz); - GL11.glScaled(sc, ys, sc); - GL11.glRotated(-Math.toDegrees(rotation1), 0, 1, 0); - GL11.glScaled(sc2, sc2, sc2); + GL11.glTranslated(0, 0.8d, 0); + GL11.glRotated(180, 0, 0, 1); + GL11.glRotated(180, 0, 1, 0); + double sc = 0.013d; + double ys = 1.3d * sc; + + int color = 0; + // int color = (1<<16) + (1<<8); + + if (!tile.isItem) { + if (tilebases.sign1.base != null && !tilebases.sign1.base.getName() + .equals("null") + && !tilebases.sign1.base.getName() + .equals("")) { + String s = tilebases.sign1.base.getName(); + double sc2 = 100d / fontrenderer.getStringWidth(s); + if (sc2 >= 1) { + sc2 = 1; + } + double lurch = (tilebases.sign1.flip ? -0.2 : 0.2) - fontrenderer.getStringWidth(s) * sc * sc2 / 2; + double alpha = Math.atan(lurch * 16 / 3.001); + double d = Math.sqrt(Math.pow(3.001 / 16, 2) + Math.pow(lurch, 2)); + double beta = alpha + rotation1; + double dx = Math.sin(beta) * d; + double dz = -Math.cos(beta) * d; + GL11.glPushMatrix(); + GL11.glTranslated(dx, 0, dz); + GL11.glScaled(sc, ys, sc); + GL11.glRotated(-Math.toDegrees(rotation1), 0, 1, 0); + GL11.glScaled(sc2, sc2, sc2); fontrenderer.drawString(s, 0, 0, color); GL11.glPopMatrix(); - } - - if(tilebases.sign2.base!=null&&!tilebases.sign2.base.getName().equals("null")&&!tilebases.sign2.base.getName().equals("")){ - GL11.glTranslated(0, 0.5d, 0); - String s = tilebases.sign2.base.getName(); - double sc2 = 100d/fontrenderer.getStringWidth(s); - if(sc2>=1){ - sc2 = 1; - } - double lurch = (tilebases.sign2.flip?-0.2:0.2)-fontrenderer.getStringWidth(s)*sc*sc2/2; - double alpha = Math.atan(lurch*16/3.001); - double d = Math.sqrt(Math.pow(3.001/16, 2)+Math.pow(lurch, 2)); - double beta = alpha + rotation2; - double dx = Math.sin(beta)*d; - double dz = -Math.cos(beta)*d; - GL11.glPushMatrix(); - GL11.glTranslated(dx, 0, dz); - GL11.glScaled(sc, ys, sc); - GL11.glRotated(-Math.toDegrees(rotation2), 0, 1, 0); - GL11.glScaled(sc2, sc2, sc2); + } + + if (tilebases.sign2.base != null && !tilebases.sign2.base.getName() + .equals("null") + && !tilebases.sign2.base.getName() + .equals("")) { + GL11.glTranslated(0, 0.5d, 0); + String s = tilebases.sign2.base.getName(); + double sc2 = 100d / fontrenderer.getStringWidth(s); + if (sc2 >= 1) { + sc2 = 1; + } + double lurch = (tilebases.sign2.flip ? -0.2 : 0.2) - fontrenderer.getStringWidth(s) * sc * sc2 / 2; + double alpha = Math.atan(lurch * 16 / 3.001); + double d = Math.sqrt(Math.pow(3.001 / 16, 2) + Math.pow(lurch, 2)); + double beta = alpha + rotation2; + double dx = Math.sin(beta) * d; + double dz = -Math.cos(beta) * d; + GL11.glPushMatrix(); + GL11.glTranslated(dx, 0, dz); + GL11.glScaled(sc, ys, sc); + GL11.glRotated(-Math.toDegrees(rotation2), 0, 1, 0); + GL11.glScaled(sc2, sc2, sc2); fontrenderer.drawString(s, 0, 0, color); GL11.glPopMatrix(); - } + } } GL11.glPopMatrix(); GL11.glPopMatrix(); - } + } } diff --git a/src/main/java/gollorum/signpost/util/BaseInfo.java b/src/main/java/gollorum/signpost/util/BaseInfo.java index bd0963bd..1e870ec5 100644 --- a/src/main/java/gollorum/signpost/util/BaseInfo.java +++ b/src/main/java/gollorum/signpost/util/BaseInfo.java @@ -1,168 +1,173 @@ package gollorum.signpost.util; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.network.ByteBufUtils; -import io.netty.buffer.ByteBuf; +import java.util.Objects; +import java.util.UUID; + import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import java.util.Objects; -import java.util.UUID; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.network.ByteBufUtils; +import io.netty.buffer.ByteBuf; public class BaseInfo { - private static final String VERSION = "Version2:"; - private String name; - public MyBlockPos blockPosition; - /** - * One block below the teleport destination - */ - public MyBlockPos teleportPosition; - /** unused */ - public UUID owner; - - public BaseInfo(String name, MyBlockPos teleportPosition, UUID owner){ - this.name = ""+name; - this.blockPosition = teleportPosition; - if(teleportPosition ==null){ - this.teleportPosition = null; - }else{ - this.teleportPosition = new MyBlockPos(teleportPosition); - } - this.owner = owner; - } - - public BaseInfo(String name, MyBlockPos blockPosition, MyBlockPos telePos, UUID owner){ - telePos.y--; - this.name = ""+name; - this.blockPosition = blockPosition; - this.teleportPosition = telePos; - this.owner = owner; - } - - public static BaseInfo loadBaseInfo(String name, MyBlockPos blockPos, MyBlockPos telePos, UUID owner){ - telePos.y++; - return new BaseInfo(name, blockPos, telePos, owner); - } - - public void writeToNBT(NBTTagCompound tC){ - tC.setString("name", ""+name); //Warum bin ich nur so unglaublich geh�rnamputiert? *kotz* - NBTTagCompound posComp = new NBTTagCompound(); - teleportPosition.writeToNBT(posComp); - tC.setTag("pos", posComp); - NBTTagCompound blockPosComp = new NBTTagCompound(); - teleportPosition.writeToNBT(blockPosComp); - blockPosition.writeToNBT(blockPosComp); - tC.setTag("blockPos", blockPosComp); - teleportPosition.writeToNBT(tC); - tC.setString("UUID", ""+owner); - } - - public static BaseInfo readFromNBT(NBTTagCompound tC) { - String name = tC.getString("name"); - UUID owner = uuidFromString(tC.getString("UUID")); - if(tC.hasKey("blockPos")){ - MyBlockPos pos = MyBlockPos.readFromNBT(tC.getCompoundTag("pos")); - MyBlockPos blockPos = MyBlockPos.readFromNBT(tC.getCompoundTag("blockPos")); - return loadBaseInfo(name, blockPos, pos, owner); - }else{ - MyBlockPos pos = MyBlockPos.readFromNBT(tC); - return new BaseInfo(name, pos, owner); - } - } - - public void toBytes(ByteBuf buf) { - ByteBufUtils.writeUTF8String(buf, ""+name); - teleportPosition.toBytes(buf); - ByteBufUtils.writeUTF8String(buf, VERSION+owner); - blockPosition.toBytes(buf); - } - - public static BaseInfo fromBytes(ByteBuf buf) { - String name = ByteBufUtils.readUTF8String(buf); - MyBlockPos pos = MyBlockPos.fromBytes(buf); - String o = ByteBufUtils.readUTF8String(buf); - if(o.startsWith(VERSION)){ - o = o.replaceFirst(VERSION, ""); - UUID owner; - try{ - owner = uuidFromString(o); - }catch(Exception e){ - owner = null; - } - MyBlockPos blockPos = MyBlockPos.fromBytes(buf); - return loadBaseInfo(name, blockPos, pos, owner);//Ich bin sehr dumm. - }else{ - UUID owner = uuidFromString(o); - return new BaseInfo(name, pos, owner); - } - } - - @Override - public boolean equals(Object other){ - if(!(other instanceof BaseInfo)){ - return super.equals(other); - }else{ - return ((BaseInfo)other).blockPosition.equals(this.blockPosition);//Wirklich sehr dumm. - } - } - - @Override - public int hashCode() { - return Objects.hash(blockPosition); - } - - public void setAll(BaseInfo newWS){ - this.name = ""+newWS.name; - this.teleportPosition.update(newWS.teleportPosition); - this.blockPosition.update(newWS.blockPosition); - this.owner = newWS.owner; - } - - public boolean update(BaseInfo newWS){ - if(equals(newWS)){ - setAll(newWS); - return true; - }else{ - return false; - } - } - - @Override - public String toString(){ - return ""+name; - } - - public boolean hasName(){ - return !(name==null || name.equals("null") || name.equals("")); - } - - public String getName(){ - return toString(); - } - - public void setName(String name){ - this.name = name; - } - - public static BaseInfo fromExternal(String name, int blockX, int blockY, int blockZ, int teleX, int teleY, int teleZ, int dimension, String modId){ - String worldString; - try{ - World world = FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(dimension); - worldString = world.getWorldInfo().getWorldName(); - }catch(Exception e){ - worldString = ""; - } - MyBlockPos blockPos = new MyBlockPos(blockX, blockY, blockZ, dimension); - MyBlockPos telePos = new MyBlockPos(teleX, teleY, teleZ, dimension); - return new BaseInfo(name, blockPos, telePos, null); - } - - private static UUID uuidFromString(String string){ - try{ - return UUID.fromString(string); - }catch(IllegalArgumentException e){ - return null; - } - } + private static final String VERSION = "Version2:"; + private String name; + public MyBlockPos blockPosition; + /** + * One block below the teleport destination + */ + public MyBlockPos teleportPosition; + /** unused */ + public UUID owner; + + public BaseInfo(String name, MyBlockPos teleportPosition, UUID owner) { + this.name = "" + name; + this.blockPosition = teleportPosition; + if (teleportPosition == null) { + this.teleportPosition = null; + } else { + this.teleportPosition = new MyBlockPos(teleportPosition); + } + this.owner = owner; + } + + public BaseInfo(String name, MyBlockPos blockPosition, MyBlockPos telePos, UUID owner) { + telePos.y--; + this.name = "" + name; + this.blockPosition = blockPosition; + this.teleportPosition = telePos; + this.owner = owner; + } + + public static BaseInfo loadBaseInfo(String name, MyBlockPos blockPos, MyBlockPos telePos, UUID owner) { + telePos.y++; + return new BaseInfo(name, blockPos, telePos, owner); + } + + public void writeToNBT(NBTTagCompound tC) { + tC.setString("name", "" + name); // Warum bin ich nur so unglaublich geh�rnamputiert? *kotz* + NBTTagCompound posComp = new NBTTagCompound(); + teleportPosition.writeToNBT(posComp); + tC.setTag("pos", posComp); + NBTTagCompound blockPosComp = new NBTTagCompound(); + teleportPosition.writeToNBT(blockPosComp); + blockPosition.writeToNBT(blockPosComp); + tC.setTag("blockPos", blockPosComp); + teleportPosition.writeToNBT(tC); + tC.setString("UUID", "" + owner); + } + + public static BaseInfo readFromNBT(NBTTagCompound tC) { + String name = tC.getString("name"); + UUID owner = uuidFromString(tC.getString("UUID")); + if (tC.hasKey("blockPos")) { + MyBlockPos pos = MyBlockPos.readFromNBT(tC.getCompoundTag("pos")); + MyBlockPos blockPos = MyBlockPos.readFromNBT(tC.getCompoundTag("blockPos")); + return loadBaseInfo(name, blockPos, pos, owner); + } else { + MyBlockPos pos = MyBlockPos.readFromNBT(tC); + return new BaseInfo(name, pos, owner); + } + } + + public void toBytes(ByteBuf buf) { + ByteBufUtils.writeUTF8String(buf, "" + name); + teleportPosition.toBytes(buf); + ByteBufUtils.writeUTF8String(buf, VERSION + owner); + blockPosition.toBytes(buf); + } + + public static BaseInfo fromBytes(ByteBuf buf) { + String name = ByteBufUtils.readUTF8String(buf); + MyBlockPos pos = MyBlockPos.fromBytes(buf); + String o = ByteBufUtils.readUTF8String(buf); + if (o.startsWith(VERSION)) { + o = o.replaceFirst(VERSION, ""); + UUID owner; + try { + owner = uuidFromString(o); + } catch (Exception e) { + owner = null; + } + MyBlockPos blockPos = MyBlockPos.fromBytes(buf); + return loadBaseInfo(name, blockPos, pos, owner);// Ich bin sehr dumm. + } else { + UUID owner = uuidFromString(o); + return new BaseInfo(name, pos, owner); + } + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof BaseInfo)) { + return super.equals(other); + } else { + return ((BaseInfo) other).blockPosition.equals(this.blockPosition);// Wirklich sehr dumm. + } + } + + @Override + public int hashCode() { + return Objects.hash(blockPosition); + } + + public void setAll(BaseInfo newWS) { + this.name = "" + newWS.name; + this.teleportPosition.update(newWS.teleportPosition); + this.blockPosition.update(newWS.blockPosition); + this.owner = newWS.owner; + } + + public boolean update(BaseInfo newWS) { + if (equals(newWS)) { + setAll(newWS); + return true; + } else { + return false; + } + } + + @Override + public String toString() { + return "" + name; + } + + public boolean hasName() { + return !(name == null || name.equals("null") || name.equals("")); + } + + public String getName() { + return toString(); + } + + public void setName(String name) { + this.name = name; + } + + public static BaseInfo fromExternal(String name, int blockX, int blockY, int blockZ, int teleX, int teleY, + int teleZ, int dimension, String modId) { + String worldString; + try { + World world = FMLCommonHandler.instance() + .getMinecraftServerInstance() + .worldServerForDimension(dimension); + worldString = world.getWorldInfo() + .getWorldName(); + } catch (Exception e) { + worldString = ""; + } + MyBlockPos blockPos = new MyBlockPos(blockX, blockY, blockZ, dimension); + MyBlockPos telePos = new MyBlockPos(teleX, teleY, teleZ, dimension); + return new BaseInfo(name, blockPos, telePos, null); + } + + private static UUID uuidFromString(String string) { + try { + return UUID.fromString(string); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/src/main/java/gollorum/signpost/util/BigBaseInfo.java b/src/main/java/gollorum/signpost/util/BigBaseInfo.java index e1ada837..bacdec97 100644 --- a/src/main/java/gollorum/signpost/util/BigBaseInfo.java +++ b/src/main/java/gollorum/signpost/util/BigBaseInfo.java @@ -2,25 +2,25 @@ import net.minecraft.util.ResourceLocation; -public class BigBaseInfo extends SignBaseInfo{ +public class BigBaseInfo extends SignBaseInfo { - public Sign sign; - public String[] description; - - public BigBaseInfo(ResourceLocation signTexture, ResourceLocation postTexture){ - this(new Sign(signTexture), postTexture); - } + public Sign sign; + public String[] description; - public BigBaseInfo(Sign sign, ResourceLocation texture){ - this.sign = sign; - String[] description = {"", "", "", ""}; - this.description = description; - this.postPaint = texture; - } + public BigBaseInfo(ResourceLocation signTexture, ResourceLocation postTexture) { + this(new Sign(signTexture), postTexture); + } - public BigBaseInfo(Sign sign, String[] description, ResourceLocation texture){ - this.sign = sign; - this.description = description; - this.postPaint = texture; - } + public BigBaseInfo(Sign sign, ResourceLocation texture) { + this.sign = sign; + String[] description = { "", "", "", "" }; + this.description = description; + this.postPaint = texture; + } + + public BigBaseInfo(Sign sign, String[] description, ResourceLocation texture) { + this.sign = sign; + this.description = description; + this.postPaint = texture; + } } diff --git a/src/main/java/gollorum/signpost/util/BiomeContainer.java b/src/main/java/gollorum/signpost/util/BiomeContainer.java index 1d3b91bb..29bf9b15 100644 --- a/src/main/java/gollorum/signpost/util/BiomeContainer.java +++ b/src/main/java/gollorum/signpost/util/BiomeContainer.java @@ -1,18 +1,20 @@ package gollorum.signpost.util; -import gollorum.signpost.util.code.MinecraftDependent; import net.minecraft.world.biome.BiomeGenBase; +import gollorum.signpost.util.code.MinecraftDependent; + @MinecraftDependent public class BiomeContainer { - private BiomeGenBase biome; - public BiomeContainer(BiomeGenBase biome) { - this.biome = biome; - } + private BiomeGenBase biome; + + public BiomeContainer(BiomeGenBase biome) { + this.biome = biome; + } + + public BiomeGenBase getBiome() { + return biome; + } - public BiomeGenBase getBiome() { - return biome; - } - } diff --git a/src/main/java/gollorum/signpost/util/BiomeLibrary.java b/src/main/java/gollorum/signpost/util/BiomeLibrary.java index bc6edcce..120c22df 100644 --- a/src/main/java/gollorum/signpost/util/BiomeLibrary.java +++ b/src/main/java/gollorum/signpost/util/BiomeLibrary.java @@ -3,94 +3,96 @@ import java.util.HashMap; import java.util.Map; -import gollorum.signpost.util.code.MinecraftDependent; import net.minecraft.world.biome.BiomeGenBase; +import gollorum.signpost.util.code.MinecraftDependent; + @MinecraftDependent public abstract class BiomeLibrary { - - protected Map entries; - - private BiomeLibrary(){ - entries = new HashMap(); - } - public String getName(BiomeGenBase biome){ - return getName(biome.biomeName); - } - - public String getName(String biomeRegistryName){ - return entries.get(biomeRegistryName); - } - - private static final BiomeLibrary INSTANCE = new BiomeLibrary(){ - { - entries.put("ocean", "Ocean"); - entries.put("plains", "Plains"); - entries.put("desert", "Desert"); - entries.put("extreme_hills", "Hills"); - entries.put("forest", "Forest"); - entries.put("taiga", "Taiga"); - entries.put("swampland", "Swamp"); - entries.put("river", "River"); - entries.put("hell", "Nether"); - entries.put("sky", "End"); - entries.put("frozen_ocean", "Ocean"); - entries.put("frozen_river", "River"); - entries.put("ice_flats", "Snow"); - entries.put("ice_mountains", "Snow"); - entries.put("mushroom_island", "Mushroom"); - entries.put("mushroom_island_shore", "Mushroom"); - entries.put("beaches", "Beaches"); - entries.put("desert_hills", "Desert"); - entries.put("forest_hills", "Forest"); - entries.put("taiga_hills", "Taiga"); - entries.put("smaller_extreme_hills", "Hills"); - entries.put("jungle", "Jungle"); - entries.put("jungle_hills", "Jungle"); - entries.put("jungle_edge", "Jungle"); - entries.put("deep_ocean", "Ocean"); - entries.put("stone_beach", "Beaches"); - entries.put("cold_beach", "Beaches"); - entries.put("birch_forest", "BirchForest"); - entries.put("birch_forest_hills", "BirchForest"); - entries.put("roofed_forest", "RoofedForest"); - entries.put("taiga_cold", "Taiga"); - entries.put("taiga_cold_hills", "Taiga"); - entries.put("redwood_taiga", "Taiga"); - entries.put("redwood_taiga_hills", "Taiga"); - entries.put("extreme_hills_with_trees", "Forest"); - entries.put("savanna", "Savanna"); - entries.put("savanna_rock", "Savanna"); - entries.put("mesa", "Mesa"); - entries.put("mesa_rock", "Mesa"); - entries.put("mesa_clear_rock", "Mesa"); - entries.put("void", "Void"); - entries.put("mutated_plains", "Plains"); - entries.put("mutated_desert", "Desert"); - entries.put("mutated_extreme_hills", "Hills"); - entries.put("mutated_forest", "Forest"); - entries.put("mutated_taiga", "Taiga"); - entries.put("mutated_swampland", "Swamp"); - entries.put("mutated_ice_flats", "Snow"); - entries.put("mutated_jungle", "Jungle"); - entries.put("mutated_jungle_edge", "Jungle"); - entries.put("mutated_birch_forest", "BirchForest"); - entries.put("mutated_birch_forest_hills", "BirchForest"); - entries.put("mutated_roofed_forest", "RoofedForest"); - entries.put("mutated_taiga_cold", "Snow"); - entries.put("mutated_redwood_taiga", "Taiga"); - entries.put("mutated_redwood_taiga_hills", "Taiga"); - entries.put("mutated_extreme_hills_with_trees", "Forest"); - entries.put("mutated_savanna", "Savanna"); - entries.put("mutated_savanna_rock", "Savanna"); - entries.put("mutated_mesa", "Mesa"); - entries.put("mutated_mesa_rock", "Mesa"); - entries.put("mutated_mesa_clear_rock", "Mesa"); - } - }; + protected Map entries; + + private BiomeLibrary() { + entries = new HashMap(); + } + + public String getName(BiomeGenBase biome) { + return getName(biome.biomeName); + } + + public String getName(String biomeRegistryName) { + return entries.get(biomeRegistryName); + } + + private static final BiomeLibrary INSTANCE = new BiomeLibrary() { + + { + entries.put("ocean", "Ocean"); + entries.put("plains", "Plains"); + entries.put("desert", "Desert"); + entries.put("extreme_hills", "Hills"); + entries.put("forest", "Forest"); + entries.put("taiga", "Taiga"); + entries.put("swampland", "Swamp"); + entries.put("river", "River"); + entries.put("hell", "Nether"); + entries.put("sky", "End"); + entries.put("frozen_ocean", "Ocean"); + entries.put("frozen_river", "River"); + entries.put("ice_flats", "Snow"); + entries.put("ice_mountains", "Snow"); + entries.put("mushroom_island", "Mushroom"); + entries.put("mushroom_island_shore", "Mushroom"); + entries.put("beaches", "Beaches"); + entries.put("desert_hills", "Desert"); + entries.put("forest_hills", "Forest"); + entries.put("taiga_hills", "Taiga"); + entries.put("smaller_extreme_hills", "Hills"); + entries.put("jungle", "Jungle"); + entries.put("jungle_hills", "Jungle"); + entries.put("jungle_edge", "Jungle"); + entries.put("deep_ocean", "Ocean"); + entries.put("stone_beach", "Beaches"); + entries.put("cold_beach", "Beaches"); + entries.put("birch_forest", "BirchForest"); + entries.put("birch_forest_hills", "BirchForest"); + entries.put("roofed_forest", "RoofedForest"); + entries.put("taiga_cold", "Taiga"); + entries.put("taiga_cold_hills", "Taiga"); + entries.put("redwood_taiga", "Taiga"); + entries.put("redwood_taiga_hills", "Taiga"); + entries.put("extreme_hills_with_trees", "Forest"); + entries.put("savanna", "Savanna"); + entries.put("savanna_rock", "Savanna"); + entries.put("mesa", "Mesa"); + entries.put("mesa_rock", "Mesa"); + entries.put("mesa_clear_rock", "Mesa"); + entries.put("void", "Void"); + entries.put("mutated_plains", "Plains"); + entries.put("mutated_desert", "Desert"); + entries.put("mutated_extreme_hills", "Hills"); + entries.put("mutated_forest", "Forest"); + entries.put("mutated_taiga", "Taiga"); + entries.put("mutated_swampland", "Swamp"); + entries.put("mutated_ice_flats", "Snow"); + entries.put("mutated_jungle", "Jungle"); + entries.put("mutated_jungle_edge", "Jungle"); + entries.put("mutated_birch_forest", "BirchForest"); + entries.put("mutated_birch_forest_hills", "BirchForest"); + entries.put("mutated_roofed_forest", "RoofedForest"); + entries.put("mutated_taiga_cold", "Snow"); + entries.put("mutated_redwood_taiga", "Taiga"); + entries.put("mutated_redwood_taiga_hills", "Taiga"); + entries.put("mutated_extreme_hills_with_trees", "Forest"); + entries.put("mutated_savanna", "Savanna"); + entries.put("mutated_savanna_rock", "Savanna"); + entries.put("mutated_mesa", "Mesa"); + entries.put("mutated_mesa_rock", "Mesa"); + entries.put("mutated_mesa_clear_rock", "Mesa"); + } + }; - public static BiomeLibrary getInstance(){ - return INSTANCE; - } + public static BiomeLibrary getInstance() { + return INSTANCE; + } } diff --git a/src/main/java/gollorum/signpost/util/BiomePaintEntry.java b/src/main/java/gollorum/signpost/util/BiomePaintEntry.java index f5e84c3c..22fbe9e6 100644 --- a/src/main/java/gollorum/signpost/util/BiomePaintEntry.java +++ b/src/main/java/gollorum/signpost/util/BiomePaintEntry.java @@ -9,46 +9,50 @@ @MinecraftIndependent public abstract class BiomePaintEntry { - - protected Map textures; - - public String getTexture(String key){ - return textures.get(key); - } - - public static final BiomePaintEntry DEFAULT_PLAINS = new BiomePaintEntry(){ - { - textures = new HashMap(); - textures.put("PostSign", PostPost.PostType.OAK.texture.toString()); - textures.put("BigPostSign", BigPostPost.BigPostType.OAK.texture.toString()); - textures.put("PostPost", PostPost.PostType.OAK.resLocMain.toString()); - } - }; - - public static final BiomePaintEntry DEFAULT_DESERT = new BiomePaintEntry(){ - { - textures = new HashMap(); - textures.put("PostSign", "textures/blocks/sandstone_smooth.png"); - textures.put("BigPostSign", "textures/blocks/sandstone_smooth.png"); - textures.put("PostPost", "textures/blocks/cobblestone.png"); - } - }; - - public static final BiomePaintEntry DEFAULT_TAIGA = new BiomePaintEntry(){ - { - textures = new HashMap(); - textures.put("PostSign", PostPost.PostType.SPRUCE.texture.toString()); - textures.put("BigPostSign", BigPostPost.BigPostType.SPRUCE.texture.toString()); - textures.put("PostPost", PostPost.PostType.SPRUCE.resLocMain.toString()); - } - }; - - public static final BiomePaintEntry DEFAULT_SAVANNA = new BiomePaintEntry(){ - { - textures = new HashMap(); - textures.put("PostSign", PostPost.PostType.ACACIA.texture.toString()); - textures.put("BigPostSign", BigPostPost.BigPostType.ACACIA.texture.toString()); - textures.put("PostPost", PostPost.PostType.ACACIA.resLocMain.toString()); - } - }; + + protected Map textures; + + public String getTexture(String key) { + return textures.get(key); + } + + public static final BiomePaintEntry DEFAULT_PLAINS = new BiomePaintEntry() { + + { + textures = new HashMap(); + textures.put("PostSign", PostPost.PostType.OAK.texture.toString()); + textures.put("BigPostSign", BigPostPost.BigPostType.OAK.texture.toString()); + textures.put("PostPost", PostPost.PostType.OAK.resLocMain.toString()); + } + }; + + public static final BiomePaintEntry DEFAULT_DESERT = new BiomePaintEntry() { + + { + textures = new HashMap(); + textures.put("PostSign", "textures/blocks/sandstone_smooth.png"); + textures.put("BigPostSign", "textures/blocks/sandstone_smooth.png"); + textures.put("PostPost", "textures/blocks/cobblestone.png"); + } + }; + + public static final BiomePaintEntry DEFAULT_TAIGA = new BiomePaintEntry() { + + { + textures = new HashMap(); + textures.put("PostSign", PostPost.PostType.SPRUCE.texture.toString()); + textures.put("BigPostSign", BigPostPost.BigPostType.SPRUCE.texture.toString()); + textures.put("PostPost", PostPost.PostType.SPRUCE.resLocMain.toString()); + } + }; + + public static final BiomePaintEntry DEFAULT_SAVANNA = new BiomePaintEntry() { + + { + textures = new HashMap(); + textures.put("PostSign", PostPost.PostType.ACACIA.texture.toString()); + textures.put("BigPostSign", BigPostPost.BigPostType.ACACIA.texture.toString()); + textures.put("PostPost", PostPost.PostType.ACACIA.resLocMain.toString()); + } + }; } diff --git a/src/main/java/gollorum/signpost/util/BiomePaintHandler.java b/src/main/java/gollorum/signpost/util/BiomePaintHandler.java index 6f9cfe59..ab823ddd 100644 --- a/src/main/java/gollorum/signpost/util/BiomePaintHandler.java +++ b/src/main/java/gollorum/signpost/util/BiomePaintHandler.java @@ -10,81 +10,94 @@ @MinecraftIndependent public abstract class BiomePaintHandler implements Map { - protected HashMap biomeList; - - public static final BiomePaintHandler DEFAULT_HANDLER = new BiomePaintHandler() { - { - biomeList = new HashMap(); - put(BiomeLibrary.getInstance().getName("plains"), BiomePaintEntry.DEFAULT_PLAINS); - put(BiomeLibrary.getInstance().getName("desert"), BiomePaintEntry.DEFAULT_DESERT); - put(BiomeLibrary.getInstance().getName("savanna"), BiomePaintEntry.DEFAULT_SAVANNA); - put(BiomeLibrary.getInstance().getName("taiga"), BiomePaintEntry.DEFAULT_TAIGA); - } - }; - - @Override - public int size() { - return biomeList.size(); - } - - @Override - public boolean isEmpty() { - return biomeList.isEmpty(); - } - - @Override - public boolean containsKey(Object key) { - return biomeList.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - return biomeList.containsValue(value); - } - - @Override - public BiomePaintEntry get(Object key) { - BiomePaintEntry ret = biomeList.get(key); - if (ret == null) { - return (BiomePaintEntry) values().toArray()[0]; - } else { - return ret; - } - } - - @Override - public BiomePaintEntry put(String key, BiomePaintEntry value) { - return biomeList.put(key, value); - } - - @Override - public BiomePaintEntry remove(Object key) { - return biomeList.remove(key); - } - - @Override - public void putAll(Map m) { - biomeList.putAll(m); - } - - @Override - public void clear() { - biomeList.clear(); - } - - @Override - public Set keySet() { - return biomeList.keySet(); - } - - @Override - public Collection values() { - return biomeList.values(); - } - - @Override - public Set> entrySet() { - return biomeList.entrySet(); - } - -} \ No newline at end of file + protected HashMap biomeList; + + public static final BiomePaintHandler DEFAULT_HANDLER = new BiomePaintHandler() { + + { + biomeList = new HashMap(); + put( + BiomeLibrary.getInstance() + .getName("plains"), + BiomePaintEntry.DEFAULT_PLAINS); + put( + BiomeLibrary.getInstance() + .getName("desert"), + BiomePaintEntry.DEFAULT_DESERT); + put( + BiomeLibrary.getInstance() + .getName("savanna"), + BiomePaintEntry.DEFAULT_SAVANNA); + put( + BiomeLibrary.getInstance() + .getName("taiga"), + BiomePaintEntry.DEFAULT_TAIGA); + } + }; + + @Override + public int size() { + return biomeList.size(); + } + + @Override + public boolean isEmpty() { + return biomeList.isEmpty(); + } + + @Override + public boolean containsKey(Object key) { + return biomeList.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return biomeList.containsValue(value); + } + + @Override + public BiomePaintEntry get(Object key) { + BiomePaintEntry ret = biomeList.get(key); + if (ret == null) { + return (BiomePaintEntry) values().toArray()[0]; + } else { + return ret; + } + } + + @Override + public BiomePaintEntry put(String key, BiomePaintEntry value) { + return biomeList.put(key, value); + } + + @Override + public BiomePaintEntry remove(Object key) { + return biomeList.remove(key); + } + + @Override + public void putAll(Map m) { + biomeList.putAll(m); + } + + @Override + public void clear() { + biomeList.clear(); + } + + @Override + public Set keySet() { + return biomeList.keySet(); + } + + @Override + public Collection values() { + return biomeList.values(); + } + + @Override + public Set> entrySet() { + return biomeList.entrySet(); + } + +} diff --git a/src/main/java/gollorum/signpost/util/BoolRun.java b/src/main/java/gollorum/signpost/util/BoolRun.java index 480de044..1e9e234f 100644 --- a/src/main/java/gollorum/signpost/util/BoolRun.java +++ b/src/main/java/gollorum/signpost/util/BoolRun.java @@ -2,6 +2,6 @@ public interface BoolRun { - public boolean run(); - + public boolean run(); + } diff --git a/src/main/java/gollorum/signpost/util/DoubleBaseInfo.java b/src/main/java/gollorum/signpost/util/DoubleBaseInfo.java index 26b20469..c090eff5 100644 --- a/src/main/java/gollorum/signpost/util/DoubleBaseInfo.java +++ b/src/main/java/gollorum/signpost/util/DoubleBaseInfo.java @@ -4,23 +4,23 @@ public class DoubleBaseInfo extends SignBaseInfo { - public Sign sign1; - public Sign sign2; + public Sign sign1; + public Sign sign2; - public DoubleBaseInfo(ResourceLocation signTexture, ResourceLocation postTexture){ - this.sign1 = new Sign(signTexture); - this.sign2 = new Sign(signTexture); - postPaint = postTexture; - } - - public DoubleBaseInfo(Sign sign1, Sign sign2, ResourceLocation texture){ - this.sign1 = sign1; - this.sign2 = sign2; - postPaint = texture; - } - - @Override - public String toString(){ - return sign1+" and "+sign2; - } + public DoubleBaseInfo(ResourceLocation signTexture, ResourceLocation postTexture) { + this.sign1 = new Sign(signTexture); + this.sign2 = new Sign(signTexture); + postPaint = postTexture; + } + + public DoubleBaseInfo(Sign sign1, Sign sign2, ResourceLocation texture) { + this.sign1 = sign1; + this.sign2 = sign2; + postPaint = texture; + } + + @Override + public String toString() { + return sign1 + " and " + sign2; + } } diff --git a/src/main/java/gollorum/signpost/util/MyBlockPos.java b/src/main/java/gollorum/signpost/util/MyBlockPos.java index 67175f94..c536615d 100644 --- a/src/main/java/gollorum/signpost/util/MyBlockPos.java +++ b/src/main/java/gollorum/signpost/util/MyBlockPos.java @@ -1,216 +1,222 @@ package gollorum.signpost.util; -import cpw.mods.fml.common.network.ByteBufUtils; -import gollorum.signpost.Signpost; -import gollorum.signpost.blocks.tiles.BigPostPostTile; -import gollorum.signpost.blocks.tiles.PostPostTile; -import gollorum.signpost.management.ClientConfigStorage; -import io.netty.buffer.ByteBuf; +import java.util.Objects; +import java.util.function.Function; + import net.minecraft.entity.Entity; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -import java.util.Objects; -import java.util.function.Function; +import cpw.mods.fml.common.network.ByteBufUtils; +import gollorum.signpost.Signpost; +import gollorum.signpost.blocks.tiles.BigPostPostTile; +import gollorum.signpost.blocks.tiles.PostPostTile; +import gollorum.signpost.management.ClientConfigStorage; +import io.netty.buffer.ByteBuf; public class MyBlockPos { - private static final String VERSION = "1"; - - public int x, y, z; - public int dim; - public MyBlockPos(World world, int x, int y, int z){ - this(x, y, z, dim(world)); - } - - public MyBlockPos(int x, int y, int z, int dim){ - this.x = x; - this.y = y; - this.z = z; - this.dim = dim; - } - - public MyBlockPos(MyBlockPos pos) { - this(pos.x, pos.y, pos.z, pos.dim); - } - - public MyBlockPos(Entity entity){ - this((int)Math.floor(entity.posX), (int)Math.floor(entity.posY), (int)Math.floor(entity.posZ), dim(entity.worldObj)); - } - - public static int dim(World world){ - if(world==null||world.provider==null){ - return Integer.MIN_VALUE; - }else - return world.provider.dimensionId; - } - - public Connection canConnectTo(BaseInfo inf){ - if(inf==null){ - return Connection.VALID; - } - if(ClientConfigStorage.INSTANCE.deactivateTeleportation()){ - return Connection.VALID; - } - if(!checkInterdimensional(inf.teleportPosition)){ - return Connection.WORLD; - } - if(ClientConfigStorage.INSTANCE.getMaxDist() > -1 && distance(inf.teleportPosition)>ClientConfigStorage.INSTANCE.getMaxDist()){ - return Connection.DIST; - } - return Connection.VALID; - } - - public static enum Connection{VALID, WORLD, DIST} - - public boolean checkInterdimensional(MyBlockPos pos){ - if(pos==null){ - return true; - } - boolean config = ClientConfigStorage.INSTANCE.interdimensional(); - return config || sameDim(pos); - } - - public NBTTagCompound writeToNBT(NBTTagCompound tC){ - int[] arr = {x, y, z, dim}; - tC.setIntArray("Position", arr); - tC.setString("Version", VERSION); - return tC; - } - - public static MyBlockPos readFromNBT(NBTTagCompound tC){ - int[] arr = tC.getIntArray("Position"); - return new MyBlockPos(arr[0], arr[1], arr[2], arr[3]); - } - - public void toBytes(ByteBuf buf) { - ByteBufUtils.writeUTF8String(buf, VERSION); - buf.writeInt(x); - buf.writeInt(y); - buf.writeInt(z); - buf.writeInt(dim); - } - - public static MyBlockPos fromBytes(ByteBuf buf) { - String savedVersion = ByteBufUtils.readUTF8String(buf); - int x = buf.readInt(); - int y = buf.readInt(); - int z = buf.readInt(); - int dim = buf.readInt(); - if(!savedVersion.equals(VERSION)) ByteBufUtils.readUTF8String(buf); - return new MyBlockPos(x, y, z, dim); - } - - @Override - public String toString(){ - return x+"|"+y+"|"+z+" in "+dim; - } - - @Override - public boolean equals(Object obj){ - if(!(obj instanceof MyBlockPos)){ - return false; - } - MyBlockPos other = (MyBlockPos)obj; - return other.x == this.x - && other.y == this.y - && other.z == this.z - && sameDim(other); - } - - @Override - public int hashCode() { - return Objects.hash(x, y, z, dim); - } - - public boolean sameDim(MyBlockPos other){ - if(other.dim==Integer.MIN_VALUE || this.dim == Integer.MIN_VALUE){ - other.dim = this.dim = Math.max(other.dim, this.dim); - } else return other.dim == this.dim; - return true; - } - - public MyBlockPos update(MyBlockPos newPos){ - x = newPos.x; - y = newPos.y; - z = newPos.z; - if(!(newPos.dim==Integer.MIN_VALUE)){ - dim = newPos.dim; - }else{ - newPos.dim = dim; - } - return this; - } - - public double distance(MyBlockPos other){ - int dx = this.x-other.x; - int dy = this.y-other.y; - int dz = this.z-other.z; - return Math.sqrt(dx*dx + dy*dy + dz*dz); - } - - public World getWorld(){ - return Signpost.proxy.getWorld(this.dim); - } - - public TileEntity getTile(){ - World world = getWorld(); - if(world!=null){ - TileEntity tile = world.getTileEntity(x, y, z); - if(tile instanceof PostPostTile){ - ((PostPostTile) tile).getBases(); - }else if(tile instanceof PostPostTile){ - ((BigPostPostTile) tile).getBases(); - } - return tile; - }else{ - return null; - } - } - - public MyBlockPos withX(int x) { - return new MyBlockPos(x, y, z, dim); - } - - public MyBlockPos withX(Function xMap) { - return this.withX(xMap.apply(x)); - } - - public MyBlockPos withY(int y) { - return new MyBlockPos(x, y, z, dim); - } - - public MyBlockPos withY(Function yMap) { - return this.withY(yMap.apply(y)); - } - - public MyBlockPos withZ(int z) { - return new MyBlockPos(x, y, z, dim); - } - - public MyBlockPos withZ(Function zMap) { - return this.withZ(zMap.apply(z)); - } - - public MyBlockPos getBelow(){ - return this.withY(y -> y - 1); - } - - public MyBlockPos front(EnumFacing facing, int i) { - return this - .withX(x -> x + facing.getFrontOffsetX() * i) - .withY(y -> y + facing.getFrontOffsetY() * i) - .withZ(z -> z + facing.getFrontOffsetZ() * i); - } - - public BiomeContainer getBiome(){ - World world = getWorld(); - if(world != null){ - return new BiomeContainer(world.getBiomeGenForCoords(x, z)); - }else{ - return null; - } - } -} \ No newline at end of file + private static final String VERSION = "1"; + + public int x, y, z; + public int dim; + + public MyBlockPos(World world, int x, int y, int z) { + this(x, y, z, dim(world)); + } + + public MyBlockPos(int x, int y, int z, int dim) { + this.x = x; + this.y = y; + this.z = z; + this.dim = dim; + } + + public MyBlockPos(MyBlockPos pos) { + this(pos.x, pos.y, pos.z, pos.dim); + } + + public MyBlockPos(Entity entity) { + this( + (int) Math.floor(entity.posX), + (int) Math.floor(entity.posY), + (int) Math.floor(entity.posZ), + dim(entity.worldObj)); + } + + public static int dim(World world) { + if (world == null || world.provider == null) { + return Integer.MIN_VALUE; + } else return world.provider.dimensionId; + } + + public Connection canConnectTo(BaseInfo inf) { + if (inf == null) { + return Connection.VALID; + } + if (ClientConfigStorage.INSTANCE.deactivateTeleportation()) { + return Connection.VALID; + } + if (!checkInterdimensional(inf.teleportPosition)) { + return Connection.WORLD; + } + if (ClientConfigStorage.INSTANCE.getMaxDist() > -1 + && distance(inf.teleportPosition) > ClientConfigStorage.INSTANCE.getMaxDist()) { + return Connection.DIST; + } + return Connection.VALID; + } + + public static enum Connection { + VALID, + WORLD, + DIST + } + + public boolean checkInterdimensional(MyBlockPos pos) { + if (pos == null) { + return true; + } + boolean config = ClientConfigStorage.INSTANCE.interdimensional(); + return config || sameDim(pos); + } + + public NBTTagCompound writeToNBT(NBTTagCompound tC) { + int[] arr = { x, y, z, dim }; + tC.setIntArray("Position", arr); + tC.setString("Version", VERSION); + return tC; + } + + public static MyBlockPos readFromNBT(NBTTagCompound tC) { + int[] arr = tC.getIntArray("Position"); + return new MyBlockPos(arr[0], arr[1], arr[2], arr[3]); + } + + public void toBytes(ByteBuf buf) { + ByteBufUtils.writeUTF8String(buf, VERSION); + buf.writeInt(x); + buf.writeInt(y); + buf.writeInt(z); + buf.writeInt(dim); + } + + public static MyBlockPos fromBytes(ByteBuf buf) { + String savedVersion = ByteBufUtils.readUTF8String(buf); + int x = buf.readInt(); + int y = buf.readInt(); + int z = buf.readInt(); + int dim = buf.readInt(); + if (!savedVersion.equals(VERSION)) ByteBufUtils.readUTF8String(buf); + return new MyBlockPos(x, y, z, dim); + } + + @Override + public String toString() { + return x + "|" + y + "|" + z + " in " + dim; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof MyBlockPos)) { + return false; + } + MyBlockPos other = (MyBlockPos) obj; + return other.x == this.x && other.y == this.y && other.z == this.z && sameDim(other); + } + + @Override + public int hashCode() { + return Objects.hash(x, y, z, dim); + } + + public boolean sameDim(MyBlockPos other) { + if (other.dim == Integer.MIN_VALUE || this.dim == Integer.MIN_VALUE) { + other.dim = this.dim = Math.max(other.dim, this.dim); + } else return other.dim == this.dim; + return true; + } + + public MyBlockPos update(MyBlockPos newPos) { + x = newPos.x; + y = newPos.y; + z = newPos.z; + if (!(newPos.dim == Integer.MIN_VALUE)) { + dim = newPos.dim; + } else { + newPos.dim = dim; + } + return this; + } + + public double distance(MyBlockPos other) { + int dx = this.x - other.x; + int dy = this.y - other.y; + int dz = this.z - other.z; + return Math.sqrt(dx * dx + dy * dy + dz * dz); + } + + public World getWorld() { + return Signpost.proxy.getWorld(this.dim); + } + + public TileEntity getTile() { + World world = getWorld(); + if (world != null) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof PostPostTile) { + ((PostPostTile) tile).getBases(); + } else if (tile instanceof PostPostTile) { + ((BigPostPostTile) tile).getBases(); + } + return tile; + } else { + return null; + } + } + + public MyBlockPos withX(int x) { + return new MyBlockPos(x, y, z, dim); + } + + public MyBlockPos withX(Function xMap) { + return this.withX(xMap.apply(x)); + } + + public MyBlockPos withY(int y) { + return new MyBlockPos(x, y, z, dim); + } + + public MyBlockPos withY(Function yMap) { + return this.withY(yMap.apply(y)); + } + + public MyBlockPos withZ(int z) { + return new MyBlockPos(x, y, z, dim); + } + + public MyBlockPos withZ(Function zMap) { + return this.withZ(zMap.apply(z)); + } + + public MyBlockPos getBelow() { + return this.withY(y -> y - 1); + } + + public MyBlockPos front(EnumFacing facing, int i) { + return this.withX(x -> x + facing.getFrontOffsetX() * i) + .withY(y -> y + facing.getFrontOffsetY() * i) + .withZ(z -> z + facing.getFrontOffsetZ() * i); + } + + public BiomeContainer getBiome() { + World world = getWorld(); + if (world != null) { + return new BiomeContainer(world.getBiomeGenForCoords(x, z)); + } else { + return null; + } + } +} diff --git a/src/main/java/gollorum/signpost/util/MyBlockPosSet.java b/src/main/java/gollorum/signpost/util/MyBlockPosSet.java index ff656b79..01b118ce 100644 --- a/src/main/java/gollorum/signpost/util/MyBlockPosSet.java +++ b/src/main/java/gollorum/signpost/util/MyBlockPosSet.java @@ -4,25 +4,25 @@ public class MyBlockPosSet extends HashSet { - @Override - public boolean add(MyBlockPos str) { - for (MyBlockPos now : this) { - if (now.equals(str)){ - return false; - } - } - super.add(str); - return true; - } + @Override + public boolean add(MyBlockPos str) { + for (MyBlockPos now : this) { + if (now.equals(str)) { + return false; + } + } + super.add(str); + return true; + } - @Override - public boolean contains(Object str) { - for (MyBlockPos now : this) { - if (str.equals(now)) { - return true; - } - } - return false; - } + @Override + public boolean contains(Object str) { + for (MyBlockPos now : this) { + if (str.equals(now)) { + return true; + } + } + return false; + } -} \ No newline at end of file +} diff --git a/src/main/java/gollorum/signpost/util/Paintable.java b/src/main/java/gollorum/signpost/util/Paintable.java index 5c3b1f5d..cf2e61df 100644 --- a/src/main/java/gollorum/signpost/util/Paintable.java +++ b/src/main/java/gollorum/signpost/util/Paintable.java @@ -1,18 +1,25 @@ package gollorum.signpost.util; -import gollorum.signpost.Signpost; import net.minecraft.util.ResourceLocation; -import net.minecraft.world.biome.BiomeGenBase; + +import gollorum.signpost.Tags; public interface Paintable { - public static final ResourceLocation SIGN_PAINT = new ResourceLocation(Signpost.MODID, "textures/blocks/sign_paint.png"); - public static final ResourceLocation BIGSIGN_PAINT = new ResourceLocation(Signpost.MODID, "textures/blocks/bigsign_paint.png"); - public static final ResourceLocation POST_PAINT = new ResourceLocation(Signpost.MODID, "textures/blocks/paint.png"); + public static final ResourceLocation SIGN_PAINT = new ResourceLocation( + Tags.MODID, + "textures/blocks/sign_paint.png"); + public static final ResourceLocation BIGSIGN_PAINT = new ResourceLocation( + Tags.MODID, + "textures/blocks/bigsign_paint.png"); + public static final ResourceLocation POST_PAINT = new ResourceLocation(Tags.MODID, "textures/blocks/paint.png"); + + public ResourceLocation getTexture(); + + public void setTexture(ResourceLocation texture); + + public ResourceLocation getDefaultBiomeTexture(BiomeContainer biome); + + public void setTextureToBiomeDefault(BiomeContainer biome); - public ResourceLocation getTexture(); - public void setTexture(ResourceLocation texture); - public ResourceLocation getDefaultBiomeTexture(BiomeContainer biome); - public void setTextureToBiomeDefault(BiomeContainer biome); - } diff --git a/src/main/java/gollorum/signpost/util/Sign.java b/src/main/java/gollorum/signpost/util/Sign.java index 06c42ad3..df94ed9f 100644 --- a/src/main/java/gollorum/signpost/util/Sign.java +++ b/src/main/java/gollorum/signpost/util/Sign.java @@ -1,115 +1,121 @@ package gollorum.signpost.util; -import gollorum.signpost.blocks.PostPost; -import gollorum.signpost.management.ClientConfigStorage; -import gollorum.signpost.util.math.tracking.DDDVector; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; +import gollorum.signpost.blocks.PostPost; +import gollorum.signpost.management.ClientConfigStorage; +import gollorum.signpost.util.math.tracking.DDDVector; + public class Sign implements Paintable { - public BaseInfo base; - public int rotation; - public boolean flip; - public OverlayType overlay; - public boolean point; - public ResourceLocation paint; - - public Sign(ResourceLocation texture){ - base = null; - rotation = 0; - flip = false; - overlay = null; - point = false; - paint = texture; - } - - public Sign(BaseInfo base, int rotation, boolean flip, OverlayType overlay, boolean point, ResourceLocation paint) { - this.base = base; - this.rotation = rotation; - this.flip = flip; - this.overlay = overlay; - this.point = point; - this.paint = paint; - } - - public static enum OverlayType{ - GRAS( "grass", Items.wheat_seeds), - VINE( "vine", Item.getItemFromBlock(Blocks.vine)), - SNOW( "snow", Items.snowball); - public String texture; - public Item item; - OverlayType(String texture, Item item){ - this.texture = texture; - this.item = item; - } - public static OverlayType get(String arg){ - try{ - return valueOf(arg); - }catch(IllegalArgumentException e){ - return null; - } - } - } - - public final double calcRot(int x, int z) { - if(point&&!(base==null||base.blockPosition ==null||ClientConfigStorage.INSTANCE.deactivateTeleportation())){ - int dx = x-base.blockPosition.x; - int dz = z-base.blockPosition.z; - return DDDVector.genAngle(dx, dz)+Math.toRadians(-90+(flip?0:180)+(dx<0&&dz>0?180:0)); - }else{ - return Math.toRadians(rotation); - } - } - - public boolean isValid(){ - return base!=null && base.hasName(); - } - - public void rot(int i, int x, int z) { - if(point){ - rotation = (int) Math.round(Math.toDegrees(calcRot(x, z))/15)*15; - point = false; - } - rotation = (rotation+i)%360; - } - - @Override - public String toString(){ - return ""+base; - } - - @Override - public ResourceLocation getTexture() { - return paint; - } - - @Override - public void setTexture(ResourceLocation texture) { - paint = texture; - } - - @Override - public ResourceLocation getDefaultBiomeTexture(BiomeContainer biome) { - if(biome == null || biome.getBiome() == null) { - return PostPost.PostType.OAK.texture; - } - if(biome.getBiome().biomeName.contains("Plains")){ - return PostPost.PostType.OAK.texture; - }else if(biome.getBiome().biomeName.contains("Desert")){ - return new ResourceLocation("textures/blocks/sandstone_smooth.png"); - }else if(biome.getBiome().biomeName.contains("Taiga")){ - return PostPost.PostType.SPRUCE.texture; - }else if(biome.getBiome().biomeName.contains("Savanna")){ - return PostPost.PostType.ACACIA.texture; - }else{ - return PostPost.PostType.OAK.texture; - } - } - - public void setTextureToBiomeDefault(BiomeContainer biome){ - setTexture(getDefaultBiomeTexture(biome)); - } -} \ No newline at end of file + public BaseInfo base; + public int rotation; + public boolean flip; + public OverlayType overlay; + public boolean point; + public ResourceLocation paint; + + public Sign(ResourceLocation texture) { + base = null; + rotation = 0; + flip = false; + overlay = null; + point = false; + paint = texture; + } + + public Sign(BaseInfo base, int rotation, boolean flip, OverlayType overlay, boolean point, ResourceLocation paint) { + this.base = base; + this.rotation = rotation; + this.flip = flip; + this.overlay = overlay; + this.point = point; + this.paint = paint; + } + + public static enum OverlayType { + + GRAS("grass", Items.wheat_seeds), + VINE("vine", Item.getItemFromBlock(Blocks.vine)), + SNOW("snow", Items.snowball); + + public String texture; + public Item item; + + OverlayType(String texture, Item item) { + this.texture = texture; + this.item = item; + } + + public static OverlayType get(String arg) { + try { + return valueOf(arg); + } catch (IllegalArgumentException e) { + return null; + } + } + } + + public final double calcRot(int x, int z) { + if (point && !(base == null || base.blockPosition == null + || ClientConfigStorage.INSTANCE.deactivateTeleportation())) { + int dx = x - base.blockPosition.x; + int dz = z - base.blockPosition.z; + return DDDVector.genAngle(dx, dz) + Math.toRadians(-90 + (flip ? 0 : 180) + (dx < 0 && dz > 0 ? 180 : 0)); + } else { + return Math.toRadians(rotation); + } + } + + public boolean isValid() { + return base != null && base.hasName(); + } + + public void rot(int i, int x, int z) { + if (point) { + rotation = (int) Math.round(Math.toDegrees(calcRot(x, z)) / 15) * 15; + point = false; + } + rotation = (rotation + i) % 360; + } + + @Override + public String toString() { + return "" + base; + } + + @Override + public ResourceLocation getTexture() { + return paint; + } + + @Override + public void setTexture(ResourceLocation texture) { + paint = texture; + } + + @Override + public ResourceLocation getDefaultBiomeTexture(BiomeContainer biome) { + if (biome == null || biome.getBiome() == null) { + return PostPost.PostType.OAK.texture; + } + if (biome.getBiome().biomeName.contains("Plains")) { + return PostPost.PostType.OAK.texture; + } else if (biome.getBiome().biomeName.contains("Desert")) { + return new ResourceLocation("textures/blocks/sandstone_smooth.png"); + } else if (biome.getBiome().biomeName.contains("Taiga")) { + return PostPost.PostType.SPRUCE.texture; + } else if (biome.getBiome().biomeName.contains("Savanna")) { + return PostPost.PostType.ACACIA.texture; + } else { + return PostPost.PostType.OAK.texture; + } + } + + public void setTextureToBiomeDefault(BiomeContainer biome) { + setTexture(getDefaultBiomeTexture(biome)); + } +} diff --git a/src/main/java/gollorum/signpost/util/SignBaseInfo.java b/src/main/java/gollorum/signpost/util/SignBaseInfo.java index 3b4c2bfa..2320d435 100644 --- a/src/main/java/gollorum/signpost/util/SignBaseInfo.java +++ b/src/main/java/gollorum/signpost/util/SignBaseInfo.java @@ -1,43 +1,44 @@ package gollorum.signpost.util; -import gollorum.signpost.blocks.PostPost; import net.minecraft.util.ResourceLocation; +import gollorum.signpost.blocks.PostPost; + public abstract class SignBaseInfo implements Paintable { - public ResourceLocation postPaint; - public boolean awaitingPaint = false; - public Paintable paintObject = null; - - @Override - public ResourceLocation getTexture() { - return postPaint; - } - - @Override - public void setTexture(ResourceLocation texture) { - postPaint = texture; - } - - @Override - public ResourceLocation getDefaultBiomeTexture(BiomeContainer biome) { - if(biome == null || biome.getBiome() == null) { - return PostPost.PostType.OAK.resLocMain; - } - if(biome.getBiome().biomeName.contains("Plains")){ - return PostPost.PostType.OAK.resLocMain; - }else if(biome.getBiome().biomeName.contains("Desert")){ - return new ResourceLocation("textures/blocks/cobblestone.png"); - }else if(biome.getBiome().biomeName.contains("Taiga")){ - return PostPost.PostType.SPRUCE.resLocMain; - }else if(biome.getBiome().biomeName.contains("Savanna")){ - return PostPost.PostType.ACACIA.resLocMain; - }else{ - return PostPost.PostType.OAK.resLocMain; - } - } - - public void setTextureToBiomeDefault(BiomeContainer biome){ - setTexture(getDefaultBiomeTexture(biome)); - } + public ResourceLocation postPaint; + public boolean awaitingPaint = false; + public Paintable paintObject = null; + + @Override + public ResourceLocation getTexture() { + return postPaint; + } + + @Override + public void setTexture(ResourceLocation texture) { + postPaint = texture; + } + + @Override + public ResourceLocation getDefaultBiomeTexture(BiomeContainer biome) { + if (biome == null || biome.getBiome() == null) { + return PostPost.PostType.OAK.resLocMain; + } + if (biome.getBiome().biomeName.contains("Plains")) { + return PostPost.PostType.OAK.resLocMain; + } else if (biome.getBiome().biomeName.contains("Desert")) { + return new ResourceLocation("textures/blocks/cobblestone.png"); + } else if (biome.getBiome().biomeName.contains("Taiga")) { + return PostPost.PostType.SPRUCE.resLocMain; + } else if (biome.getBiome().biomeName.contains("Savanna")) { + return PostPost.PostType.ACACIA.resLocMain; + } else { + return PostPost.PostType.OAK.resLocMain; + } + } + + public void setTextureToBiomeDefault(BiomeContainer biome) { + setTexture(getDefaultBiomeTexture(biome)); + } } diff --git a/src/main/java/gollorum/signpost/util/StonedHashSet.java b/src/main/java/gollorum/signpost/util/StonedHashSet.java index cb1e6bc2..c160760a 100644 --- a/src/main/java/gollorum/signpost/util/StonedHashSet.java +++ b/src/main/java/gollorum/signpost/util/StonedHashSet.java @@ -1,109 +1,111 @@ package gollorum.signpost.util; -import gollorum.signpost.management.PostHandler; - import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.function.Function; +import gollorum.signpost.management.PostHandler; + public class StonedHashSet extends HashSet { - public BaseInfo getByPos(MyBlockPos pos){ - for(BaseInfo now: this){ - if(now.blockPosition.equals(pos)){ - return now; - } - } - return null; - } + public BaseInfo getByPos(MyBlockPos pos) { + for (BaseInfo now : this) { + if (now.blockPosition.equals(pos)) { + return now; + } + } + return null; + } + + public BaseInfo getByName(String waystoneName) { + for (BaseInfo now : this) { + if (now.getName() + .equals(waystoneName)) { + return now; + } + } + return null; + } + + public boolean nameTaken(String name) { + if (name == null) { + return false; + } + for (BaseInfo now : this) { + if (name.equals(now.getName())) { + return true; + } + } + return false; + } + + @Override + public boolean add(BaseInfo now) { + boolean nowFound = false; + for (BaseInfo org : this) { + if (org.update(now)) { + nowFound = true; + break; + } + } + if (!nowFound) { + nowFound = super.add(now); + } + return nowFound; + } + + public boolean addAll(HashSet names) { + boolean ret = false; + for (String nown : names) { + for (BaseInfo nowws : PostHandler.getAllWaystones()) { + if (nowws.getName() + .equals(nown)) { + add(nowws); + ret = true; + } + } + } + return ret; + } + + public boolean removeByPos(MyBlockPos pos) { + BaseInfo toDelete = getByPos(pos); + if (toDelete == null) { + return true; + } else { + return super.remove(toDelete); + } + } - public BaseInfo getByName(String waystoneName) { - for(BaseInfo now: this){ - if(now.getName().equals(waystoneName)){ - return now; - } - } - return null; - } - - public boolean nameTaken(String name){ - if(name==null){ - return false; - } - for(BaseInfo now:this){ - if(name.equals(now.getName())){ - return true; - } - } - return false; - } - - @Override - public boolean add(BaseInfo now){ - boolean nowFound = false; - for(BaseInfo org: this){ - if(org.update(now)){ - nowFound = true; - break; - } - } - if(!nowFound){ - nowFound = super.add(now); - } - return nowFound; - } - - public boolean addAll(HashSet names){ - boolean ret = false; - for(String nown: names){ - for(BaseInfo nowws: PostHandler.getAllWaystones()){ - if(nowws.getName().equals(nown)){ - add(nowws); - ret = true; - } - } - } - return ret; - } - - public boolean removeByPos(MyBlockPos pos){ - BaseInfo toDelete = getByPos(pos); - if(toDelete==null){ - return true; - }else{ - return super.remove(toDelete); - } - } - - @Override - public boolean remove(Object obj) { - if(!(obj instanceof BaseInfo)){ - return false; - } - BaseInfo toDelete = (BaseInfo)obj; - for(BaseInfo now: this){ - if(now.equals(toDelete)){ - toDelete = now; - break; - } - } - return super.remove(toDelete); - } + @Override + public boolean remove(Object obj) { + if (!(obj instanceof BaseInfo)) { + return false; + } + BaseInfo toDelete = (BaseInfo) obj; + for (BaseInfo now : this) { + if (now.equals(toDelete)) { + toDelete = now; + break; + } + } + return super.remove(toDelete); + } - public Collection positions() { - Set positions = new java.util.HashSet(size()); - for(BaseInfo now: this){ - positions.add(now.blockPosition); - } - return positions; - } + public Collection positions() { + Set positions = new java.util.HashSet(size()); + for (BaseInfo now : this) { + positions.add(now.blockPosition); + } + return positions; + } - public Collection select(Function mapping){ - HashSet ret = new HashSet(); - for(BaseInfo info: this) { - ret.add(mapping.apply(info)); - } - return ret; - } + public Collection select(Function mapping) { + HashSet ret = new HashSet(); + for (BaseInfo info : this) { + ret.add(mapping.apply(info)); + } + return ret; + } } diff --git a/src/main/java/gollorum/signpost/util/StringSet.java b/src/main/java/gollorum/signpost/util/StringSet.java index 7cb0989e..56d6f314 100644 --- a/src/main/java/gollorum/signpost/util/StringSet.java +++ b/src/main/java/gollorum/signpost/util/StringSet.java @@ -4,25 +4,25 @@ public class StringSet extends HashSet { - @Override - public boolean add(String str) { - for (String now : this) { - if (now.equals(str)){ - return false; - } - } - super.add(str); - return true; - } + @Override + public boolean add(String str) { + for (String now : this) { + if (now.equals(str)) { + return false; + } + } + super.add(str); + return true; + } - @Override - public boolean contains(Object str) { - for (String now : this) { - if (str.equals(now)) { - return true; - } - } - return false; - } + @Override + public boolean contains(Object str) { + for (String now : this) { + if (str.equals(now)) { + return true; + } + } + return false; + } } diff --git a/src/main/java/gollorum/signpost/util/TextureHelper.java b/src/main/java/gollorum/signpost/util/TextureHelper.java index 11b3a583..74a64cc4 100644 --- a/src/main/java/gollorum/signpost/util/TextureHelper.java +++ b/src/main/java/gollorum/signpost/util/TextureHelper.java @@ -1,8 +1,5 @@ package gollorum.signpost.util; -import cpw.mods.fml.client.FMLClientHandler; -import gollorum.signpost.blocks.SuperPostPost; -import gollorum.signpost.blocks.tiles.SuperPostPostTile; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; @@ -11,42 +8,53 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; +import cpw.mods.fml.client.FMLClientHandler; +import gollorum.signpost.blocks.SuperPostPost; +import gollorum.signpost.blocks.tiles.SuperPostPostTile; + public class TextureHelper { - private static TextureHelper INSTANCE; - - private TextureHelper(){} - - public static TextureHelper instance(){ - return INSTANCE==null? INSTANCE=new TextureHelper(): INSTANCE; - } - - public ResourceLocation getHeldBlockTexture(EntityPlayer player, World worldIn, int x, int y, int z){ - try{ - Vec3 look = player.getLookVec(); - int side = getFacingFromVector((float)-look.xCoord, (float)-look.yCoord, (float)-look.zCoord); - - Block block = Block.getBlockFromItem(player.getHeldItem().getItem()); - String textureName = block.getBlockTextureFromSide(side).getIconName(); - String resourceName = textureNameToResourceName(textureName); - - ResourceLocation ret = new ResourceLocation(resourceName); - - FMLClientHandler.instance().getClient().getResourceManager().getResource(ret); - return ret; - }catch(Exception e){return null;} - } - - public static int getFacingFromVector(float x, float y, float z){ + private static TextureHelper INSTANCE; + + private TextureHelper() {} + + public static TextureHelper instance() { + return INSTANCE == null ? INSTANCE = new TextureHelper() : INSTANCE; + } + + public ResourceLocation getHeldBlockTexture(EntityPlayer player, World worldIn, int x, int y, int z) { + try { + Vec3 look = player.getLookVec(); + int side = getFacingFromVector((float) -look.xCoord, (float) -look.yCoord, (float) -look.zCoord); + + Block block = Block.getBlockFromItem( + player.getHeldItem() + .getItem()); + String textureName = block.getBlockTextureFromSide(side) + .getIconName(); + String resourceName = textureNameToResourceName(textureName); + + ResourceLocation ret = new ResourceLocation(resourceName); + + FMLClientHandler.instance() + .getClient() + .getResourceManager() + .getResource(ret); + return ret; + } catch (Exception e) { + return null; + } + } + + public static int getFacingFromVector(float x, float y, float z) { EnumFacing enumfacing = EnumFacing.NORTH; float f = Float.MIN_VALUE; - for (EnumFacing enumfacing1 : EnumFacing.values()) - { - float f1 = x * (float)enumfacing1.getFrontOffsetX() + y * (float)enumfacing1.getFrontOffsetY() + z * (float)enumfacing1.getFrontOffsetZ(); + for (EnumFacing enumfacing1 : EnumFacing.values()) { + float f1 = x * (float) enumfacing1.getFrontOffsetX() + y * (float) enumfacing1.getFrontOffsetY() + + z * (float) enumfacing1.getFrontOffsetZ(); - if (f1 > f) - { + if (f1 > f) { f = f1; enumfacing = enumfacing1; } @@ -54,52 +62,56 @@ public static int getFacingFromVector(float x, float y, float z){ return enumfacing.ordinal(); } - - private String textureNameToResourceName(String textureName){ - if(textureName.equals("missingno")){ - return null; - } - String[] split; - if(textureName.contains(":")){ - split = textureName.split(":"); - if(split.length!=2){ - return null; - } - }else{ - split = new String[2]; - split[0] = "minecraft"; - split[1] = textureName; - } - if(!split[1].startsWith("textures/blocks/")){ - if(!split[1].startsWith("blocks/")){ - split[1] = "blocks/"+split[1]; - } - split[1] = "textures/"+split[1]; - } - if(!endsWithIgnoreCase(split[1], ".png")){ - split[1] += ".png"; - } - return split[0]+":"+split[1]; - } - - public boolean setTexture(int x, int y, int z){ - EntityPlayer player = FMLClientHandler.instance().getClient().thePlayer; - World world = FMLClientHandler.instance().getClient().theWorld; - ResourceLocation texture = getHeldBlockTexture(player, world, x, y, z); - TileEntity tileEntity = world.getTileEntity(x, y, z); - if(texture==null ||! (tileEntity instanceof SuperPostPostTile)){ - return false; - }else{ - SuperPostPostTile superTile = (SuperPostPostTile) tileEntity; - superTile.getPaintObject().setTexture(texture); - superTile.setPaintObject(null); - superTile.setAwaitingPaint(false); - ((SuperPostPost)superTile.getBlockType()).sendPostBasesToServer(superTile); - return true; - } - } - - private static boolean endsWithIgnoreCase(String str1, String str2){ - return str1.length() T find(List list, Predicate where) { - for(T t: list){ - if(where.test(t)) return t; + for (T t : list) { + if (where.test(t)) return t; } return null; } - public static Collection where(Collection collection, Predicate condition){ + public static Collection where(Collection collection, Predicate condition) { List ret = new ArrayList<>(); - for(T t: collection) { - if(condition.test(t)) { + for (T t : collection) { + if (condition.test(t)) { ret.add(t); } } return ret; } - public static Map mutateOr( - Map map, - BiPredicate condition, - BiFunction mutation, - BiConsumer elseAction - ){ + public static Map mutateOr(Map map, BiPredicate condition, + BiFunction mutation, BiConsumer elseAction) { Map ret = new HashMap<>(); - for(Map.Entry entry: map.entrySet()) { + for (Map.Entry entry : map.entrySet()) { Key key = entry.getKey(); Value value = entry.getValue(); - if(condition.test(key, value)) { + if (condition.test(key, value)) { ret.put(key, mutation.apply(key, value)); } else { elseAction.accept(key, value); diff --git a/src/main/java/gollorum/signpost/util/math/MatrixD.java b/src/main/java/gollorum/signpost/util/math/MatrixD.java index 7c0fc9d2..ade02658 100644 --- a/src/main/java/gollorum/signpost/util/math/MatrixD.java +++ b/src/main/java/gollorum/signpost/util/math/MatrixD.java @@ -3,174 +3,175 @@ import java.util.Collection; public class MatrixD { - - protected double[][] values; - protected int rows; - protected int columns; - - public MatrixD(int i, int j){ - values = new double[i][j]; - rows = i; - columns = j; - } - - public MatrixD(double[][] values){ - this.values = values.clone(); - repair(); - } - - public MatrixD(Collection> values){ - this.values = new double[values.size()][]; - int i=0; - for(Collection now: values){ - this.columns = Math.max(columns, now.size()); - this.values[i] = new double[columns]; - int j=0; - for(Double val: now){ - this.values[i][j] = val.doubleValue(); - j++; - } - i++; - } - repair(); - } - - public double get(int i, int j){ - checkBounds(i, j); - return values[i][j]; - } - - public void set(double value, int i, int j){ - checkBounds(i, j); - values[i][j] = value; - } - - public void gaussAlgorithm(){ - int offset = 0; - for(int i=0; i=rows){ - break; - } - sortColumnBy0(i, offset); - if(!test0(values[offset][i])){ - divideRow(offset, values[offset][i]); - for(int j=0; j1||(n0c==0&&!test0(values[row][columns-1]))); - } - - private void substractRows(int targetRow, int otherRow, double factor){ - for(int i=0; i=offset; j--){ - if(test0(values[j][col])){ - swapRows(j, row--); - } - } - } - - private void repair(){ - rows = values.length; - for(double[] now: values){ - columns = Math.max(columns, now.length); - } - for(int i=0; i=rows ||j>=columns){ - throw new IndexOutOfBoundsException("Out of matrix bounds: "+i+"|"+j+" ("+rows+"x"+columns+")"); - } - } - - private void swapRows(int i, int j){ - double[] org = values[i]; - values[i] = values[j]; - values[j] = org; - } - - public void print(){ - for(double[] row: values){ - System.out.print("|"); - for(double x: row){ - System.out.print(x+" "); - } - System.out.print("|"); - System.out.println(); - } - } - - private boolean test0(double var){ - return -0.00000000001> values) { + this.values = new double[values.size()][]; + int i = 0; + for (Collection now : values) { + this.columns = Math.max(columns, now.size()); + this.values[i] = new double[columns]; + int j = 0; + for (Double val : now) { + this.values[i][j] = val.doubleValue(); + j++; + } + i++; + } + repair(); + } + + public double get(int i, int j) { + checkBounds(i, j); + return values[i][j]; + } + + public void set(double value, int i, int j) { + checkBounds(i, j); + values[i][j] = value; + } + + public void gaussAlgorithm() { + int offset = 0; + for (int i = 0; i < columns; i++) { + if (offset >= rows) { + break; + } + sortColumnBy0(i, offset); + if (!test0(values[offset][i])) { + divideRow(offset, values[offset][i]); + for (int j = 0; j < offset; j++) { + substractRows(j, offset, values[j][i]); + } + for (int j = offset + 1; j < rows; j++) { + substractRows(j, offset, values[j][i]); + } + offset++; + } else { + values[offset][i] = 0; + } + } + } + + public boolean check() { + boolean ret = true; + for (int i = 0; i < rows; i++) { + ret = ret && checkRow(i); + } + return ret; + } + + private boolean checkRow(int row) { + int n0c = 0; + for (int i = 0; i < columns - 1; i++) { + if (!test0(values[row][i])) { + n0c++; + } else { + values[row][i] = 0; + } + } + return !(n0c > 1 || (n0c == 0 && !test0(values[row][columns - 1]))); + } + + private void substractRows(int targetRow, int otherRow, double factor) { + for (int i = 0; i < columns; i++) { + values[targetRow][i] -= values[otherRow][i] * factor; + } + } + + private void divideRow(int row, double divident) { + for (int i = 0; i < columns; i++) { + values[row][i] /= divident; + } + } + + private void sortColumnBy0(int col, int offset) { + int row = rows - 1; + for (int j = row; j >= offset; j--) { + if (test0(values[j][col])) { + swapRows(j, row--); + } + } + } + + private void repair() { + rows = values.length; + for (double[] now : values) { + columns = Math.max(columns, now.length); + } + for (int i = 0; i < rows; i++) { + if (values[i].length != columns) { + double[] vals = new double[columns]; + for (int j = 0; j < values[i].length; j++) { + vals[j] = values[i][j]; + } + values[i] = vals; + } + } + } + + private void checkBounds(int i, int j) { + if (i < 0 || j < 0 || i >= rows || j >= columns) { + throw new IndexOutOfBoundsException( + "Out of matrix bounds: " + i + "|" + j + " (" + rows + "x" + columns + ")"); + } + } + + private void swapRows(int i, int j) { + double[] org = values[i]; + values[i] = values[j]; + values[j] = org; + } + + public void print() { + for (double[] row : values) { + System.out.print("|"); + for (double x : row) { + System.out.print(x + " "); + } + System.out.print("|"); + System.out.println(); + } + } + + private boolean test0(double var) { + return -0.00000000001 < var && var < 0.00000000001; + } + + // Unused + + private void addRows(int targetRow, int otherRow, double factor) { + for (int i = 0; i < columns; i++) { + values[targetRow][i] += values[otherRow][i] * factor; + } + } + + private void multiplyRow(int row, double factor) { + for (int i = 0; i < columns; i++) { + values[row][i] *= factor; + } + } + + private void swapColumns(int i, int j) { + for (int k = 0; k < rows; k++) { + double val = values[k][i]; + values[k][i] = values[k][j]; + values[k][j] = val; + } + } } diff --git a/src/main/java/gollorum/signpost/util/math/tracking/Body.java b/src/main/java/gollorum/signpost/util/math/tracking/Body.java index 2c80b36f..6afb2e9e 100644 --- a/src/main/java/gollorum/signpost/util/math/tracking/Body.java +++ b/src/main/java/gollorum/signpost/util/math/tracking/Body.java @@ -2,25 +2,27 @@ import java.util.ArrayList; -public class Body extends ArrayList{ +public class Body extends ArrayList { - public Body(int i) {super(i);} + public Body(int i) { + super(i); + } - public Intersect traceLine(DDDVector start, DDDVector end, boolean unlimited){ - if(this.size()==0){ - return new Intersect(false, null); - } - Intersect nearest = new Intersect(false, null); - double d = Double.MAX_VALUE; - for(Rectangle now: this){ - Intersect inter = now.traceLine(start, end, unlimited); - double dn; - if(inter.exists && (dn = inter.pos.sqrDistance(start))0?180:0))); - } - - protected boolean angleTooLarge(double calcRot, double optimalRot) { - double difference = Math.abs(optimalRot - calcRot) % (Math.PI * 2); - double twisted = Math.abs(difference - Math.PI); - return twisted < Math.PI*0.5; - } - -} \ No newline at end of file + + protected MyBlockPos villageLocation; + + protected LibraryHelper(MyBlockPos villageLocation) { + this.villageLocation = villageLocation; + } + + protected BaseInfo getBaseInfo(MyBlockPos stoneLocation) { + return PostHandler.getNativeWaystones() + .getByPos(stoneLocation); + } + + protected int compareClosest(MyBlockPos pos1, MyBlockPos pos2, MyBlockPos target) { + return Double.compare(pos1.distance(target), pos2.distance(target)); + } + + protected double calcRot(MyBlockPos pos1, MyBlockPos pos2) { + int dx = pos2.x - pos1.x; + int dz = pos2.z - pos1.z; + return (DDDVector.genAngle(dx, dz) + Math.toRadians(90 + (dx < 0 && dz > 0 ? 180 : 0))); + } + + protected boolean angleTooLarge(double calcRot, double optimalRot) { + double difference = Math.abs(optimalRot - calcRot) % (Math.PI * 2); + double twisted = Math.abs(difference - Math.PI); + return twisted < Math.PI * 0.5; + } + +} diff --git a/src/main/java/gollorum/signpost/worldGen/villages/LibrarySignpostHelper.java b/src/main/java/gollorum/signpost/worldGen/villages/LibrarySignpostHelper.java index aa4b08a6..66d59b3d 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/LibrarySignpostHelper.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/LibrarySignpostHelper.java @@ -1,90 +1,98 @@ package gollorum.signpost.worldGen.villages; +import java.util.*; +import java.util.function.Consumer; + import gollorum.signpost.blocks.SuperPostPost; import gollorum.signpost.management.ClientConfigStorage; import gollorum.signpost.management.PostHandler; import gollorum.signpost.util.*; import gollorum.signpost.util.code.MinecraftIndependent; -import java.util.*; -import java.util.function.Consumer; - @MinecraftIndependent class LibrarySignpostHelper extends LibraryHelper { - private static final Map takenWaystones = new HashMap(); - - private MyBlockPos signpostLocation; - private Map villageWaystones; - LibrarySignpostHelper(MyBlockPos villageLocation, MyBlockPos signpostLocation, Map villageWaystones) { - super(villageLocation); - this.signpostLocation = signpostLocation; - this.villageWaystones = villageWaystones; - if (!takenWaystones.containsKey(villageLocation)) { - takenWaystones.put(villageLocation, new MyBlockPosSet()); - } - } + private static final Map takenWaystones = new HashMap(); + + private MyBlockPos signpostLocation; + private Map villageWaystones; + + LibrarySignpostHelper(MyBlockPos villageLocation, MyBlockPos signpostLocation, + Map villageWaystones) { + super(villageLocation); + this.signpostLocation = signpostLocation; + this.villageWaystones = villageWaystones; + if (!takenWaystones.containsKey(villageLocation)) { + takenWaystones.put(villageLocation, new MyBlockPosSet()); + } + } + + void enscribeNewSign(double optimalRot) { + List signs = PostHandler.getSigns(signpostLocation); + Paintable post = PostHandler.getPost(signpostLocation); + final BiomeContainer biome = signpostLocation.getBiome(); + if (!(post == null || biome == null)) { + post.setTextureToBiomeDefault(biome); + } + post = PostHandler.getPost(signpostLocation.getBelow()); + if (!(post == null || biome == null)) { + post.setTextureToBiomeDefault(biome); + } + if (biome != null) { + signs.forEach(new Consumer() { + + @Override + public void accept(Sign sign) { + sign.setTextureToBiomeDefault(biome); + } + }); + } + List closestWaystones = getClosestWaystones(signs.size()); + for (int i = 0; i < signs.size() && i < closestWaystones.size(); i++) { + if (signs.get(i).base != null) { + continue; + } + signs.get(i).base = getBaseInfo(closestWaystones.get(i)); + takenWaystones.get(villageLocation) + .add(closestWaystones.get(i)); + signs.get(i).point = true; + if (angleTooLarge(calcRot(signpostLocation, closestWaystones.get(i)), optimalRot)) { + signs.get(i).flip = true; + } + } + SuperPostPost.updateServer(signpostLocation); + } + + private List getClosestWaystones(int size) { + List waystones = getAllowedWaystones(); + waystones.sort(new Comparator() { - void enscribeNewSign(double optimalRot) { - List signs = PostHandler.getSigns(signpostLocation); - Paintable post = PostHandler.getPost(signpostLocation); - final BiomeContainer biome = signpostLocation.getBiome(); - if(!(post == null || biome == null)){ - post.setTextureToBiomeDefault(biome); - } - post = PostHandler.getPost(signpostLocation.getBelow()); - if(!(post == null || biome == null)){ - post.setTextureToBiomeDefault(biome); - } - if(biome!=null){ - signs.forEach(new Consumer() { - @Override public void accept(Sign sign) { - sign.setTextureToBiomeDefault(biome); - } - }); - } - List closestWaystones = getClosestWaystones(signs.size()); - for(int i=0; i getClosestWaystones(int size) { - List waystones = getAllowedWaystones(); - waystones.sort(new Comparator(){ - @Override - public int compare(MyBlockPos pos1, MyBlockPos pos2) { - return compareClosest(pos1, pos2, signpostLocation); - } - }); - MyBlockPos myPos = this.villageWaystones.get(villageLocation); - for(MyBlockPos now: waystones){ - if(now.equals(myPos)){ - myPos = now; - break; - } - } - waystones.remove(myPos); - return waystones; - } - - private List getAllowedWaystones() { - List ret = new LinkedList(); - if(ClientConfigStorage.INSTANCE.isOnlyVillageTargets()){ - ret.addAll(villageWaystones.values()); - }else{ - ret.addAll(PostHandler.getNativeWaystones().positions()); - } - ret.removeAll(takenWaystones.get(villageLocation)); - return ret; - } + private List getAllowedWaystones() { + List ret = new LinkedList(); + if (ClientConfigStorage.INSTANCE.isOnlyVillageTargets()) { + ret.addAll(villageWaystones.values()); + } else { + ret.addAll( + PostHandler.getNativeWaystones() + .positions()); + } + ret.removeAll(takenWaystones.get(villageLocation)); + return ret; + } } diff --git a/src/main/java/gollorum/signpost/worldGen/villages/LibraryWaystoneHelper.java b/src/main/java/gollorum/signpost/worldGen/villages/LibraryWaystoneHelper.java index 0b002786..ba575dde 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/LibraryWaystoneHelper.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/LibraryWaystoneHelper.java @@ -1,5 +1,8 @@ package gollorum.signpost.worldGen.villages; +import java.util.*; +import java.util.Map.Entry; + import gollorum.signpost.SPEventHandler; import gollorum.signpost.blocks.SuperPostPost; import gollorum.signpost.blocks.tiles.SuperPostPostTile; @@ -8,153 +11,172 @@ import gollorum.signpost.util.Sign; import gollorum.signpost.util.code.MinecraftIndependent; -import java.util.*; -import java.util.Map.Entry; - @MinecraftIndependent class LibraryWaystoneHelper extends LibraryHelper { - private MyBlockPos waystoneLocation; - private Map> villagePosts; - - LibraryWaystoneHelper(MyBlockPos villageLocation, Map> villagePosts, - MyBlockPos waystoneLocation) { - super(villageLocation); - this.villagePosts = villagePosts; - this.waystoneLocation = waystoneLocation; - } - - void enscribeEmptySign() { - SPEventHandler.scheduleTask(new BoolRun() { - boolean go = false; - @Override - public boolean run() { - if (!go) { - go = true; - return false; - } - try { - final Set posts = fetchOtherVillagesPosts(); - final SignChooser.SingeEmptySign emptySign = new SignChooser(posts).getBestSign(); - if (emptySign != null) { - final MyBlockPos pos = emptySign.post.getTopSignPosition(); - final Sign sign = SuperPostPost.getSuperTile(pos).getEmptySigns().get(0); - if (pos.getTile() instanceof SuperPostPostTile && ((SuperPostPostTile) pos.getTile()).isLoading()) { - return false; - } else { - sign.base = getBaseInfo(waystoneLocation); - sign.point = true; - if (angleTooLarge(calcRot(pos, waystoneLocation), emptySign.post.desiredRotation)) { - emptySign.sign.flip = true; - } - SuperPostPost.updateServer(pos); - return true; - } - } else { - return true; - } - } catch(Exception e) {return true;} - } - }); - } - - private Set fetchOtherVillagesPosts() { - Set posts = new HashSet<>(); - for (Entry> entry : villagePosts.entrySet()) { - if (!(entry.getKey().equals(villageLocation) || containsMeAsTarget(entry.getValue()))) { - posts.addAll(entry.getValue()); - } - } - return posts; - } - - private boolean containsMeAsTarget(Set posts) { - for(VillagePost post : posts) { - for(Sign sign : post.getSigns()) { - if(sign != null && sign.isValid() && sign.base != null && sign.base.blockPosition != null && sign.base.blockPosition.equals(waystoneLocation)){ - return true; - } - } - } - return false; - } - - private class SignChooser { - private List signs = new LinkedList<>(); - - public SignChooser(Set posts) { - fetchSigns(posts); - } - - public SingeEmptySign getBestSign() { - sort(); - if (signs.size() > 0) { - for(VillageSign sign : signs) { - if(sign == null || sign.post == null) continue; - List postSigns = sign.signs; - if(postSigns.size() == 0) continue; - final MyBlockPos pos = sign.post.getTopSignPosition(); - if (pos != null && SuperPostPost.getSuperTile(pos) != null) { - try { - SuperPostPost.getSuperTile(pos).getEmptySigns().get(0); - return new SingeEmptySign(postSigns.get(0), sign.post); - } catch(Exception e) {} - } - } - } - return null; - } - - private void fetchSigns(Set posts) { - for (VillagePost post : posts) { - List signs = getEmptySigns(post); - if (!signs.isEmpty()) { - this.signs.add(new VillageSign(new VillagePost(post.getTopSignPosition(), post.desiredRotation), signs)); - } - } - } - - private void sort() { - sortDistance(); - sortSignCount(); - } - - private void sortDistance() { - signs.sort((sign1, sign2) -> compareClosest(sign1.post.getTopSignPosition(), sign2.post.getTopSignPosition(), villageLocation)); - } - - private void sortSignCount() { - signs.sort((sign1, sign2) -> new Integer(sign2.signs.size()).compareTo(sign1.signs.size())); - } - - private List getEmptySigns(VillagePost post) { - List signs = post.getSigns(); - List ret = new LinkedList(); - for (Sign now : signs) { - if (now.base == null || !now.base.hasName()) { - ret.add(now); - } - } - return ret; - } - - private class VillageSign { - public VillagePost post; - public List signs; - - public VillageSign(VillagePost post, List signs) { - this.post = post; - this.signs = signs; - } - } - - public class SingeEmptySign { - public Sign sign; - public VillagePost post; - - public SingeEmptySign(Sign sign, VillagePost post) { - this.sign = sign; - this.post = post; - } - } - } + + private MyBlockPos waystoneLocation; + private Map> villagePosts; + + LibraryWaystoneHelper(MyBlockPos villageLocation, Map> villagePosts, + MyBlockPos waystoneLocation) { + super(villageLocation); + this.villagePosts = villagePosts; + this.waystoneLocation = waystoneLocation; + } + + void enscribeEmptySign() { + SPEventHandler.scheduleTask(new BoolRun() { + + boolean go = false; + + @Override + public boolean run() { + if (!go) { + go = true; + return false; + } + try { + final Set posts = fetchOtherVillagesPosts(); + final SignChooser.SingeEmptySign emptySign = new SignChooser(posts).getBestSign(); + if (emptySign != null) { + final MyBlockPos pos = emptySign.post.getTopSignPosition(); + final Sign sign = SuperPostPost.getSuperTile(pos) + .getEmptySigns() + .get(0); + if (pos.getTile() instanceof SuperPostPostTile + && ((SuperPostPostTile) pos.getTile()).isLoading()) { + return false; + } else { + sign.base = getBaseInfo(waystoneLocation); + sign.point = true; + if (angleTooLarge(calcRot(pos, waystoneLocation), emptySign.post.desiredRotation)) { + emptySign.sign.flip = true; + } + SuperPostPost.updateServer(pos); + return true; + } + } else { + return true; + } + } catch (Exception e) { + return true; + } + } + }); + } + + private Set fetchOtherVillagesPosts() { + Set posts = new HashSet<>(); + for (Entry> entry : villagePosts.entrySet()) { + if (!(entry.getKey() + .equals(villageLocation) || containsMeAsTarget(entry.getValue()))) { + posts.addAll(entry.getValue()); + } + } + return posts; + } + + private boolean containsMeAsTarget(Set posts) { + for (VillagePost post : posts) { + for (Sign sign : post.getSigns()) { + if (sign != null && sign.isValid() + && sign.base != null + && sign.base.blockPosition != null + && sign.base.blockPosition.equals(waystoneLocation)) { + return true; + } + } + } + return false; + } + + private class SignChooser { + + private List signs = new LinkedList<>(); + + public SignChooser(Set posts) { + fetchSigns(posts); + } + + public SingeEmptySign getBestSign() { + sort(); + if (signs.size() > 0) { + for (VillageSign sign : signs) { + if (sign == null || sign.post == null) continue; + List postSigns = sign.signs; + if (postSigns.size() == 0) continue; + final MyBlockPos pos = sign.post.getTopSignPosition(); + if (pos != null && SuperPostPost.getSuperTile(pos) != null) { + try { + SuperPostPost.getSuperTile(pos) + .getEmptySigns() + .get(0); + return new SingeEmptySign(postSigns.get(0), sign.post); + } catch (Exception e) {} + } + } + } + return null; + } + + private void fetchSigns(Set posts) { + for (VillagePost post : posts) { + List signs = getEmptySigns(post); + if (!signs.isEmpty()) { + this.signs + .add(new VillageSign(new VillagePost(post.getTopSignPosition(), post.desiredRotation), signs)); + } + } + } + + private void sort() { + sortDistance(); + sortSignCount(); + } + + private void sortDistance() { + signs.sort( + (sign1, sign2) -> compareClosest( + sign1.post.getTopSignPosition(), + sign2.post.getTopSignPosition(), + villageLocation)); + } + + private void sortSignCount() { + signs.sort((sign1, sign2) -> new Integer(sign2.signs.size()).compareTo(sign1.signs.size())); + } + + private List getEmptySigns(VillagePost post) { + List signs = post.getSigns(); + List ret = new LinkedList(); + for (Sign now : signs) { + if (now.base == null || !now.base.hasName()) { + ret.add(now); + } + } + return ret; + } + + private class VillageSign { + + public VillagePost post; + public List signs; + + public VillageSign(VillagePost post, List signs) { + this.post = post; + this.signs = signs; + } + } + + public class SingeEmptySign { + + public Sign sign; + public VillagePost post; + + public SingeEmptySign(Sign sign, VillagePost post) { + this.sign = sign; + this.post = post; + } + } + } } diff --git a/src/main/java/gollorum/signpost/worldGen/villages/NameLibrary.java b/src/main/java/gollorum/signpost/worldGen/villages/NameLibrary.java index 8dd8a7d6..5559a8fa 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/NameLibrary.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/NameLibrary.java @@ -13,111 +13,119 @@ import org.apache.commons.io.IOUtils; import gollorum.signpost.Signpost; +import gollorum.signpost.Tags; import gollorum.signpost.management.PostHandler; import gollorum.signpost.util.code.MinecraftIndependent; @MinecraftIndependent public class NameLibrary { - - private static NameLibrary INSTANCE; - - private static final int MAX_TRIES = 50; - - public static NameLibrary getInstance(){ - return INSTANCE; - } - - private final List first; - private final List second; - private final List third; - - public static void init(String configFolder){ - try{ - INSTANCE = new NameLibrary(configFolder); - }catch(Exception e){ - e.printStackTrace(); - } - } - - private NameLibrary(String configFolder){ - assureFileExists(configFolder, "first"); - this.first = readNameParts(configFolder, "first"); - assureFileExists(configFolder, "second"); - this.second = readNameParts(configFolder, "second"); - assureFileExists(configFolder, "third"); - this.third = readNameParts(configFolder, "third"); - } - - private File getFile(String folder, String index) { - return new File(folder, "villagenames"+index+".txt"); - } - - private void assureFileExists(String configFolder, String index) { - try { - if(!getFile(configFolder, index).exists()){ - copyFile(configFolder, index); - } - } catch (IOException e) {e.printStackTrace();} - } - - private void copyFile(String configFolder, String index) throws IOException { - InputStream in; - in = Signpost.proxy.getResourceInputStream(Signpost.MODID+":worldgen/villagenames"+index+".txt"); - if(in == null){ - in = Signpost.proxy.getResourceInputStream("/assets/signpost/worldgen/villagenames"+index+".txt"); - } - OutputStream out = new FileOutputStream(getFile(configFolder, index)); - IOUtils.copy(in, out); - in.close(); - out.close(); - } - - private List readNameParts(String configFolder, String index) { - List possibleNames = new LinkedList(); - try{ - possibleNames.addAll(Files.readAllLines(getFile(configFolder, index).toPath())); - }catch(IOException e){ - e.printStackTrace(); - } - return possibleNames; - } - - public boolean namesLeft(){ - for(int i=0; i first; + private final List second; + private final List third; + + public static void init(String configFolder) { + try { + INSTANCE = new NameLibrary(configFolder); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private NameLibrary(String configFolder) { + assureFileExists(configFolder, "first"); + this.first = readNameParts(configFolder, "first"); + assureFileExists(configFolder, "second"); + this.second = readNameParts(configFolder, "second"); + assureFileExists(configFolder, "third"); + this.third = readNameParts(configFolder, "third"); + } + + private File getFile(String folder, String index) { + return new File(folder, "villagenames" + index + ".txt"); + } + + private void assureFileExists(String configFolder, String index) { + try { + if (!getFile(configFolder, index).exists()) { + copyFile(configFolder, index); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void copyFile(String configFolder, String index) throws IOException { + InputStream in; + in = Signpost.proxy.getResourceInputStream(Tags.MODID + ":worldgen/villagenames" + index + ".txt"); + if (in == null) { + in = Signpost.proxy.getResourceInputStream("/assets/signpost/worldgen/villagenames" + index + ".txt"); + } + OutputStream out = new FileOutputStream(getFile(configFolder, index)); + IOUtils.copy(in, out); + in.close(); + out.close(); + } + + private List readNameParts(String configFolder, String index) { + List possibleNames = new LinkedList(); + try { + possibleNames.addAll(Files.readAllLines(getFile(configFolder, index).toPath())); + } catch (IOException e) { + e.printStackTrace(); + } + return possibleNames; + } + + public boolean namesLeft() { + for (int i = 0; i < first.size(); i++) { + for (int j = 0; j < second.size(); j++) { + for (int k = 0; k < third.size(); k++) { + if (!PostHandler.getNativeWaystones() + .nameTaken(getName(i, j, k))) { + return true; + } + } + } + } + return false; + } + + public String getName(Random random) { + for (int i = 0; i < MAX_TRIES; i++) { + String name = getName( + random.nextInt(first.size()), + random.nextInt(second.size()), + random.nextInt(third.size())); + if (!PostHandler.getNativeWaystones() + .nameTaken(name)) { + return name; + } + } + return null; + } + + private String getName(int i, int j, int k) { + String a = first.get(i); + String b = second.get(j); + String c = third.get(k); + if (a.endsWith(" ")) { + b = b.substring(0, 1) + .toUpperCase() + b.substring(1); + } + if (b.endsWith(" ")) { + c = c.substring(0, 1) + .toUpperCase() + c.substring(1); + } + return a + b + c; + } + } diff --git a/src/main/java/gollorum/signpost/worldGen/villages/VillageHandler.java b/src/main/java/gollorum/signpost/worldGen/villages/VillageHandler.java index 47c34328..e717c66e 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/VillageHandler.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/VillageHandler.java @@ -1,8 +1,6 @@ package gollorum.signpost.worldGen.villages; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; +import net.minecraft.world.gen.structure.MapGenStructureIO; import cpw.mods.fml.common.registry.VillagerRegistry; import gollorum.signpost.management.ClientConfigStorage; @@ -10,37 +8,38 @@ import gollorum.signpost.worldGen.villages.signpost.VillageComponentSignpost; import gollorum.signpost.worldGen.villages.waystone.VillageComponentWaystone; import gollorum.signpost.worldGen.villages.waystone.WaystoneVillageCreationHandler; -import net.minecraft.world.gen.structure.MapGenStructureIO; public class VillageHandler { - - private static final VillageHandler INSTANCE = new VillageHandler(); - - public static VillageHandler getInstance(){ - return INSTANCE; - } - - private VillageHandler(){} - - public void register(){ - if(ClientConfigStorage.INSTANCE.isDisableVillageGeneration()){ - return; - } - registerVillagePieces(); - registerHandlers(); - } - - private void registerVillagePieces(){ - registerVillagePiece("villageComponentSignpost", VillageComponentSignpost.class); - registerVillagePiece("villageComponentWaystone", VillageComponentWaystone.class); - } - - private void registerVillagePiece(String name, Class componentClass){ - MapGenStructureIO.func_143031_a(componentClass, name); - } - - private void registerHandlers() { - VillagerRegistry.instance().registerVillageCreationHandler(new SignpostVillageCreationHandler()); - VillagerRegistry.instance().registerVillageCreationHandler(new WaystoneVillageCreationHandler()); - } -} \ No newline at end of file + + private static final VillageHandler INSTANCE = new VillageHandler(); + + public static VillageHandler getInstance() { + return INSTANCE; + } + + private VillageHandler() {} + + public void register() { + if (ClientConfigStorage.INSTANCE.isDisableVillageGeneration()) { + return; + } + registerVillagePieces(); + registerHandlers(); + } + + private void registerVillagePieces() { + registerVillagePiece("villageComponentSignpost", VillageComponentSignpost.class); + registerVillagePiece("villageComponentWaystone", VillageComponentWaystone.class); + } + + private void registerVillagePiece(String name, Class componentClass) { + MapGenStructureIO.func_143031_a(componentClass, name); + } + + private void registerHandlers() { + VillagerRegistry.instance() + .registerVillageCreationHandler(new SignpostVillageCreationHandler()); + VillagerRegistry.instance() + .registerVillageCreationHandler(new WaystoneVillageCreationHandler()); + } +} diff --git a/src/main/java/gollorum/signpost/worldGen/villages/VillageLibrary.java b/src/main/java/gollorum/signpost/worldGen/villages/VillageLibrary.java index 983fdc80..2a2876ab 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/VillageLibrary.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/VillageLibrary.java @@ -1,141 +1,146 @@ package gollorum.signpost.worldGen.villages; -import gollorum.signpost.SPEventHandler; -import gollorum.signpost.util.MyBlockPos; -import gollorum.signpost.util.code.MinecraftDependent; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; - import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; + +import gollorum.signpost.SPEventHandler; +import gollorum.signpost.util.MyBlockPos; +import gollorum.signpost.util.code.MinecraftDependent; + @MinecraftDependent public class VillageLibrary { - private static VillageLibrary INSTANCE = new VillageLibrary(); - public static VillageLibrary getInstance(){ - return INSTANCE; - } - public static void init(){ - INSTANCE = new VillageLibrary(); - } - - private Map villageWaystones; - private Map> villagePosts; - - private VillageLibrary(){ - villageWaystones = new HashMap<>(); - villagePosts = new HashMap<>(); - } - - public void putWaystone(final MyBlockPos villageLocation, final MyBlockPos waystoneLocation){ - villageWaystones.put(villageLocation, waystoneLocation); - SPEventHandler.scheduleTask(() -> { - if(waystoneLocation.getTile() == null){ - return false; - }else{ - new LibraryWaystoneHelper(villageLocation, villagePosts, waystoneLocation).enscribeEmptySign(); - return true; - } - }); - } - - public void putSignpost(final MyBlockPos villageLocation, final MyBlockPos signpostLocation, final double optimalRot){ - Set villageSignposts = villagePosts.get(villageLocation); - if(villageSignposts == null){ - villageSignposts = new HashSet<>(); - villagePosts.put(villageLocation, villageSignposts); - } - villageSignposts.add(new VillagePost(signpostLocation, optimalRot)); - SPEventHandler.scheduleTask(() -> { - if(signpostLocation.getTile() == null){ - return false; - }else{ - new LibrarySignpostHelper(villageLocation, signpostLocation, villageWaystones).enscribeNewSign(optimalRot); - return true; - } - }); - } - - public void save(NBTTagCompound compound){ - compound.setTag("Waystones", saveWaystones()); - compound.setTag("Signposts", savePosts()); - } - - private NBTTagCompound saveWaystones() { - NBTTagCompound compound = new NBTTagCompound(); - compound.setInteger("WaystoneCount", villageWaystones.size()); - int i=0; - for(Entry now: villageWaystones.entrySet()){ - compound.setTag("Waystone"+(i++), saveWaystone(now.getKey(), now.getValue())); - } - return compound; - } - - private NBTBase saveWaystone(MyBlockPos villageLocation, MyBlockPos waystoneLocation) { - NBTTagCompound compound = new NBTTagCompound(); - compound.setTag("VillageLocation", villageLocation.writeToNBT(new NBTTagCompound())); - compound.setTag("WaystoneLocation", waystoneLocation.writeToNBT(new NBTTagCompound())); - return compound; - } - - private NBTTagCompound savePosts() { - NBTTagCompound compound = new NBTTagCompound(); - compound.setInteger("PostCount", villagePosts.size()); - int i=0; - for(Entry> now: villagePosts.entrySet()){ - compound.setTag("Posts"+(i++), savePostCollection(now.getKey(), now.getValue())); - } - return compound; - } - - private NBTBase savePostCollection(MyBlockPos villageLocation, Set posts) { - NBTTagCompound compound = new NBTTagCompound(); - compound.setTag("VillageLocation", villageLocation.writeToNBT(new NBTTagCompound())); - compound.setInteger("PostCount", posts.size()); - int i=0; - for(VillagePost now: posts){ - compound.setTag("Post"+(i++), now.save()); - } - return compound; - } - - public void load(NBTTagCompound compound){ - loadWaystones(compound.getCompoundTag("Waystones")); - loadSignpost(compound.getCompoundTag("Signposts")); - } - - private void loadWaystones(NBTTagCompound compound) { - villageWaystones = new HashMap<>(); - int count = compound.getInteger("WaystoneCount"); - for(int i=0; i(); - int postCount = compound.getInteger("PostCount"); - for(int i=0; i posts = loadPostSet(entry); - villagePosts.put(villageLocation, posts); - } - } - - private Set loadPostSet(NBTTagCompound compound) { - Set ret = new HashSet<>(); - int postCount = compound.getInteger("PostCount"); - for(int i=0; i villageWaystones; + private Map> villagePosts; + + private VillageLibrary() { + villageWaystones = new HashMap<>(); + villagePosts = new HashMap<>(); + } + + public void putWaystone(final MyBlockPos villageLocation, final MyBlockPos waystoneLocation) { + villageWaystones.put(villageLocation, waystoneLocation); + SPEventHandler.scheduleTask(() -> { + if (waystoneLocation.getTile() == null) { + return false; + } else { + new LibraryWaystoneHelper(villageLocation, villagePosts, waystoneLocation).enscribeEmptySign(); + return true; + } + }); + } + + public void putSignpost(final MyBlockPos villageLocation, final MyBlockPos signpostLocation, + final double optimalRot) { + Set villageSignposts = villagePosts.get(villageLocation); + if (villageSignposts == null) { + villageSignposts = new HashSet<>(); + villagePosts.put(villageLocation, villageSignposts); + } + villageSignposts.add(new VillagePost(signpostLocation, optimalRot)); + SPEventHandler.scheduleTask(() -> { + if (signpostLocation.getTile() == null) { + return false; + } else { + new LibrarySignpostHelper(villageLocation, signpostLocation, villageWaystones) + .enscribeNewSign(optimalRot); + return true; + } + }); + } + + public void save(NBTTagCompound compound) { + compound.setTag("Waystones", saveWaystones()); + compound.setTag("Signposts", savePosts()); + } + + private NBTTagCompound saveWaystones() { + NBTTagCompound compound = new NBTTagCompound(); + compound.setInteger("WaystoneCount", villageWaystones.size()); + int i = 0; + for (Entry now : villageWaystones.entrySet()) { + compound.setTag("Waystone" + (i++), saveWaystone(now.getKey(), now.getValue())); + } + return compound; + } + + private NBTBase saveWaystone(MyBlockPos villageLocation, MyBlockPos waystoneLocation) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setTag("VillageLocation", villageLocation.writeToNBT(new NBTTagCompound())); + compound.setTag("WaystoneLocation", waystoneLocation.writeToNBT(new NBTTagCompound())); + return compound; + } + + private NBTTagCompound savePosts() { + NBTTagCompound compound = new NBTTagCompound(); + compound.setInteger("PostCount", villagePosts.size()); + int i = 0; + for (Entry> now : villagePosts.entrySet()) { + compound.setTag("Posts" + (i++), savePostCollection(now.getKey(), now.getValue())); + } + return compound; + } + + private NBTBase savePostCollection(MyBlockPos villageLocation, Set posts) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setTag("VillageLocation", villageLocation.writeToNBT(new NBTTagCompound())); + compound.setInteger("PostCount", posts.size()); + int i = 0; + for (VillagePost now : posts) { + compound.setTag("Post" + (i++), now.save()); + } + return compound; + } + + public void load(NBTTagCompound compound) { + loadWaystones(compound.getCompoundTag("Waystones")); + loadSignpost(compound.getCompoundTag("Signposts")); + } + + private void loadWaystones(NBTTagCompound compound) { + villageWaystones = new HashMap<>(); + int count = compound.getInteger("WaystoneCount"); + for (int i = 0; i < count; i++) { + NBTTagCompound entry = compound.getCompoundTag("Waystone" + i); + MyBlockPos villageLocation = MyBlockPos.readFromNBT(entry.getCompoundTag("VillageLocation")); + MyBlockPos waystoneLocation = MyBlockPos.readFromNBT(entry.getCompoundTag("WaystoneLocation")); + villageWaystones.put(villageLocation, waystoneLocation); + } + } + + private void loadSignpost(NBTTagCompound compound) { + villagePosts = new HashMap<>(); + int postCount = compound.getInteger("PostCount"); + for (int i = 0; i < postCount; i++) { + NBTTagCompound entry = compound.getCompoundTag("Posts" + i); + MyBlockPos villageLocation = MyBlockPos.readFromNBT(entry.getCompoundTag("VillageLocation")); + Set posts = loadPostSet(entry); + villagePosts.put(villageLocation, posts); + } + } + + private Set loadPostSet(NBTTagCompound compound) { + Set ret = new HashSet<>(); + int postCount = compound.getInteger("PostCount"); + for (int i = 0; i < postCount; i++) { + ret.add(VillagePost.load(compound.getCompoundTag("Post" + i))); + } + return ret; + } } diff --git a/src/main/java/gollorum/signpost/worldGen/villages/VillagePost.java b/src/main/java/gollorum/signpost/worldGen/villages/VillagePost.java index 376e1047..0b50c545 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/VillagePost.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/VillagePost.java @@ -2,43 +2,45 @@ import java.util.List; +import net.minecraft.nbt.NBTTagCompound; + import gollorum.signpost.management.PostHandler; import gollorum.signpost.util.MyBlockPos; import gollorum.signpost.util.Sign; -import net.minecraft.nbt.NBTTagCompound; class VillagePost { - private MyBlockPos topSignPosition; - public Double desiredRotation; - - public VillagePost(MyBlockPos topSignPosition, Double desiredRotation) { - this.topSignPosition = topSignPosition; - this.desiredRotation = desiredRotation; - } - - @Override - public String toString() { - return topSignPosition.toString(); - } - - public List getSigns() { - return PostHandler.getSigns(topSignPosition); - } - - public MyBlockPos getTopSignPosition() { - return topSignPosition; - } - - NBTTagCompound save() { - NBTTagCompound compound = new NBTTagCompound(); - topSignPosition.writeToNBT(compound); - compound.setDouble("DesiredRotation", desiredRotation); - return compound; - } - - static VillagePost load(NBTTagCompound compound) { - MyBlockPos topSignPosition = MyBlockPos.readFromNBT(compound); - double desiredRotation = compound.getDouble("DesiredRotation"); - return new VillagePost(topSignPosition, desiredRotation); - } -} \ No newline at end of file + + private MyBlockPos topSignPosition; + public Double desiredRotation; + + public VillagePost(MyBlockPos topSignPosition, Double desiredRotation) { + this.topSignPosition = topSignPosition; + this.desiredRotation = desiredRotation; + } + + @Override + public String toString() { + return topSignPosition.toString(); + } + + public List getSigns() { + return PostHandler.getSigns(topSignPosition); + } + + public MyBlockPos getTopSignPosition() { + return topSignPosition; + } + + NBTTagCompound save() { + NBTTagCompound compound = new NBTTagCompound(); + topSignPosition.writeToNBT(compound); + compound.setDouble("DesiredRotation", desiredRotation); + return compound; + } + + static VillagePost load(NBTTagCompound compound) { + MyBlockPos topSignPosition = MyBlockPos.readFromNBT(compound); + double desiredRotation = compound.getDouble("DesiredRotation"); + return new VillagePost(topSignPosition, desiredRotation); + } +} diff --git a/src/main/java/gollorum/signpost/worldGen/villages/signpost/SignpostVillageCreationHandler.java b/src/main/java/gollorum/signpost/worldGen/villages/signpost/SignpostVillageCreationHandler.java index ec46854a..962be736 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/signpost/SignpostVillageCreationHandler.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/signpost/SignpostVillageCreationHandler.java @@ -3,36 +3,40 @@ import java.util.List; import java.util.Random; -import cpw.mods.fml.common.registry.VillagerRegistry.IVillageCreationHandler; -import gollorum.signpost.management.ClientConfigStorage; -import gollorum.signpost.management.ConfigHandler; import net.minecraft.world.gen.structure.StructureVillagePieces.PieceWeight; import net.minecraft.world.gen.structure.StructureVillagePieces.Start; -public class SignpostVillageCreationHandler implements IVillageCreationHandler{ - - private static final Class COMPONENT_CLASS = VillageComponentSignpost.class; - - @Override - public PieceWeight getVillagePieceWeight(Random random, int i) { - if(ClientConfigStorage.INSTANCE.isDisableVillageGeneration()){ - return new PieceWeight(COMPONENT_CLASS, 0, 0); - } - return new PieceWeight(COMPONENT_CLASS, ClientConfigStorage.INSTANCE.getVillageSignpostsWeight(), getCount(random)); - } - - private int getCount(Random random){ - return ClientConfigStorage.INSTANCE.getVillageMaxSignposts(); - } - - @Override - public Class getComponentClass() { - return COMPONENT_CLASS; - } - - @Override - public Object buildComponent(PieceWeight villagePiece, Start startPiece, List pieces, Random random, int x, int y, int z, int facing, int type) { - return VillageComponentSignpost.buildComponent(startPiece, pieces, random, x, y, z, facing, type); - } - -} \ No newline at end of file +import cpw.mods.fml.common.registry.VillagerRegistry.IVillageCreationHandler; +import gollorum.signpost.management.ClientConfigStorage; + +public class SignpostVillageCreationHandler implements IVillageCreationHandler { + + private static final Class COMPONENT_CLASS = VillageComponentSignpost.class; + + @Override + public PieceWeight getVillagePieceWeight(Random random, int i) { + if (ClientConfigStorage.INSTANCE.isDisableVillageGeneration()) { + return new PieceWeight(COMPONENT_CLASS, 0, 0); + } + return new PieceWeight( + COMPONENT_CLASS, + ClientConfigStorage.INSTANCE.getVillageSignpostsWeight(), + getCount(random)); + } + + private int getCount(Random random) { + return ClientConfigStorage.INSTANCE.getVillageMaxSignposts(); + } + + @Override + public Class getComponentClass() { + return COMPONENT_CLASS; + } + + @Override + public Object buildComponent(PieceWeight villagePiece, Start startPiece, List pieces, Random random, int x, int y, + int z, int facing, int type) { + return VillageComponentSignpost.buildComponent(startPiece, pieces, random, x, y, z, facing, type); + } + +} diff --git a/src/main/java/gollorum/signpost/worldGen/villages/signpost/VillageComponentSignpost.java b/src/main/java/gollorum/signpost/worldGen/villages/signpost/VillageComponentSignpost.java index 91528e5f..1eaf063c 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/signpost/VillageComponentSignpost.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/signpost/VillageComponentSignpost.java @@ -5,11 +5,6 @@ import javax.annotation.Nullable; -import gollorum.signpost.Signpost; -import gollorum.signpost.util.MyBlockPos; -import gollorum.signpost.util.code.MinecraftDependent; -import gollorum.signpost.worldGen.villages.GenerateStructureHelper; -import gollorum.signpost.worldGen.villages.VillageLibrary; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.world.World; @@ -17,80 +12,93 @@ import net.minecraft.world.gen.structure.StructureComponent; import net.minecraft.world.gen.structure.StructureVillagePieces; +import gollorum.signpost.Signpost; +import gollorum.signpost.util.MyBlockPos; +import gollorum.signpost.util.code.MinecraftDependent; +import gollorum.signpost.worldGen.villages.GenerateStructureHelper; +import gollorum.signpost.worldGen.villages.VillageLibrary; + @MinecraftDependent -public class VillageComponentSignpost extends StructureVillagePieces.Village{ - - private boolean built = false; - private StructureVillagePieces.Start start; - private int facing; - - public VillageComponentSignpost(){ - super(); - } - - public VillageComponentSignpost(StructureVillagePieces.Start start, int type, StructureBoundingBox boundingBox, int facing){ - super(start, type); - this.boundingBox = boundingBox; - this.start = start; - this.facing = facing; - } - - @Nullable - public static StructureVillagePieces.Village buildComponent(StructureVillagePieces.Start startPiece, List pieces, Random random, int x, int y, int z, int facing, int type) { - StructureBoundingBox boundingBox = StructureBoundingBox.getComponentToAddBoundingBox(x, y, z, 0, 0, 0, 3, 3, 3, facing); - if (canVillageGoDeeper(boundingBox) && findIntersecting(pieces, boundingBox) == null) { - return new VillageComponentSignpost(startPiece, type, boundingBox, facing); - } - return null; - } +public class VillageComponentSignpost extends StructureVillagePieces.Village { + + private boolean built = false; + private StructureVillagePieces.Start start; + private int facing; + + public VillageComponentSignpost() { + super(); + } + + public VillageComponentSignpost(StructureVillagePieces.Start start, int type, StructureBoundingBox boundingBox, + int facing) { + super(start, type); + this.boundingBox = boundingBox; + this.start = start; + this.facing = facing; + } + + @Nullable + public static StructureVillagePieces.Village buildComponent(StructureVillagePieces.Start startPiece, + List pieces, Random random, int x, int y, int z, int facing, int type) { + StructureBoundingBox boundingBox = StructureBoundingBox + .getComponentToAddBoundingBox(x, y, z, 0, 0, 0, 3, 3, 3, facing); + if (canVillageGoDeeper(boundingBox) && findIntersecting(pieces, boundingBox) == null) { + return new VillageComponentSignpost(startPiece, type, boundingBox, facing); + } + return null; + } - @Override - public boolean addComponentParts(World world, Random random, StructureBoundingBox boundingBox) { - if(built || start==null){ - return true; - }else{ - built = true; - } - int x = this.boundingBox.getCenterX(); - int z = this.boundingBox.getCenterZ(); - int y; - try{ - y = GenerateStructureHelper.getInstance().getTopSolidOrLiquidBlock(world, x, z); - } catch(Exception e) { - y = this.boundingBox.getCenterY(); - } - world.setBlock(x, y, z, Signpost.proxy.blockHandler.post_oak); - world.setBlock(x, y + 1, z, Signpost.proxy.blockHandler.post_oak); - if(world.getBlock(x, y-1, z).getMaterial().isLiquid()){ - Block block = this.func_151558_b(Blocks.planks, 0); - world.setBlock(x, y-1, z, block); - world.setBlock(x-1, y-1, z-1, block); - world.setBlock(x-1, y-1, z, block); - world.setBlock(x-1, y-1, z+1, block); - world.setBlock(x, y-1, z-1, block); - world.setBlock(x, y-1, z+1, block); - world.setBlock(x+1, y-1, z-1, block); - world.setBlock(x+1, y-1, z, block); - world.setBlock(x+1, y-1, z+1, block); - } - StructureBoundingBox villageBox = start.getBoundingBox(); - MyBlockPos villagePos = new MyBlockPos(world, villageBox.minX, 0, villageBox.minZ); - MyBlockPos blockPos = new MyBlockPos(world, x, y + 1, z); - VillageLibrary.getInstance().putSignpost(villagePos, blockPos, optimalRot(facing)); - return true; - } + @Override + public boolean addComponentParts(World world, Random random, StructureBoundingBox boundingBox) { + if (built || start == null) { + return true; + } else { + built = true; + } + int x = this.boundingBox.getCenterX(); + int z = this.boundingBox.getCenterZ(); + int y; + try { + y = GenerateStructureHelper.getInstance() + .getTopSolidOrLiquidBlock(world, x, z); + } catch (Exception e) { + y = this.boundingBox.getCenterY(); + } + world.setBlock(x, y, z, Signpost.proxy.blockHandler.post_oak); + world.setBlock(x, y + 1, z, Signpost.proxy.blockHandler.post_oak); + if (world.getBlock(x, y - 1, z) + .getMaterial() + .isLiquid()) { + Block block = this.func_151558_b(Blocks.planks, 0); + world.setBlock(x, y - 1, z, block); + world.setBlock(x - 1, y - 1, z - 1, block); + world.setBlock(x - 1, y - 1, z, block); + world.setBlock(x - 1, y - 1, z + 1, block); + world.setBlock(x, y - 1, z - 1, block); + world.setBlock(x, y - 1, z + 1, block); + world.setBlock(x + 1, y - 1, z - 1, block); + world.setBlock(x + 1, y - 1, z, block); + world.setBlock(x + 1, y - 1, z + 1, block); + } + StructureBoundingBox villageBox = start.getBoundingBox(); + MyBlockPos villagePos = new MyBlockPos(world, villageBox.minX, 0, villageBox.minZ); + MyBlockPos blockPos = new MyBlockPos(world, x, y + 1, z); + VillageLibrary.getInstance() + .putSignpost(villagePos, blockPos, optimalRot(facing)); + return true; + } - private double optimalRot(int facing) { - switch(facing){ - case 0: - return 0; - case 1: - return 1.5*Math.PI; - case 2: - return Math.PI; - case 3: - return 0.5*Math.PI; - } - return 0; - } + private double optimalRot(int facing) { + switch (facing) { + case 0: + return 0; + case 1: + return 1.5 * Math.PI; + case 2: + return Math.PI; + case 3: + return 0.5 * Math.PI; + } + return 0; + } } diff --git a/src/main/java/gollorum/signpost/worldGen/villages/waystone/VillageComponentWaystone.java b/src/main/java/gollorum/signpost/worldGen/villages/waystone/VillageComponentWaystone.java index 12fa88ff..96560d83 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/waystone/VillageComponentWaystone.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/waystone/VillageComponentWaystone.java @@ -1,5 +1,19 @@ package gollorum.signpost.worldGen.villages.waystone; +import java.util.List; +import java.util.Random; + +import javax.annotation.Nullable; + +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.world.World; +import net.minecraft.world.gen.structure.StructureBoundingBox; +import net.minecraft.world.gen.structure.StructureComponent; +import net.minecraft.world.gen.structure.StructureVillagePieces; + import gollorum.signpost.SPEventHandler; import gollorum.signpost.Signpost; import gollorum.signpost.blocks.BaseModelPost; @@ -10,119 +24,122 @@ import gollorum.signpost.worldGen.villages.GenerateStructureHelper; import gollorum.signpost.worldGen.villages.NameLibrary; import gollorum.signpost.worldGen.villages.VillageLibrary; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.world.World; -import net.minecraft.world.gen.structure.StructureBoundingBox; -import net.minecraft.world.gen.structure.StructureComponent; -import net.minecraft.world.gen.structure.StructureVillagePieces; - -import javax.annotation.Nullable; -import java.util.List; -import java.util.Random; public class VillageComponentWaystone extends StructureVillagePieces.Village { - private boolean built = false; - private StructureVillagePieces.Start start; - private int facing; - - public VillageComponentWaystone() { - super(); - } - - public VillageComponentWaystone(StructureVillagePieces.Start start, int type, StructureBoundingBox boundingBox, - int facing) { - super(start, type); - this.boundingBox = boundingBox; - this.start = start; - this.facing = facing; - } - - @Nullable - public static StructureVillagePieces.Village buildComponent(StructureVillagePieces.Start startPiece, - List pieces, Random random, int x, int y, int z, int facing, int type) { - StructureBoundingBox boundingBox = StructureBoundingBox.getComponentToAddBoundingBox(x, y, z, 0, 0, 0, 1, 1, 1, - facing); - if (canVillageGoDeeper(boundingBox) && findIntersecting(pieces, boundingBox) == null) { - return new VillageComponentWaystone(startPiece, type, boundingBox, facing); - } - return null; - } - - @Override - public boolean addComponentParts(final World world, final Random random, StructureBoundingBox boundingBox) { - if (built || start == null || !NameLibrary.getInstance().namesLeft()) { - return true; - } else { - built = true; - } - final String name = NameLibrary.getInstance().getName(random); - if (name == null) { - return true; - } - final int x = this.boundingBox.getCenterX(); - final int z = this.boundingBox.getCenterZ(); - final int y = GenerateStructureHelper.getInstance().getTopSolidOrLiquidBlock(world, x, z); - - List allowedModelTypes = Signpost.proxy.blockHandler.baseModelsForVillages(); - if(allowedModelTypes.size() == 0) return true; - - if (world.getBlock(x, y - 1, z).getMaterial().isLiquid()) { - Block block = this.func_151558_b(Blocks.planks, 0); - world.setBlock(x, y - 1, z, block); - } - if (world.setBlock(x, y, z, allowedModelTypes.get(random.nextInt(allowedModelTypes.size())), facing, 3)) { - SPEventHandler.scheduleTask(() -> { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof WaystoneContainer) { - if (PostHandler.getNativeWaystones().nameTaken(name)) { - setupWaystone(NameLibrary.getInstance().getName(random), world, x, y, z, (WaystoneContainer) tile); - } else { - setupWaystone(name, world, x, y, z, (WaystoneContainer) tile); - } - return true; - } else { - return false; - } - }); - } - return true; - } - - private void setupWaystone(String name, World world, int x, int y, int z, WaystoneContainer container) { - assureBaseInfo(container, world, new MyBlockPos(world, x, y, z), getEnumFacing(facing), name); - - StructureBoundingBox villageBox = start.getBoundingBox(); - MyBlockPos villagePos = new MyBlockPos(world, villageBox.minX, 0, villageBox.minZ); - MyBlockPos blockPos = new MyBlockPos(world, x, y, z); - VillageLibrary.getInstance().putWaystone(villagePos, blockPos); - } - - private void assureBaseInfo(WaystoneContainer container, World world, MyBlockPos blockPos, EnumFacing facing, - String name) { - if (container.getBaseInfo() == null) { - MyBlockPos telePos = GenerateStructureHelper.getInstance() - .getTopSolidOrLiquidBlock(blockPos.front(facing, 2)); - BasePost.generate(world, blockPos, telePos, name); - } else { - container.setName(name); - } - } - - private EnumFacing getEnumFacing(int facing) { - switch (facing) { - case 0: - return EnumFacing.NORTH; - case 1: - return EnumFacing.WEST; - case 2: - return EnumFacing.SOUTH; - case 3: - return EnumFacing.EAST; - } - return EnumFacing.EAST; - } + private boolean built = false; + private StructureVillagePieces.Start start; + private int facing; + + public VillageComponentWaystone() { + super(); + } + + public VillageComponentWaystone(StructureVillagePieces.Start start, int type, StructureBoundingBox boundingBox, + int facing) { + super(start, type); + this.boundingBox = boundingBox; + this.start = start; + this.facing = facing; + } + + @Nullable + public static StructureVillagePieces.Village buildComponent(StructureVillagePieces.Start startPiece, + List pieces, Random random, int x, int y, int z, int facing, int type) { + StructureBoundingBox boundingBox = StructureBoundingBox + .getComponentToAddBoundingBox(x, y, z, 0, 0, 0, 1, 1, 1, facing); + if (canVillageGoDeeper(boundingBox) && findIntersecting(pieces, boundingBox) == null) { + return new VillageComponentWaystone(startPiece, type, boundingBox, facing); + } + return null; + } + + @Override + public boolean addComponentParts(final World world, final Random random, StructureBoundingBox boundingBox) { + if (built || start == null + || !NameLibrary.getInstance() + .namesLeft()) { + return true; + } else { + built = true; + } + final String name = NameLibrary.getInstance() + .getName(random); + if (name == null) { + return true; + } + final int x = this.boundingBox.getCenterX(); + final int z = this.boundingBox.getCenterZ(); + final int y = GenerateStructureHelper.getInstance() + .getTopSolidOrLiquidBlock(world, x, z); + + List allowedModelTypes = Signpost.proxy.blockHandler.baseModelsForVillages(); + if (allowedModelTypes.size() == 0) return true; + + if (world.getBlock(x, y - 1, z) + .getMaterial() + .isLiquid()) { + Block block = this.func_151558_b(Blocks.planks, 0); + world.setBlock(x, y - 1, z, block); + } + if (world.setBlock(x, y, z, allowedModelTypes.get(random.nextInt(allowedModelTypes.size())), facing, 3)) { + SPEventHandler.scheduleTask(() -> { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof WaystoneContainer) { + if (PostHandler.getNativeWaystones() + .nameTaken(name)) { + setupWaystone( + NameLibrary.getInstance() + .getName(random), + world, + x, + y, + z, + (WaystoneContainer) tile); + } else { + setupWaystone(name, world, x, y, z, (WaystoneContainer) tile); + } + return true; + } else { + return false; + } + }); + } + return true; + } + + private void setupWaystone(String name, World world, int x, int y, int z, WaystoneContainer container) { + assureBaseInfo(container, world, new MyBlockPos(world, x, y, z), getEnumFacing(facing), name); + + StructureBoundingBox villageBox = start.getBoundingBox(); + MyBlockPos villagePos = new MyBlockPos(world, villageBox.minX, 0, villageBox.minZ); + MyBlockPos blockPos = new MyBlockPos(world, x, y, z); + VillageLibrary.getInstance() + .putWaystone(villagePos, blockPos); + } + + private void assureBaseInfo(WaystoneContainer container, World world, MyBlockPos blockPos, EnumFacing facing, + String name) { + if (container.getBaseInfo() == null) { + MyBlockPos telePos = GenerateStructureHelper.getInstance() + .getTopSolidOrLiquidBlock(blockPos.front(facing, 2)); + BasePost.generate(world, blockPos, telePos, name); + } else { + container.setName(name); + } + } + + private EnumFacing getEnumFacing(int facing) { + switch (facing) { + case 0: + return EnumFacing.NORTH; + case 1: + return EnumFacing.WEST; + case 2: + return EnumFacing.SOUTH; + case 3: + return EnumFacing.EAST; + } + return EnumFacing.EAST; + } } diff --git a/src/main/java/gollorum/signpost/worldGen/villages/waystone/WaystoneVillageCreationHandler.java b/src/main/java/gollorum/signpost/worldGen/villages/waystone/WaystoneVillageCreationHandler.java index 97f889f5..2f0a9669 100644 --- a/src/main/java/gollorum/signpost/worldGen/villages/waystone/WaystoneVillageCreationHandler.java +++ b/src/main/java/gollorum/signpost/worldGen/villages/waystone/WaystoneVillageCreationHandler.java @@ -3,34 +3,37 @@ import java.util.List; import java.util.Random; -import cpw.mods.fml.common.registry.VillagerRegistry.IVillageCreationHandler; -import gollorum.signpost.management.ClientConfigStorage; -import gollorum.signpost.worldGen.villages.NameLibrary; import net.minecraft.world.gen.structure.StructureVillagePieces.PieceWeight; import net.minecraft.world.gen.structure.StructureVillagePieces.Start; -public class WaystoneVillageCreationHandler implements IVillageCreationHandler{ - - private static final int COUNT = 1; - private static final Class COMPONENT_CLASS = VillageComponentWaystone.class; - - @Override - public PieceWeight getVillagePieceWeight(Random random, int i) { - if(ClientConfigStorage.INSTANCE.isDisableVillageGeneration() ||! NameLibrary.getInstance().namesLeft()){ - return new PieceWeight(COMPONENT_CLASS, 0, 0); - } - int weight = ClientConfigStorage.INSTANCE.getVillageWaystonesWeight(); - return new PieceWeight(COMPONENT_CLASS, weight, COUNT); - } - - @Override - public Class getComponentClass() { - return COMPONENT_CLASS; - } - - @Override - public Object buildComponent(PieceWeight villagePiece, Start startPiece, List pieces, Random random, int x, int y, int z, int facing, int type) { - return VillageComponentWaystone.buildComponent(startPiece, pieces, random, x, y, z, facing, type); - } +import cpw.mods.fml.common.registry.VillagerRegistry.IVillageCreationHandler; +import gollorum.signpost.management.ClientConfigStorage; +import gollorum.signpost.worldGen.villages.NameLibrary; -} \ No newline at end of file +public class WaystoneVillageCreationHandler implements IVillageCreationHandler { + + private static final int COUNT = 1; + private static final Class COMPONENT_CLASS = VillageComponentWaystone.class; + + @Override + public PieceWeight getVillagePieceWeight(Random random, int i) { + if (ClientConfigStorage.INSTANCE.isDisableVillageGeneration() || !NameLibrary.getInstance() + .namesLeft()) { + return new PieceWeight(COMPONENT_CLASS, 0, 0); + } + int weight = ClientConfigStorage.INSTANCE.getVillageWaystonesWeight(); + return new PieceWeight(COMPONENT_CLASS, weight, COUNT); + } + + @Override + public Class getComponentClass() { + return COMPONENT_CLASS; + } + + @Override + public Object buildComponent(PieceWeight villagePiece, Start startPiece, List pieces, Random random, int x, int y, + int z, int facing, int type) { + return VillageComponentWaystone.buildComponent(startPiece, pieces, random, x, y, z, facing, type); + } + +} diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index 9a45f3f7..1d4572ba 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -1,16 +1,23 @@ -[ { - "modid": "signpost", - "name": "Signpost", - "description": "signpost mod.", - "version": "${version}", - "mcversion": "${mcversion}", - "url": "", - "updateUrl": "", - "authorList": ["Gollorum"], - "credits": "Developed by Gollorum; Chinese localization by TartaricAcid; Russian localization by Aqelius", - "logoFile": "", - "screenshots": [], - "dependencies": [] + "modListVersion": 2, + "modList": [ + { + "modid": "${modId}", + "name": "${modName}", + "description": "A mod that adds signs posts and waystones.", + "version": "${modVersion}", + "mcversion": "${minecraftVersion}", + "url": "https://github.com/Pilzinsel64/Signpost", + "updateUrl": "", + "authorList": ["Gollorum", "Pilzinsel64"], + "credits": "Developed by Gollorum; Chinese localization by TartaricAcid; Russian localization by Aqelius", + "logoFile": "", + "screenshots": [], + "parent": "", + "requiredMods": [], + "dependencies": [], + "dependants": [], + "useDependencyInformation": true + } + ] } -]