Compare commits

..
2 Commits
Author SHA1 Message Date
TataTawa 9176fdc020 Update TileConduitBundle.java 2022-06-15 15:19:18 +08:00
TataTawa b6614df9b3 Update TileConduitBundle.java 2022-06-15 15:07:26 +08:00
1660 changed files with 89312 additions and 94075 deletions

No files matched your search

+3 -2
View File
@@ -18,5 +18,6 @@ end_of_line = crlf
[*.{dtd,json,info,mcmeta,md,sh,svg,xml,xsd,xsl,yaml,yml}]
indent_size = 2
[*.lang]
trim_trailing_whitespace = false
[*.java]
indent_size = 2
ij_java_space_before_if_parentheses = false
-2
View File
@@ -1,2 +0,0 @@
# Ignore spotlessApply reformat
275d137ba8573454518c21bdcf4372362302ee82
-44
View File
@@ -1,44 +0,0 @@
* 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
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
RUNDIR="run"
CRASH="crash-reports"
SERVERLOG="server.log"
if [[ -d $RUNDIR/$CRASH ]]; then
echo "Crash reports detected:"
cat $RUNDIR/$CRASH/crash*.txt
exit 1
fi
if grep --quiet "Fatal errors were detected" $SERVERLOG; then
echo "Fatal errors detected:"
cat server.log
exit 1
fi
if grep --quiet "The state engine was in incorrect state ERRORED and forced into state SERVER_STOPPED" $SERVERLOG; then
echo "Server force stopped:"
cat server.log
exit 1
fi
if ! grep --quiet -Po '.+Done \(.+\)\! For help, type "help" or "\?"' $SERVERLOG; then
echo "Server didn't finish startup:"
cat server.log
exit 1
fi
echo "No crash reports detected"
exit 0
+36 -4
View File
@@ -1,13 +1,45 @@
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Build and test
on:
pull_request:
branches: [ master, main, release/** ]
branches: [ master, main ]
push:
branches: [ master, main, release/** ]
branches: [ master, main ]
jobs:
build-and-test:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/build-and-test.yml@master
secrets: inherit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Setup the workspace
run: ./gradlew setupCIWorkspace
- name: Build the mod
run: ./gradlew build
- name: Run server for 1.5 minutes
run: |
mkdir run
echo "eula=true" > run/eula.txt
timeout 90 ./gradlew runServer 2>&1 | tee -a server.log || true
- name: Test no errors reported during server run
run: |
chmod +x .github/scripts/test-no-error-reports.sh
.github/scripts/test-no-error-reports.sh
-17
View File
@@ -1,17 +0,0 @@
name: Optimize images
on:
pull_request:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
push:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
jobs:
optimize-images:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/optimize-images.yml@master
secrets: inherit
+44 -7
View File
@@ -1,14 +1,51 @@
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Release tagged build
on:
push:
tags: [ '*' ]
permissions:
contents: write
tags:
- '*'
jobs:
release-tags:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/release-tags.yml@master
secrets: inherit
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set release version
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Setup the workspace
run: ./gradlew setupCIWorkspace
- name: Build the mod
run: ./gradlew build
- name: Release under current tag
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "${{ env.RELEASE_VERSION }}"
prerelease: false
title: "${{ env.RELEASE_VERSION }}"
files: build/libs/*.jar
- name: Publish to Maven
run: ./gradlew publish
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
-2
View File
@@ -27,5 +27,3 @@ whitelist.json
*.iws
src/main/resources/mixins.*.json
*.bat
layout.json
.DS_Store
+2 -2
View File
@@ -8,11 +8,11 @@ Issues can be reported to the [GTNH tracker](https://github.com/GTNewHorizons/GT
All code (excluding the bundled APIs from other mods, which are covered by their respective licenses) were released without restriction into the public domain under the CC0 1.0 license (http://creativecommons.org/publicdomain/zero/1.0/legalcode) FAQ (https://wiki.creativecommons.org/CC0_FAQ).
Do what you want with it, as long as you smile while doing so.
### GTNH Modifications:
###GTNH Modifications:
LGPL v3.0 or later. Feel free to use our changes, just give back any changes you make to the community as well!
### Sound Credits
###Sound Credits
Most sound attributed under Creative Commons Attribution 3.0 Unported (CC BY 3.0)
+745 -2
View File
@@ -1,5 +1,748 @@
//version: 1707058017
//version: 1652851397
/*
DO NOT CHANGE THIS FILE!
Also, you may replace this file at any time if there is an update available.
Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates.
*/
import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.internal.logging.text.StyledTextOutput.Style
import org.gradle.internal.logging.text.StyledTextOutputFactory
import java.util.concurrent.TimeUnit
buildscript {
repositories {
maven {
name 'forge'
url 'https://maven.minecraftforge.net'
}
maven {
name 'sonatype'
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
maven {
name 'Scala CI dependencies'
url 'https://repo1.maven.org/maven2/'
}
maven {
name 'jitpack'
url 'https://jitpack.io'
}
}
dependencies {
classpath 'com.github.GTNewHorizons:ForgeGradle:1.2.7'
}
}
plugins {
id 'com.gtnewhorizons.gtnhconvention'
id 'java-library'
id 'idea'
id 'eclipse'
id 'scala'
id 'maven-publish'
id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false
id 'org.jetbrains.kotlin.kapt' version '1.5.30' apply false
id 'com.google.devtools.ksp' version '1.5.30-1.0.0' apply false
id 'org.ajoberstar.grgit' version '4.1.1'
id 'com.github.johnrengelman.shadow' version '4.0.4'
id 'com.palantir.git-version' version '0.13.0' apply false
id 'de.undercouch.download' version '5.0.1'
id 'com.github.gmazzo.buildconfig' version '3.0.3' apply false
}
if (project.file('.git/HEAD').isFile()) {
apply plugin: 'com.palantir.git-version'
}
def out = services.get(StyledTextOutputFactory).create('an-output')
apply plugin: 'forge'
def projectJavaVersion = JavaLanguageVersion.of(8)
java {
toolchain {
languageVersion.set(projectJavaVersion)
}
}
idea {
module {
inheritOutputDirs = true
downloadJavadoc = true
downloadSources = true
}
}
if(JavaVersion.current() != JavaVersion.VERSION_1_8) {
throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current())
}
checkPropertyExists("modName")
checkPropertyExists("modId")
checkPropertyExists("modGroup")
checkPropertyExists("autoUpdateBuildScript")
checkPropertyExists("minecraftVersion")
checkPropertyExists("forgeVersion")
checkPropertyExists("replaceGradleTokenInFile")
checkPropertyExists("gradleTokenModId")
checkPropertyExists("gradleTokenModName")
checkPropertyExists("gradleTokenVersion")
checkPropertyExists("gradleTokenGroupName")
checkPropertyExists("apiPackage")
checkPropertyExists("accessTransformersFile")
checkPropertyExists("usesMixins")
checkPropertyExists("mixinPlugin")
checkPropertyExists("mixinsPackage")
checkPropertyExists("coreModClass")
checkPropertyExists("containsMixinsAndOrCoreModOnly")
checkPropertyExists("usesShadowedDependencies")
checkPropertyExists("developmentEnvironmentUserName")
boolean noPublishedSources = project.findProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false
boolean usesMixinDebug = project.findProperty('usesMixinDebug') ?: project.usesMixins.toBoolean()
String javaSourceDir = "src/main/java/"
String scalaSourceDir = "src/main/scala/"
String kotlinSourceDir = "src/main/kotlin/"
String targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/")
String targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/")
String targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/")
if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) {
throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin)
}
if(apiPackage) {
targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/")
targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/")
targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/")
if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) {
throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin)
}
}
if(accessTransformersFile) {
String targetFile = "src/main/resources/META-INF/" + accessTransformersFile
if(!getFile(targetFile).exists()) {
throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile)
}
}
if(usesMixins.toBoolean()) {
if(mixinsPackage.isEmpty() || mixinPlugin.isEmpty()) {
throw new GradleException("\"mixinPlugin\" requires \"mixinsPackage\" and \"mixinPlugin\" to be set!")
}
targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/")
targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/")
targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/")
if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) {
throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin)
}
String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java"
String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".scala"
String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java"
String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".kt"
if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) {
throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin)
}
}
if(coreModClass) {
String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java"
String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".scala"
String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java"
String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".kt"
if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) {
throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin)
}
}
configurations.all {
resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)
// Make sure GregTech build won't time out
System.setProperty("org.gradle.internal.http.connectionTimeout", 120000 as String)
System.setProperty("org.gradle.internal.http.socketTimeout", 120000 as String)
}
// Fix Jenkins' Git: chmod a file should not be detected as a change and append a '.dirty' to the version
try {
'git config core.fileMode false'.execute()
}
catch (Exception ignored) {
out.style(Style.Failure).println("git isn't installed at all")
}
// Pulls version first from the VERSION env and then git tag
String identifiedVersion
String versionOverride = System.getenv("VERSION") ?: null
try {
identifiedVersion = versionOverride == null ? gitVersion() : versionOverride
}
catch (Exception ignored) {
out.style(Style.Failure).text(
'This mod must be version controlled by Git AND the repository must provide at least one tag,\n' +
'or the VERSION override must be set! ').style(Style.SuccessHeader).text('(Do NOT download from GitHub using the ZIP option, instead\n' +
'clone the repository, see ').style(Style.Info).text('https://gtnh.miraheze.org/wiki/Development').style(Style.SuccessHeader).println(' for details.)'
)
versionOverride = 'NO-GIT-TAG-SET'
identifiedVersion = versionOverride
}
version = minecraftVersion + '-' + identifiedVersion
ext {
modVersion = identifiedVersion
}
if(identifiedVersion == versionOverride) {
out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7')
}
group = modGroup
if(project.hasProperty("customArchiveBaseName") && customArchiveBaseName) {
archivesBaseName = customArchiveBaseName
}
else {
archivesBaseName = modId
}
def arguments = []
def jvmArguments = []
if (usesMixins.toBoolean()) {
arguments += [
"--tweakClass org.spongepowered.asm.launch.MixinTweaker"
]
if (usesMixinDebug.toBoolean()) {
jvmArguments += [
"-Dmixin.debug.countInjections=true",
"-Dmixin.debug.verbose=true",
"-Dmixin.debug.export=true"
]
}
}
minecraft {
version = minecraftVersion + '-' + forgeVersion + '-' + minecraftVersion
runDir = 'run'
if (replaceGradleTokenInFile) {
replaceIn replaceGradleTokenInFile
if(gradleTokenModId) {
replace gradleTokenModId, modId
}
if(gradleTokenModName) {
replace gradleTokenModName, modName
}
if(gradleTokenVersion) {
replace gradleTokenVersion, modVersion
}
if(gradleTokenGroupName) {
replace gradleTokenGroupName, modGroup
}
}
clientIntellijRun {
args(arguments)
jvmArgs(jvmArguments)
if(developmentEnvironmentUserName) {
args("--username", developmentEnvironmentUserName)
}
}
serverIntellijRun {
args(arguments)
jvmArgs(jvmArguments)
}
}
if(file('addon.gradle').exists()) {
apply from: 'addon.gradle'
}
apply from: 'repositories.gradle'
configurations {
implementation.extendsFrom(shadowImplementation) // TODO: remove after all uses are refactored
implementation.extendsFrom(shadowCompile)
implementation.extendsFrom(shadeCompile)
}
repositories {
maven {
name 'Overmind forge repo mirror'
url 'https://gregtech.overminddl1.com/'
}
if(usesMixins.toBoolean()) {
maven {
name 'sponge'
url 'https://repo.spongepowered.org/repository/maven-public'
}
maven {
url 'https://jitpack.io'
}
}
}
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('org.spongepowered:mixin:0.8-SNAPSHOT')
// using 0.8 to workaround a issue in 0.7 which fails mixin application
compile('com.github.GTNewHorizons:SpongePoweredMixin:0.7.12-GTNH') {
// Mixin includes a lot of dependencies that are too up-to-date
exclude module: 'launchwrapper'
exclude module: 'guava'
exclude module: 'gson'
exclude module: 'commons-io'
exclude module: 'log4j-core'
}
compile('com.github.GTNewHorizons:SpongeMixins:1.5.0')
}
}
apply from: 'dependencies.gradle'
def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json'
def refMap = "${tasks.compileJava.temporaryDir}" + File.separator + mixingConfigRefMap
def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg"
task generateAssets {
if (usesMixins.toBoolean()) {
def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json");
if (!mixinConfigFile.exists()) {
mixinConfigFile.text = """{
"required": true,
"minVersion": "0.7.11",
"package": "${modGroup}.${mixinsPackage}",
"plugin": "${modGroup}.${mixinPlugin}",
"refmap": "${mixingConfigRefMap}",
"target": "@env(DEFAULT)",
"compatibilityLevel": "JAVA_8",
"mixins": [],
"client": [],
"server": []
}
"""
}
}
}
task relocateShadowJar(type: ConfigureShadowRelocation) {
target = tasks.shadowJar
prefix = modGroup + ".shadow"
}
shadowJar {
project.configurations.shadeCompile.each { dep ->
from(project.zipTree(dep)) {
exclude 'META-INF', 'META-INF/**'
}
}
manifest {
attributes(getManifestAttributes())
}
minimize() // This will only allow shading for actually used classes
configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile]
dependsOn(relocateShadowJar)
}
jar {
project.configurations.shadeCompile.each { dep ->
from(project.zipTree(dep)) {
exclude 'META-INF', 'META-INF/**'
}
}
manifest {
attributes(getManifestAttributes())
}
if(usesShadowedDependencies.toBoolean()) {
dependsOn(shadowJar)
enabled = false
}
}
reobf {
if(usesMixins.toBoolean()) {
addExtraSrgFile mixinSrg
}
}
afterEvaluate {
if(usesMixins.toBoolean()) {
tasks.compileJava {
options.compilerArgs += [
"-AreobfSrgFile=${tasks.reobf.srg}",
"-AoutSrgFile=${mixinSrg}",
"-AoutRefMapFile=${refMap}",
// Elan: from what I understand they are just some linter configs so you get some warning on how to properly code
"-XDenableSunApiLintControl",
"-XDignore.symbol.file"
]
}
}
}
runClient {
if(developmentEnvironmentUserName) {
arguments += [
"--username",
developmentEnvironmentUserName
]
}
args(arguments)
jvmArgs(jvmArguments)
}
runServer {
args(arguments)
jvmArgs(jvmArguments)
}
tasks.withType(JavaExec).configureEach {
javaLauncher.set(
javaToolchains.launcherFor {
languageVersion = projectJavaVersion
}
)
}
processResources {
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace modVersion and minecraftVersion
expand "minecraftVersion": project.minecraft.version,
"modVersion": modVersion,
"modId": modId,
"modName": modName
}
if(usesMixins.toBoolean()) {
from refMap
}
// copy everything else that's not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
def getManifestAttributes() {
def manifestAttributes = [:]
if(!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) {
manifestAttributes += ["FMLCorePluginContainsFMLMod": true]
}
if(accessTransformersFile) {
manifestAttributes += ["FMLAT" : accessTransformersFile.toString()]
}
if(coreModClass) {
manifestAttributes += ["FMLCorePlugin": modGroup + "." + coreModClass]
}
if(usesMixins.toBoolean()) {
manifestAttributes += [
"TweakClass" : "org.spongepowered.asm.launch.MixinTweaker",
"MixinConfigs" : "mixins." + modId + ".json",
"ForceLoadAsMod" : !containsMixinsAndOrCoreModOnly.toBoolean()
]
}
return manifestAttributes
}
task sourcesJar(type: Jar) {
from (sourceSets.main.allSource)
from (file("$projectDir/LICENSE"))
getArchiveClassifier().set('sources')
}
task shadowDevJar(type: ShadowJar) {
project.configurations.shadeCompile.each { dep ->
from(project.zipTree(dep)) {
exclude 'META-INF', 'META-INF/**'
}
}
from sourceSets.main.output
getArchiveClassifier().set("dev")
manifest {
attributes(getManifestAttributes())
}
minimize() // This will only allow shading for actually used classes
configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile]
}
task relocateShadowDevJar(type: ConfigureShadowRelocation) {
target = tasks.shadowDevJar
prefix = modGroup + ".shadow"
}
task circularResolverJar(type: Jar) {
dependsOn(relocateShadowDevJar)
dependsOn(shadowDevJar)
enabled = false
}
task devJar(type: Jar) {
project.configurations.shadeCompile.each { dep ->
from(project.zipTree(dep)) {
exclude 'META-INF', 'META-INF/**'
}
}
from sourceSets.main.output
getArchiveClassifier().set("dev")
manifest {
attributes(getManifestAttributes())
}
if(usesShadowedDependencies.toBoolean()) {
dependsOn(circularResolverJar)
enabled = false
}
}
task apiJar(type: Jar) {
from (sourceSets.main.allSource) {
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**'
}
from (sourceSets.main.output) {
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**'
}
from (sourceSets.main.resources.srcDirs) {
include("LICENSE")
}
getArchiveClassifier().set('api')
}
artifacts {
if(!noPublishedSources) {
archives sourcesJar
}
archives devJar
if(apiPackage) {
archives apiJar
}
}
// The gradle metadata includes all of the additional deps that we disabled from POM generation (including forgeBin with no groupID),
// and isn't strictly needed with the POM so just disable it.
tasks.withType(GenerateModuleMetadata) {
enabled = false
}
// workaround variable hiding in pom processing
def projectConfigs = project.configurations
publishing {
publications {
maven(MavenPublication) {
from components.java
if(usesShadowedDependencies.toBoolean()) {
artifact source: shadowJar, classifier: ""
}
if(!noPublishedSources) {
artifact source: sourcesJar, classifier: "sources"
}
artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev"
if (apiPackage) {
artifact source: apiJar, classifier: "api"
}
groupId = System.getenv("ARTIFACT_GROUP_ID") ?: "com.github.GTNewHorizons"
artifactId = System.getenv("ARTIFACT_ID") ?: project.name
// Using the identified version, not project.version as it has the prepended 1.7.10
version = System.getenv("RELEASE_VERSION") ?: identifiedVersion
// remove extra garbage from minecraft and minecraftDeps configuration
pom.withXml {
def badArtifacts = [:].withDefault {[] as Set<String>}
for (configuration in [projectConfigs.minecraft, projectConfigs.minecraftDeps]) {
for (dependency in configuration.allDependencies) {
badArtifacts[dependency.group == null ? "" : dependency.group] += dependency.name
}
}
// example for specifying extra stuff to ignore
// badArtifacts["org.example.group"] += "artifactName"
Node pomNode = asNode()
pomNode.dependencies.'*'.findAll() {
badArtifacts[it.groupId.text()].contains(it.artifactId.text())
}.each() {
it.parent().remove(it)
}
}
}
}
repositories {
maven {
url = "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases"
credentials {
username = System.getenv("MAVEN_USER") ?: "NONE"
password = System.getenv("MAVEN_PASSWORD") ?: "NONE"
}
}
}
}
// Updating
task updateBuildScript {
doLast {
if (performBuildScriptUpdate(projectDir.toString())) return
print("Build script already up-to-date!")
}
}
if (isNewBuildScriptVersionAvailable(projectDir.toString())) {
if (autoUpdateBuildScript.toBoolean()) {
performBuildScriptUpdate(projectDir.toString())
} else {
out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'")
}
}
static URL availableBuildScriptUrl() {
new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/main/build.gradle")
}
boolean performBuildScriptUpdate(String projectDir) {
if (isNewBuildScriptVersionAvailable(projectDir)) {
def buildscriptFile = getFile("build.gradle")
availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } }
out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!")
return true
}
return false
}
boolean isNewBuildScriptVersionAvailable(String projectDir) {
Map parameters = ["connectTimeout": 2000, "readTimeout": 2000]
String currentBuildScript = getFile("build.gradle").getText()
String currentBuildScriptHash = getVersionHash(currentBuildScript)
String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText()
String availableBuildScriptHash = getVersionHash(availableBuildScript)
boolean isUpToDate = currentBuildScriptHash.empty || availableBuildScriptHash.empty || currentBuildScriptHash == availableBuildScriptHash
return !isUpToDate
}
static String getVersionHash(String buildScriptContent) {
String versionLine = buildScriptContent.find("^//version: [a-z0-9]*")
if(versionLine != null) {
return versionLine.split(": ").last()
}
return ""
}
configure(updateBuildScript) {
group = 'forgegradle'
description = 'Updates the build script to the latest version'
}
// Deobfuscation
def deobf(String sourceURL) {
try {
URL url = new URL(sourceURL)
String fileName = url.getFile()
//get rid of directories:
int lastSlash = fileName.lastIndexOf("/")
if(lastSlash > 0) {
fileName = fileName.substring(lastSlash + 1)
}
//get rid of extension:
if(fileName.endsWith(".jar")) {
fileName = fileName.substring(0, fileName.lastIndexOf("."))
}
String hostName = url.getHost()
if(hostName.startsWith("www.")) {
hostName = hostName.substring(4)
}
List parts = Arrays.asList(hostName.split("\\."))
Collections.reverse(parts)
hostName = String.join(".", parts)
return deobf(sourceURL, hostName + "/" + fileName)
} catch(Exception e) {
return deobf(sourceURL, "deobf/" + String.valueOf(sourceURL.hashCode()))
}
}
// The method above is to be preferred. Use this method if the filename is not at the end of the URL.
def deobf(String sourceURL, String fileName) {
String cacheDir = System.getProperty("user.home") + "/.gradle/caches/"
String bon2Dir = cacheDir + "forge_gradle/deobf"
String bon2File = bon2Dir + "/BON2-2.5.0.jar"
String obfFile = cacheDir + "modules-2/files-2.1/" + fileName + ".jar"
String deobfFile = cacheDir + "modules-2/files-2.1/" + fileName + "-deobf.jar"
if(file(deobfFile).exists()) {
return files(deobfFile)
}
download.run {
src 'https://github.com/GTNewHorizons/BON2/releases/download/2.5.0/BON2-2.5.0.CUSTOM-all.jar'
dest bon2File
quiet true
overwrite false
}
download.run {
src sourceURL
dest obfFile
quiet true
overwrite false
}
exec {
commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', '1.7.10', '--mappingsVer', 'stable_12', '--notch'
workingDir bon2Dir
standardOutput = new ByteArrayOutputStream()
}
return files(deobfFile)
}
// 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 getFile(String relativePath) {
return new File(projectDir, relativePath)
}
+15 -26
View File
@@ -1,35 +1,24 @@
// Add your dependencies here
dependencies {
api('com.github.GTNewHorizons:EnderCore:0.5.15:dev') {transitive = false}
compileOnly('com.github.GTNewHorizons:ForestryMC:4.11.37:dev')
compileOnly('com.github.GTNewHorizons:NotEnoughItems:2.8.130-GTNH:dev')
api("com.github.GTNewHorizons:GTNHLib:0.11.45:dev")
compileOnly('com.github.GTNewHorizons:BuildCraft:7.1.63:dev')
api('curse.maven:cofh-lib-220333:2388748') // https://www.curseforge.com/minecraft/mc-mods/cofh-lib/files/2388748
compile('com.github.GTNewHorizons:EnderCore:0.2.6:dev')
compile('com.github.GTNewHorizons:ForestryMC:4.4.6:dev')
compile('com.github.GTNewHorizons:NotEnoughItems:2.2.15-GTNH:dev')
compile('com.github.GTNewHorizons:BuildCraft:7.1.27:dev')
compile('curse.maven:cofh-lib-220333:2388748') // https://www.curseforge.com/minecraft/mc-mods/cofh-lib/files/2388748
shadowImplementation('cglib:cglib-nodep:3.3.0')
api("com.github.GTNewHorizons:TinkersConstruct:1.14.107-GTNH:dev")
devOnlyNonPublishable('com.github.GTNewHorizons:waila:1.19.34:dev') {transitive = false}
compileOnly('ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.48-GTNH:dev') {transitive = false}
runtimeOnlyNonPublishable('com.github.GTNewHorizons:WAILAPlugins:0.7.2:dev') {transitive = false}
compileOnly("com.github.GTNewHorizons:Backhand:1.8.14:dev") { transitive = false }
compileOnly('com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-999-GTNH:api') {transitive = false}
compileOnly('com.github.GTNewHorizons:Baubles-Expanded:2.2.22-GTNH:dev') {transitive = false}
compileOnly('com.github.GTNewHorizons:GT5-Unofficial:5.09.54.129:dev') {transitive = false}
compileOnly("com.github.GTNewHorizons:ModularUI2:2.3.88-1.7.10:dev") {transitive = false}
compileOnly('com.github.GTNewHorizons:Railcraft:9.17.31:dev') {transitive = false}
compileOnly('com.github.GTNewHorizons:StorageDrawers:2.2.29-GTNH:api') {transitive = false}
compileOnly('com.github.GTNewHorizons:Chisel:2.17.32-GTNH:dev') {transitive = false}
compileOnly('com.github.GTNewHorizons:OpenComputers:1.12.61-GTNH:api') {transitive = false}
compileOnly('com.github.GTNewHorizons:waila:1.5.19:api') {transitive = false}
compileOnly('com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-85-GTNH:api') {transitive = false}
compileOnly('com.github.GTNewHorizons:Baubles:1.0.1.14:dev') {transitive = false}
compileOnly('com.github.GTNewHorizons:Railcraft:9.13.6:api') {transitive = false}
compileOnly('com.github.GTNewHorizons:StorageDrawers:1.11.13-GTNH:api') {transitive = false}
compile('com.github.GTNewHorizons:Chisel:2.10.8-GTNH:dev') {transitive = false}
compileOnly('com.github.GTNewHorizons:OpenComputers:1.7.5.25-GTNH:api') {transitive = false}
compileOnly('curse.maven:minefactory-reloaded-66672:2366150') // https://www.curseforge.com/minecraft/mc-mods/minefactory-reloaded/files/2366150
compileOnly('thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev')
compileOnly('curse.maven:ee3-65509:2305023') // https://www.curseforge.com/minecraft/mc-mods/ee3/files/2305023
compileOnly(rfg.deobf('curse.maven:computercraft-67504:2269339')) // https://www.curseforge.com/minecraft/mc-mods/computercraft/files/2269339
compileOnly(rfg.deobf('curse.maven:mekanism-268560:2475797')) // https://www.curseforge.com/minecraft/mc-mods/mekanism/files/2475797
compileOnly(rfg.deobf('maven.modrinth:immibis-microblocks:59.1.2')) // https://modrinth.com/mod/immibis-microblocks/version/59.1.2
compileOnly('com.github.GTNewHorizons:BetterBuildersWands:0.13.12-GTNH:dev@jar')
compileOnlyApi('com.github.GTNewHorizons:Angelica:2.2.10:api') {transitive = false}
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.196:dev")
compileOnly('curse.maven:automagy-222153:2285272')
compileOnly(deobf('https://media.forgecdn.net/files/2269/339/ComputerCraft1.75.jar')) // https://www.curseforge.com/minecraft/mc-mods/computercraft/files/2269339
compileOnly(deobf('https://media.forgecdn.net/files/2426/270/Mekanism-1.7.10-9.1.0.281.jar')) // https://aidancbrady.com/mekanism/download/
compileOnly(deobf('https://immibis.com/mcmoddl/files/immibis-microblocks-59.1.2.jar'))
}
+26 -204
View File
@@ -1,238 +1,60 @@
# ExampleMod tag to use as Blowdryer (Spotless, etc.) settings version, leave empty to disable.
# LOCAL to test local config updates.
gtnh.settings.blowdryerTag = 0.2.0
# Human-readable mod name, available for mcmod.info population.
modName = Ender IO
# Case-sensitive identifier string, available for mcmod.info population and used for automatic mixin JSON generation.
# Conventionally lowercase.
# This is a case-sensitive string to identify your mod. Convention is to use lower case.
modId = EnderIO
# Root package of the mod, used to find various classes in other properties,
# mcmod.info substitution, enabling assertions in run tasks, etc.
modGroup = crazypants.enderio
# Whether to use modGroup as the maven publishing group.
# When false, com.github.GTNewHorizons is used.
useModGroupForPublishing = false
# 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/
# Updates your build.gradle and settings.gradle automatically whenever an update is available.
# Will update your build.gradle automatically whenever an update is available
autoUpdateBuildScript = false
# Version of Minecraft to target
minecraftVersion = 1.7.10
# Version of Minecraft Forge to target
forgeVersion = 10.13.4.1614
# Specify an MCP channel for dependency deobfuscation and the deobfParams task.
channel = stable
# Specify an MCP mappings version for dependency deobfuscation and the deobfParams task.
mappingsVersion = 12
# Defines other MCP mappings for dependency deobfuscation.
remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/
# Select a default username for testing your mod. You can always override this per-run by running
# `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE.
# Select a username for testing your mod with breakpoints. You may leave this empty for a random user name 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 modern Java syntax support. Valid values:
# - false: No modern syntax, Java 8 only
# - jabel: Jabel syntax-only support, compiles to J8 bytecode
# - jvmDowngrader: Full modern Java via JVM Downgrader (syntax + stdlib APIs)
# - modern: Native modern Java bytecode, no downgrading
enableModernJavaSyntax = jabel
# If set, ignores the above setting and compiles with the given toolchain. This may cause unexpected issues,
# and should *not* be used in most situations. -1 disables this.
# forceToolchainVersion = -1
# Target JVM version for JVM Downgrader bytecode downgrading.
# Only used when enableModernJavaSyntax = jvmDowngrader
# downgradeTargetVersion = 8
# Comma-separated list of Java versions for multi-release jar support (JVM Downgrader only).
# Classes will be available in META-INF/versions/N/ for each version N in this list.
# Default: "21,25" (J25+ gets native classes, J21-24 gets partial downgrade, J8-20 gets full downgrade).
# jvmDowngraderMultiReleaseVersions = 21,25
# Specifies how JVM Downgrader API stubs are provided. Options:
# - shade: Shade minimized stubs into the jar
# - gtnhlib: GTNHLib provides stubs at runtime (adds version constraint)
# - external: Another dependency provides stubs (no constraint, no warning)
# - (empty): Warning reminding you to configure stubs
# Note: 'shade' option requires you to verify license compliance, see: https://github.com/unimined/JvmDowngrader/blob/main/LICENSE.md
# jvmDowngraderStubsProvider =
# Enables injecting missing generics into the decompiled source code for a better coding experience.
# Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types.
enableGenericInjection = true
# Generate a class with a String field for the mod version named as defined below.
# If generateGradleTokenClass is empty or not missing, no such class will be generated.
# If gradleTokenVersion is empty or missing, the field will not be present in the class.
generateGradleTokenClass = crazypants.enderio.Tags
# Name of the token containing the project's current version to generate/replace.
gradleTokenVersion = VERSION
# [DEPRECATED] Mod ID replacement token.
# Define a source file of your project with:
# public static final String VERSION = "GRADLETOKEN_VERSION";
# The string's content will be replaced with your mods 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 = EnderIO.java
gradleTokenModId =
# [DEPRECATED] Mod name replacement token.
gradleTokenModName =
# [DEPRECATED] Mod Group replacement token.
gradleTokenVersion = GRADLETOKEN_VERSION
gradleTokenGroupName =
# [DEPRECATED]
# Multiple source files can be defined here by providing a comma-separated 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
# 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
# Example value: apiPackage = api + modGroup = com.myname.mymodid -> com.myname.mymodid.api
apiPackage = api
# 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 space-separated list.
# Example value: mymodid_at.cfg nei_at.cfg
accessTransformersFile = enderio_at.cfg
# Specify the configuration file for Forge's access transformers here. I must be placed into /src/main/resources/META-INF/
# Example value: mymodid_at.cfg
accessTransformersFile =
# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled!
usesMixins = false
# Set to a non-empty string to configure mixins in a separate source set under src/VALUE, instead of src/main.
# This can speed up compile times thanks to not running the mixin annotation processor on all input sources.
# Mixin classes will have access to "main" classes, but not the other way around.
separateMixinSourceSet =
# Adds some debug arguments like verbose output and class 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. The package must exist or
# the build will fail. If you have a package property defined in your mixins.<modid>.json,
# it must match with this or the build will fail.
# 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
# This parameter is for legacy compatability 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 into your jar. It is your
# responsibility to check the license and request permission for distribution if required.
# If enabled, you may use 'shadowImplementation' for dependencies. They will be integrated in your jar. It is your
# responsibility check the licence and request permission for distribution, if required.
usesShadowedDependencies = true
# If disabled, won't remove unused classes from shadowed 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 CurseMaven, Modrinth, and some more well-known 1.7.10 repositories.
includeWellKnownRepositories = true
# A list of repositories to exclude from the includeWellKnownRepositories setting. Should be a space separated
# list of strings, with the acceptable keys being(case does not matter):
# cursemaven
# modrinth
excludeWellKnownRepositories =
# Change these to your Maven coordinates if you want to publish to a custom Maven repository instead of the default GTNH Maven.
# Authenticate with the MAVEN_USER and MAVEN_PASSWORD environment variables.
# If you need a more complex setup disable maven publishing here and add a publishing repository to addon.gradle.
usesMavenPublishing = true
# Maven repository to publish the mod to.
# mavenPublishUrl = https\://nexus.gtnewhorizons.com/repository/releases/
# Publishing to Modrinth requires you to set the MODRINTH_TOKEN environment variable to your current Modrinth API token.
#
# The project's ID on Modrinth. Can be either the slug or the ID.
# Leave this empty if you don't want to publish to 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: UniMixins 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: UniMixins is automatically set as a required dependency if usesMixins = true.
curseForgeRelations =
# Optional parameter to customize the produced artifacts. Use this to preserve artifact naming when migrating older
# projects. New projects should not use this parameter.
# customArchiveBaseName =
# Optional parameter to customize the default working directory used by the runClient* tasks. Relative to the project directory.
# runClientWorkingDirectory = run/client
# Optional parameter to customize the default working directory used by the runServer* tasks. Relative to the project directory.
# runServerWorkingDirectory = run/server
# Optional parameter to have the build automatically fail if an illegal version is used.
# This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'.
# The check is ONLY performed if the version is a git tag.
# Note: the specified string must be escaped, so e.g. 1\\.1\\.\\d+ instead of 1\.1\.\d+
# versionPattern =
# Uncomment to prevent the source code from being published.
# noPublishedSources = true
# Uncomment this to disable Spotless checks.
# This should only be uncommented to keep it easier to sync with upstream/other forks.
# That is, if there is no other active fork/upstream, NEVER change this.
# disableSpotless = true
# Uncomment this to disable Checkstyle checks (currently wildcard import check).
# disableCheckstyle = true
# Override the IDEA build type. Valid values are: "" (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 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
# Whether IDEA should run spotless checks when pressing the Build button.
# This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
org.gradle.configuration-cache = true
org.gradle.parallel = true
-12
View File
@@ -1,12 +0,0 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/539ea72837c6244075f8ee037babc29e/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/876dbbf00bf4ef6190f7da074cee903a/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/539ea72837c6244075f8ee037babc29e/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/876dbbf00bf4ef6190f7da074cee903a/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/9064f22734b42ac03e85df04b632e167/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/4d0277c49991306ac78048580fe34bcf/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/539ea72837c6244075f8ee037babc29e/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/876dbbf00bf4ef6190f7da074cee903a/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/a9fa3b809e484a1e1ac4308a5dda661a/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/aa99913fa6d767d899ffc96082da01ca/redirect
toolchainVersion=25
Binary file not shown.
+1 -3
View File
@@ -1,7 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+113 -173
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#!/usr/bin/env sh
#
# Copyright © 2015 the original authors.
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,114 +15,80 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# 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/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##
## Gradle start up script for UN*X
##
##############################################################################
# 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
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
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 ;;
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD=$JAVA_HOME/bin/java
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -131,118 +97,92 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
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
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=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
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 Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
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
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# 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"'
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
# 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" "$@"
Vendored
+34 -27
View File
@@ -13,10 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -27,14 +25,10 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
if "%DIRNAME%" == "" set DIRNAME=.
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"
@@ -43,13 +37,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
if "%ERRORLEVEL%" == "0" goto init
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
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
@@ -57,35 +51,48 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
if exist "%JAVA_EXE%" goto init
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
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
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
if "%ERRORLEVEL%"=="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%
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
+22
View File
@@ -1,4 +1,26 @@
// Add any additional repositories for your dependencies here
repositories {
maven {
name 'GTNH Maven'
url 'http://jenkins.usrv.eu:8081/nexus/content/groups/public/'
allowInsecureProtocol
}
maven {
name 'ic2'
url 'http://maven.ic2.player.to/'
metadataSources {
mavenPom()
artifact()
}
}
maven {
url 'https://cursemaven.com'
content {
includeGroup 'curse.maven'
}
}
maven {
url = 'https://jitpack.io'
}
}
-23
View File
@@ -1,23 +0,0 @@
pluginManagement {
repositories {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "https://nexus.gtnewhorizons.com/repository/public/"
mavenContent {
includeGroup("com.gtnewhorizons")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
}
}
gradlePluginPortal()
mavenCentral()
mavenLocal()
}
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.29'
}
+26 -29
View File
@@ -14,36 +14,33 @@ import crazypants.enderio.tool.ToolUtil;
public abstract class BlockEio extends BlockEnder {
protected BlockEio(String name, Class<? extends TileEntityEio> teClass) {
super(name, teClass);
setCreativeTab(EnderIOTab.tabEnderIO);
protected BlockEio(String name, Class<? extends TileEntityEio> teClass) {
super(name, teClass);
setCreativeTab(EnderIOTab.tabEnderIO);
}
protected BlockEio(String name, Class<? extends TileEntityEio> teClass, Material mat) {
super(name, teClass, mat);
setCreativeTab(EnderIOTab.tabEnderIO);
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float par7, float par8, float par9) {
if(shouldWrench(world, x, y, z, entityPlayer, side) && ToolUtil.breakBlockWithTool(this, world, x, y, z, entityPlayer)) {
return true;
}
TileEntity te = world.getTileEntity(x, y, z);
protected BlockEio(String name, Class<? extends TileEntityEio> teClass, Material mat) {
super(name, teClass, mat);
setCreativeTab(EnderIOTab.tabEnderIO);
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float par7,
float par8, float par9) {
if (shouldWrench(world, x, y, z, entityPlayer, side)
&& ToolUtil.breakBlockWithTool(this, world, x, y, z, entityPlayer)) {
return true;
}
TileEntity te = world.getTileEntity(x, y, z);
ITool tool = ToolUtil.getEquippedTool(entityPlayer);
if (tool != null && !entityPlayer.isSneaking()
&& tool.canUse(entityPlayer.getCurrentEquippedItem(), entityPlayer, x, y, z)) {
if (te instanceof AbstractMachineEntity) {
((AbstractMachineEntity) te).toggleIoModeForFace(ForgeDirection.getOrientation(side));
world.markBlockForUpdate(x, y, z);
return true;
}
}
return super.onBlockActivated(world, x, y, z, entityPlayer, side, par7, par8, par9);
ITool tool = ToolUtil.getEquippedTool(entityPlayer);
if(tool != null && !entityPlayer.isSneaking() && tool.canUse(entityPlayer.getCurrentEquippedItem(), entityPlayer, x, y, z)) {
if(te instanceof AbstractMachineEntity) {
((AbstractMachineEntity) te).toggleIoModeForFace(ForgeDirection.getOrientation(side));
world.markBlockForUpdate(x, y, z);
return true;
}
}
return super.onBlockActivated(world, x, y, z, entityPlayer, side, par7, par8, par9);
}
}
+347 -312
View File
@@ -1,5 +1,8 @@
package crazypants.enderio;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
@@ -27,29 +30,39 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.conduit.BlockConduitBundle;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.TileConduitBundle;
import crazypants.enderio.conduit.facade.FacadeRenderer;
import crazypants.enderio.conduit.gas.GasConduit;
import crazypants.enderio.conduit.gas.GasConduitRenderer;
import crazypants.enderio.conduit.gas.GasUtil;
import crazypants.enderio.conduit.item.ItemConduit;
import crazypants.enderio.conduit.liquid.AbstractEnderLiquidConduit;
import crazypants.enderio.conduit.liquid.AdvancedLiquidConduit;
import crazypants.enderio.conduit.liquid.AdvancedLiquidConduitRenderer;
import crazypants.enderio.conduit.liquid.CrystallineEnderLiquidConduit;
import crazypants.enderio.conduit.liquid.CrystallinePinkSlimeEnderLiquidConduit;
import crazypants.enderio.conduit.liquid.EnderLiquidConduit;
import crazypants.enderio.conduit.liquid.EnderLiquidConduitRenderer;
import crazypants.enderio.conduit.liquid.LiquidConduit;
import crazypants.enderio.conduit.liquid.LiquidConduitRenderer;
import crazypants.enderio.conduit.liquid.MelodicEnderLiquidConduit;
import crazypants.enderio.conduit.liquid.StellarEnderLiquidConduit;
import crazypants.enderio.conduit.me.MEConduit;
import crazypants.enderio.conduit.me.MEUtil;
import crazypants.enderio.conduit.oc.OCConduit;
import crazypants.enderio.conduit.oc.OCConduitRenderer;
import crazypants.enderio.conduit.oc.OCUtil;
import crazypants.enderio.conduit.power.PowerConduit;
import crazypants.enderio.conduit.power.PowerConduitRenderer;
import crazypants.enderio.conduit.power.endergy.PowerConduitEndergy;
import crazypants.enderio.conduit.redstone.InsulatedRedstoneConduit;
import crazypants.enderio.conduit.redstone.InsulatedRedstoneConduitRenderer;
import crazypants.enderio.conduit.redstone.RedstoneConduit;
import crazypants.enderio.conduit.redstone.RedstoneSwitch;
import crazypants.enderio.conduit.redstone.RedstoneSwitchRenderer;
import crazypants.enderio.conduit.render.ConduitBundleRenderer;
import crazypants.enderio.conduit.render.ConduitRenderer;
import crazypants.enderio.conduit.render.DefaultConduitRenderer;
import crazypants.enderio.conduit.render.ItemConduitRenderer;
import crazypants.enderio.config.Config;
import crazypants.enderio.enderface.EnderIoRenderer;
@@ -103,8 +116,11 @@ import crazypants.enderio.machine.painter.BlockPaintedFenceGateRenderer;
import crazypants.enderio.machine.painter.BlockPaintedGlowstone;
import crazypants.enderio.machine.painter.PaintedBlockRenderer;
import crazypants.enderio.machine.painter.PaintedItemRenderer;
import crazypants.enderio.machine.power.BlockCapacitorBank;
import crazypants.enderio.machine.power.CapBankRenderer2;
import crazypants.enderio.machine.power.CapacitorBankRenderer;
import crazypants.enderio.machine.ranged.RangeEntity;
import crazypants.enderio.machine.ranged.RangeRenderer;
import crazypants.enderio.machine.ranged.RangeRenerer;
import crazypants.enderio.machine.reservoir.ReservoirRenderer;
import crazypants.enderio.machine.reservoir.TileReservoir;
import crazypants.enderio.machine.solar.BlockSolarPanel;
@@ -139,336 +155,355 @@ import crazypants.enderio.teleport.telepad.TileTelePad;
@SideOnly(Side.CLIENT)
public class ClientProxy extends CommonProxy {
// @formatter:off
public static int[][] sideAndFacingToSpriteOffset = new int[][] {
{3, 2, 0, 0, 0, 0},
{2, 3, 1, 1, 1, 1},
{1, 1, 3, 2, 5, 4},
{0, 0, 2, 3, 4, 5},
{4, 5, 4, 5, 3, 2},
{5, 4, 5, 4, 2, 3}
};
// @formatter:on
// @formatter:off
public static int[][] sideAndFacingToSpriteOffset = new int[][] {
{ 3, 2, 0, 0, 0, 0 },
{ 2, 3, 1, 1, 1, 1 },
{ 1, 1, 3, 2, 5, 4 },
{ 0, 0, 2, 3, 4, 5 },
{ 4, 5, 4, 5, 3, 2 },
{ 5, 4, 5, 4, 2, 3 }
};
// @formatter:on
private ConduitBundleRenderer cbr;
private final List<ConduitRenderer> conduitRenderers = new ArrayList<ConduitRenderer>();
private boolean checkedNei = false;
private boolean neiInstalled = false;
private final DefaultConduitRenderer dcr = new DefaultConduitRenderer();
@Override
public World getClientWorld() {
return FMLClientHandler.instance().getClient().theWorld;
private ConduitBundleRenderer cbr;
private boolean checkedNei = false;
private boolean neiInstalled = false;
@Override
public World getClientWorld() {
return FMLClientHandler.instance().getClient().theWorld;
}
@Override
public boolean isNeiInstalled() {
if(checkedNei) {
return neiInstalled;
}
try {
Class.forName("crazypants.enderio.nei.EnchanterRecipeHandler");
neiInstalled = true;
} catch (Exception e) {
neiInstalled = false;
}
checkedNei = true;
return false;
}
@Override
public EntityPlayer getClientPlayer() {
return Minecraft.getMinecraft().thePlayer;
}
public ConduitBundleRenderer getConduitBundleRenderer() {
return cbr;
}
public void setCbr(ConduitBundleRenderer cbr) {
this.cbr = cbr;
}
@Override
public void loadIcons() {
RedstoneConduit.initIcons();
InsulatedRedstoneConduit.initIcons();
RedstoneSwitch.initIcons();
PowerConduit.initIcons();
PowerConduitEndergy.initIcons();
LiquidConduit.initIcons();
AdvancedLiquidConduit.initIcons();
AbstractEnderLiquidConduit.initIcons();
EnderLiquidConduit.initIcons();
CrystallineEnderLiquidConduit.initIcons();
CrystallinePinkSlimeEnderLiquidConduit.initIcons();
MelodicEnderLiquidConduit.initIcons();
StellarEnderLiquidConduit.initIcons();
ItemConduit.initIcons();
if(GasUtil.isGasConduitEnabled()) {
GasConduit.initIcons();
}
if(MEUtil.isMEEnabled()) {
MEConduit.initIcons();
}
if (OCUtil.isOCEnabled()) {
OCConduit.initIcons();
}
}
@Override
public void load() {
super.load();
SpecialTooltipHandler tt = SpecialTooltipHandler.INSTANCE;
tt.addCallback(new TooltipHandlerGrinding());
tt.addCallback(new TooltipHandlerBurnTime());
if (Config.addFuelTooltipsToAllFluidContainers) {
tt.addCallback(new TooltipHandlerFluid());
}
@Override
public boolean isNeiInstalled() {
if (checkedNei) {
return neiInstalled;
}
try {
Class.forName("crazypants.enderio.nei.EnchanterRecipeHandler");
neiInstalled = true;
} catch (Exception e) {
neiInstalled = false;
}
checkedNei = true;
return false;
// Renderers
AbstractMachineBlock.renderId = RenderingRegistry.getNextAvailableRenderId();
AbstractMachineRenderer machRen = new AbstractMachineRenderer();
RenderingRegistry.registerBlockHandler(machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockStirlingGenerator), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCrusher), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockAlloySmelter), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPowerMonitor), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPainter), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCrafter), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockBuffer), machRen);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemBrokenSpawner, new BrokenSpawnerRenderer());
BlockSolarPanel.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new SolarPanelRenderer());
EnchanterModelRenderer emr = new EnchanterModelRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileEnchanter.class, emr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEnchanter), emr);
BlockFusedQuartz.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new FusedQuartzRenderer());
BlockFarmStation.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new FarmingStationRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileFarmStation.class, new FarmingStationSpecialRenderer());
BlockSoulBinder.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new SoulBinderRenderer());
ObeliskRenderer defaultObeliskRenderer = new ObeliskRenderer();
BlockObeliskAbstract.defaultObeliskRenderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(defaultObeliskRenderer);
ObeliskSpecialRenderer<TileAttractor> attRen = new ObeliskSpecialRenderer<TileAttractor>(new ItemStack(EnderIO.itemMaterial, 1,
Material.ATTRACTOR_CRYSTAL.ordinal()), defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileAttractor.class, attRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockAttractor), attRen);
AversionObeliskRenderer sgr = new AversionObeliskRenderer(defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileAversionObelisk.class, sgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockSpawnGuard), sgr);
ObeliskSpecialRenderer<TileExperienceObelisk> eor = new ObeliskSpecialRenderer<TileExperienceObelisk>(new ItemStack(EnderIO.itemXpTransfer),
defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileExperienceObelisk.class, eor);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockExperianceOblisk), eor);
ObeliskSpecialRenderer<TileWeatherObelisk> twr = new WeatherObeliskSpecialRenderer(new ItemStack(Items.fireworks), defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileWeatherObelisk.class, twr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockWeatherObelisk), twr);
BlockCombustionGenerator.renderId = RenderingRegistry.getNextAvailableRenderId();
TechneMachineRenderer<TileCombustionGenerator> cr = new TechneMachineRenderer<TileCombustionGenerator>(EnderIO.blockCombustionGenerator, "models/combustionGen");
RenderingRegistry.registerBlockHandler(cr);
ZombieGeneratorRenderer zgr = new ZombieGeneratorRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileZombieGenerator.class, zgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockZombieGenerator), zgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockFrankenZombieGenerator), zgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEnderGenerator), zgr);
KillerJoeRenderer kjr = new KillerJoeRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileKillerJoe.class, kjr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockKillerJoe), kjr);
BlockVat.renderId = RenderingRegistry.getNextAvailableRenderId();
TechneMachineRenderer<TileVat> vr = new TechneMachineRenderer<TileVat>(EnderIO.blockVat, "models/vat");
RenderingRegistry.registerBlockHandler(vr);
FusedQuartzFrameRenderer fqfr = new FusedQuartzFrameRenderer();
MinecraftForgeClient.registerItemRenderer(EnderIO.itemFusedQuartzFrame, fqfr);
BlockElectricLight.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new ElectricLightRenderer());
if(EnderIO.blockCapBank != null) {
BlockCapBank.renderId = RenderingRegistry.getNextAvailableRenderId();
CapBankRenderer newCbr = new CapBankRenderer();
RenderingRegistry.registerBlockHandler(newCbr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCapBank), newCbr);
ClientRegistry.bindTileEntitySpecialRenderer(TileCapBank.class, newCbr);
}
@Override
public EntityPlayer getClientPlayer() {
return Minecraft.getMinecraft().thePlayer;
CapacitorBankRenderer capr = new CapacitorBankRenderer();
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCapacitorBank), capr);
BlockCapacitorBank.renderId = RenderingRegistry.getNextAvailableRenderId();
CapBankRenderer2 cbr2 = new CapBankRenderer2();
RenderingRegistry.registerBlockHandler(cbr2);
BlockVacuumChest.renderId = RenderingRegistry.getNextAvailableRenderId();
VacuumChestRenderer vcr = new VacuumChestRenderer();
RenderingRegistry.registerBlockHandler(vcr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockVacuumChest), vcr);
ItemConduitRenderer itemConRenderer = new ItemConduitRenderer();
MinecraftForgeClient.registerItemRenderer(EnderIO.itemLiquidConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemPowerConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemPowerConduitEndergy, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemRedstoneConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemItemConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemGasConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemMEConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemOCConduit, itemConRenderer);
BlockPaintedFenceGateRenderer bcfgr = new BlockPaintedFenceGateRenderer();
BlockPaintedFenceGate.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(bcfgr);
PaintedItemRenderer pir = new PaintedItemRenderer();
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedFence), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedFenceGate), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedWall), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedStair), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedSlab), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedGlowstone), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedCarpet), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockDarkSteelPressurePlate), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTravelPlatform), pir);
BlockPaintedGlowstone.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new PaintedBlockRenderer(BlockPaintedGlowstone.renderId, Blocks.glowstone));
BlockTravelAnchor.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new PaintedBlockRenderer(BlockTravelAnchor.renderId, EnderIO.blockTravelPlatform));
BlockTelePad.renderId = RenderingRegistry.getNextAvailableRenderId();
TelePadRenderer telePadRenderer = new TelePadRenderer();
RenderingRegistry.registerBlockHandler(telePadRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileTelePad.class, new TelePadSpecialRenderer(telePadRenderer));
MinecraftForgeClient.registerItemRenderer(EnderIO.itemMachinePart, new MachinePartRenderer());
MinecraftForgeClient.registerItemRenderer(EnderIO.itemConduitFacade, new FacadeRenderer());
cbr = new ConduitBundleRenderer((float) Config.conduitScale);
BlockConduitBundle.rendererId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(cbr);
ClientRegistry.bindTileEntitySpecialRenderer(TileConduitBundle.class, cbr);
ClientRegistry.bindTileEntitySpecialRenderer(TileTravelAnchor.class, new TravelEntitySpecialRenderer());
BlockEndermanSkull.renderId = RenderingRegistry.getNextAvailableRenderId();
EndermanSkullRenderer esk = new EndermanSkullRenderer();
RenderingRegistry.registerBlockHandler(esk);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEndermanSkull), esk);
conduitRenderers.add(RedstoneSwitchRenderer.getInstance());
conduitRenderers.add(new AdvancedLiquidConduitRenderer());
conduitRenderers.add(LiquidConduitRenderer.create());
conduitRenderers.add(new PowerConduitRenderer());
conduitRenderers.add(new InsulatedRedstoneConduitRenderer());
conduitRenderers.add(new EnderLiquidConduitRenderer());
conduitRenderers.add(new crazypants.enderio.conduit.item.ItemConduitRenderer());
if(GasUtil.isGasConduitEnabled()) {
conduitRenderers.add(new GasConduitRenderer());
}
if (OCUtil.isOCEnabled()) {
conduitRenderers.add(new OCConduitRenderer());
}
public ConduitBundleRenderer getConduitBundleRenderer() {
return cbr;
EnderIoRenderer eior = new EnderIoRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileEnderIO.class, eior);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEnderIo), eior);
ClientRegistry.bindTileEntitySpecialRenderer(TileReservoir.class, new ReservoirRenderer(EnderIO.blockReservoir));
ClientRegistry.bindTileEntitySpecialRenderer(TileTank.class, new TankFluidRenderer());
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTank), new TankItemRenderer());
HyperCubeRenderer hcr = new HyperCubeRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileHyperCube.class, hcr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockHyperCube), hcr);
if(Config.transceiverEnabled) {
TransceiverRenderer tr = new TransceiverRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileTransceiver.class, tr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTransceiver), tr);
}
public void setCbr(ConduitBundleRenderer cbr) {
this.cbr = cbr;
new YetaWrenchOverlayRenderer();
new ConduitProbeOverlayRenderer();
if(Config.useSneakMouseWheelYetaWrench) {
ToolTickHandler th = new ToolTickHandler();
MinecraftForge.EVENT_BUS.register(th);
FMLCommonHandler.instance().bus().register(th);
}
MinecraftForge.EVENT_BUS.register(TravelController.instance);
FMLCommonHandler.instance().bus().register(TravelController.instance);
DarkSteelItems.registerItemRenderer();
FMLCommonHandler.instance().bus().register(KeyTracker.instance);
RenderingRegistry.registerEntityRenderingHandler(SoundEntity.class, new SoundRenderer());
RenderingRegistry.registerEntityRenderingHandler(RangeEntity.class, new RangeRenerer());
MinecraftForge.EVENT_BUS.register(SoundDetector.instance);
FMLCommonHandler.instance().bus().register(SoundDetector.instance);
if(!Loader.isModLoaded("OpenBlocks")) {
//We have registered liquid XP so we need to give it textures
IconUtil.addIconProvider(new IconUtil.IIconProvider() {
@Override
public void registerIcons(IIconRegister register) {
//NB: textures re-used with permission from OpenBlocks to maintain look
IIcon flowing = register.registerIcon("enderio:xpjuiceflowing");
IIcon still = register.registerIcon("enderio:xpjuicestill");
EnderIO.fluidXpJuice.setIcons(still, flowing);
}
@Override
public int getTextureType() {
return 0;
}
});
}
@Override
public void loadIcons() {
RedstoneConduit.initIcons();
InsulatedRedstoneConduit.initIcons();
RedstoneSwitch.initIcons();
PowerConduit.initIcons();
PowerConduitEndergy.initIcons();
LiquidConduit.initIcons();
AdvancedLiquidConduit.initIcons();
AbstractEnderLiquidConduit.initIcons();
EnderLiquidConduit.initIcons();
CrystallineEnderLiquidConduit.initIcons();
CrystallinePinkSlimeEnderLiquidConduit.initIcons();
MelodicEnderLiquidConduit.initIcons();
StellarEnderLiquidConduit.initIcons();
ItemConduit.initIcons();
if (GasUtil.isGasConduitEnabled()) {
GasConduit.initIcons();
}
if (MEUtil.isMEEnabled()) {
MEConduit.initIcons();
}
if (OCUtil.isOCEnabled()) {
OCConduit.initIcons();
}
MinecraftForge.EVENT_BUS.register(new TeleportEntityRenderHandler());
}
@Override
public ConduitRenderer getRendererForConduit(IConduit conduit) {
for (ConduitRenderer renderer : conduitRenderers) {
if(renderer.isRendererForConduit(conduit)) {
return renderer;
}
}
return dcr;
}
@Override
public void load() {
super.load();
SpecialTooltipHandler tt = SpecialTooltipHandler.INSTANCE;
tt.addCallback(new TooltipHandlerGrinding());
tt.addCallback(new TooltipHandlerBurnTime());
if (Config.addFuelTooltipsToAllFluidContainers) {
tt.addCallback(new TooltipHandlerFluid());
}
// Renderers
AbstractMachineBlock.renderId = RenderingRegistry.getNextAvailableRenderId();
AbstractMachineRenderer machRen = new AbstractMachineRenderer();
RenderingRegistry.registerBlockHandler(machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockStirlingGenerator), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCrusher), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockAlloySmelter), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPowerMonitor), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPainter), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCrafter), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockBuffer), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPoweredSpawner), machRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockSliceAndSplice), machRen);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemBrokenSpawner, new BrokenSpawnerRenderer());
BlockSolarPanel.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new SolarPanelRenderer());
EnchanterModelRenderer emr = new EnchanterModelRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileEnchanter.class, emr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEnchanter), emr);
BlockFusedQuartz.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new FusedQuartzRenderer());
BlockFarmStation.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new FarmingStationRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileFarmStation.class, new FarmingStationSpecialRenderer());
BlockSoulBinder.renderId = RenderingRegistry.getNextAvailableRenderId();
SoulBinderRenderer soulBinderRenderer = new SoulBinderRenderer();
RenderingRegistry.registerBlockHandler(soulBinderRenderer);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockSoulFuser), soulBinderRenderer);
ObeliskRenderer defaultObeliskRenderer = new ObeliskRenderer();
BlockObeliskAbstract.defaultObeliskRenderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(defaultObeliskRenderer);
ObeliskSpecialRenderer<TileAttractor> attRen = new ObeliskSpecialRenderer<>(
new ItemStack(EnderIO.itemMaterial, 1, Material.ATTRACTOR_CRYSTAL.ordinal()),
defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileAttractor.class, attRen);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockAttractor), attRen);
AversionObeliskRenderer sgr = new AversionObeliskRenderer(defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileAversionObelisk.class, sgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockSpawnGuard), sgr);
ObeliskSpecialRenderer<TileExperienceObelisk> eor = new ObeliskSpecialRenderer<>(
new ItemStack(EnderIO.itemXpTransfer),
defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileExperienceObelisk.class, eor);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockExperianceOblisk), eor);
ObeliskSpecialRenderer<TileWeatherObelisk> twr = new WeatherObeliskSpecialRenderer(
new ItemStack(Items.fireworks),
defaultObeliskRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileWeatherObelisk.class, twr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockWeatherObelisk), twr);
BlockCombustionGenerator.renderId = RenderingRegistry.getNextAvailableRenderId();
TechneMachineRenderer<TileCombustionGenerator> cr = new TechneMachineRenderer<>(
EnderIO.blockCombustionGenerator,
"models/combustionGen");
RenderingRegistry.registerBlockHandler(cr);
ZombieGeneratorRenderer zgr = new ZombieGeneratorRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileZombieGenerator.class, zgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockZombieGenerator), zgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockFrankenZombieGenerator), zgr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEnderGenerator), zgr);
KillerJoeRenderer kjr = new KillerJoeRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileKillerJoe.class, kjr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockKillerJoe), kjr);
BlockVat.renderId = RenderingRegistry.getNextAvailableRenderId();
TechneMachineRenderer<TileVat> vr = new TechneMachineRenderer<>(EnderIO.blockVat, "models/vat");
RenderingRegistry.registerBlockHandler(vr);
FusedQuartzFrameRenderer fqfr = new FusedQuartzFrameRenderer();
MinecraftForgeClient.registerItemRenderer(EnderIO.itemFusedQuartzFrame, fqfr);
BlockElectricLight.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(new ElectricLightRenderer());
if (EnderIO.blockCapBank != null) {
BlockCapBank.renderId = RenderingRegistry.getNextAvailableRenderId();
CapBankRenderer newCbr = new CapBankRenderer();
RenderingRegistry.registerBlockHandler(newCbr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockCapBank), newCbr);
ClientRegistry.bindTileEntitySpecialRenderer(TileCapBank.class, newCbr);
}
BlockVacuumChest.renderId = RenderingRegistry.getNextAvailableRenderId();
VacuumChestRenderer vcr = new VacuumChestRenderer();
RenderingRegistry.registerBlockHandler(vcr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockVacuumChest), vcr);
ItemConduitRenderer itemConRenderer = new ItemConduitRenderer();
MinecraftForgeClient.registerItemRenderer(EnderIO.itemLiquidConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemPowerConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemPowerConduitEndergy, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemRedstoneConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemItemConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemGasConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemMEConduit, itemConRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemOCConduit, itemConRenderer);
BlockPaintedFenceGateRenderer bcfgr = new BlockPaintedFenceGateRenderer();
BlockPaintedFenceGate.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(bcfgr);
PaintedItemRenderer pir = new PaintedItemRenderer();
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedFence), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedFenceGate), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedWall), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedStair), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedSlab), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedGlowstone), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockPaintedCarpet), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockDarkSteelPressurePlate), pir);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTravelPlatform), pir);
BlockPaintedGlowstone.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry
.registerBlockHandler(new PaintedBlockRenderer(BlockPaintedGlowstone.renderId, Blocks.glowstone));
BlockTravelAnchor.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(
new PaintedBlockRenderer(BlockTravelAnchor.renderId, EnderIO.blockTravelPlatform));
BlockTelePad.renderId = RenderingRegistry.getNextAvailableRenderId();
TelePadRenderer telePadRenderer = new TelePadRenderer();
RenderingRegistry.registerBlockHandler(telePadRenderer);
ClientRegistry.bindTileEntitySpecialRenderer(TileTelePad.class, new TelePadSpecialRenderer(telePadRenderer));
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTelePad), telePadRenderer);
MinecraftForgeClient.registerItemRenderer(EnderIO.itemMachinePart, new MachinePartRenderer());
MinecraftForgeClient.registerItemRenderer(EnderIO.itemConduitFacade, new FacadeRenderer());
cbr = new ConduitBundleRenderer((float) Config.conduitScale);
BlockConduitBundle.rendererId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(cbr);
ClientRegistry.bindTileEntitySpecialRenderer(TileTravelAnchor.class, new TravelEntitySpecialRenderer());
BlockEndermanSkull.renderId = RenderingRegistry.getNextAvailableRenderId();
EndermanSkullRenderer esk = new EndermanSkullRenderer();
RenderingRegistry.registerBlockHandler(esk);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEndermanSkull), esk);
EnderIoRenderer eior = new EnderIoRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileEnderIO.class, eior);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockEnderIo), eior);
ClientRegistry
.bindTileEntitySpecialRenderer(TileReservoir.class, new ReservoirRenderer(EnderIO.blockReservoir));
ClientRegistry.bindTileEntitySpecialRenderer(TileTank.class, new TankFluidRenderer());
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTank), new TankItemRenderer());
HyperCubeRenderer hcr = new HyperCubeRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileHyperCube.class, hcr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockHyperCube), hcr);
if (Config.transceiverEnabled) {
TransceiverRenderer tr = new TransceiverRenderer();
ClientRegistry.bindTileEntitySpecialRenderer(TileTransceiver.class, tr);
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(EnderIO.blockTransceiver), tr);
}
new YetaWrenchOverlayRenderer();
new ConduitProbeOverlayRenderer();
if (Config.useSneakMouseWheelYetaWrench) {
ToolTickHandler th = new ToolTickHandler();
MinecraftForge.EVENT_BUS.register(th);
FMLCommonHandler.instance().bus().register(th);
}
MinecraftForge.EVENT_BUS.register(TravelController.instance);
FMLCommonHandler.instance().bus().register(TravelController.instance);
DarkSteelItems.registerItemRenderer();
FMLCommonHandler.instance().bus().register(KeyTracker.instance);
RenderingRegistry.registerEntityRenderingHandler(SoundEntity.class, new SoundRenderer());
RenderingRegistry.registerEntityRenderingHandler(RangeEntity.class, new RangeRenderer());
MinecraftForge.EVENT_BUS.register(SoundDetector.instance);
FMLCommonHandler.instance().bus().register(SoundDetector.instance);
if (!Loader.isModLoaded("OpenBlocks")) {
// We have registered liquid XP so we need to give it textures
IconUtil.addIconProvider(new IconUtil.IIconProvider() {
@Override
public void registerIcons(IIconRegister register) {
// NB: textures re-used with permission from OpenBlocks to maintain look
IIcon flowing = register.registerIcon("enderio:xpjuiceflowing");
IIcon still = register.registerIcon("enderio:xpjuicestill");
EnderIO.fluidXpJuice.setIcons(still, flowing);
}
@Override
public int getTextureType() {
return 0;
}
});
}
MinecraftForge.EVENT_BUS.register(new TeleportEntityRenderHandler());
@Override
public double getReachDistanceForPlayer(EntityPlayer entityPlayer) {
if(entityPlayer instanceof EntityPlayerMP) {
return ((EntityPlayerMP) entityPlayer).theItemInWorldManager.getBlockReachDistance();
}
return super.getReachDistanceForPlayer(entityPlayer);
}
@Override
public ConduitRenderer getRendererForConduit(IConduit conduit) {
return conduit.getRenderer();
}
@Override
public void setInstantConfusionOnPlayer(EntityPlayer ent, int duration) {
ent.addPotionEffect(new PotionEffect(Potion.confusion.getId(), duration, 1, true));
Minecraft.getMinecraft().thePlayer.timeInPortal = 1;
}
@Override
public double getReachDistanceForPlayer(EntityPlayer entityPlayer) {
if (entityPlayer instanceof EntityPlayerMP) {
return ((EntityPlayerMP) entityPlayer).theItemInWorldManager.getBlockReachDistance();
}
return super.getReachDistanceForPlayer(entityPlayer);
}
@Override
public long getTickCount() {
return clientTickCount;
}
@Override
public void setInstantConfusionOnPlayer(EntityPlayer ent, int duration) {
ent.addPotionEffect(new PotionEffect(Potion.confusion.getId(), duration, 1, true));
Minecraft.getMinecraft().thePlayer.timeInPortal = 1;
@Override
protected void onClientTick() {
if(!Minecraft.getMinecraft().isGamePaused() && Minecraft.getMinecraft().theWorld != null) {
++clientTickCount;
}
}
@Override
public long getTickCount() {
return clientTickCount;
}
@Override
protected void onClientTick() {
if (!Minecraft.getMinecraft().isGamePaused() && Minecraft.getMinecraft().theWorld != null) {
++clientTickCount;
}
}
}
@@ -1,120 +1,87 @@
package crazypants.enderio;
import java.text.DecimalFormat;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent;
import crazypants.enderio.conduit.ConduitNetworkTickHandler;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.render.ConduitRenderer;
import crazypants.enderio.machine.hypercube.HyperCubeRegister;
import crazypants.enderio.machine.transceiver.ServerChannelRegister;
import crazypants.enderio.machine.wireless.WirelessChargerController;
public class CommonProxy {
protected long serverTickCount = 0;
protected long clientTickCount = 0;
protected final TickTimer tickTimer = new TickTimer();
public ConduitNetworkTickHandler conduitNetworkTickHandler = null;
public WirelessChargerController wirelessChargerController = null;
private static final DecimalFormat FORMAT = new DecimalFormat("########0.000");
public CommonProxy() {}
protected long serverTickCount = 0;
protected long clientTickCount = 0;
protected final TickTimer tickTimer = new TickTimer();
public World getClientWorld() {
return null;
public CommonProxy() {
}
public World getClientWorld() {
return null;
}
public EntityPlayer getClientPlayer() {
return null;
}
public ConduitRenderer getRendererForConduit(IConduit conduit) {
return null;
}
public double getReachDistanceForPlayer(EntityPlayer entityPlayer) {
return 5;
}
public void loadIcons() {
;
}
public void load() {
FMLCommonHandler.instance().bus().register(tickTimer);
}
public long getTickCount() {
return serverTickCount;
}
public boolean isNeiInstalled() {
return false;
}
public void setInstantConfusionOnPlayer(EntityPlayer ent, int duration) {
ent.addPotionEffect(new PotionEffect(Potion.confusion.getId(), duration, 1, true));
}
protected void onServerTick() {
++serverTickCount;
}
protected void onClientTick() {
}
public final class TickTimer {
@SubscribeEvent
public void onTick(ServerTickEvent evt) {
if(evt.phase == Phase.END) {
onServerTick();
}
}
public EntityPlayer getClientPlayer() {
return null;
}
@Deprecated
public ConduitRenderer getRendererForConduit(IConduit conduit) {
return null;
}
public double getReachDistanceForPlayer(EntityPlayer entityPlayer) {
return 5;
}
public void loadIcons() {
}
public void load() {
FMLCommonHandler.instance().bus().register(tickTimer);
}
public long getTickCount() {
return serverTickCount;
}
public boolean isNeiInstalled() {
return false;
}
public void setInstantConfusionOnPlayer(EntityPlayer ent, int duration) {
ent.addPotionEffect(new PotionEffect(Potion.confusion.getId(), duration, 1, true));
}
protected void onServerTick() {
++serverTickCount;
}
protected void onClientTick() {}
private static final String TEXTURE_PATH = ":textures/gui/23/";
private static final String TEXTURE_EXT = ".png";
public ResourceLocation getGuiTexture(String name) {
return new ResourceLocation(EnderIO.DOMAIN + TEXTURE_PATH + name + TEXTURE_EXT);
}
public void onServerAboutToStart(FMLServerAboutToStartEvent event) {
conduitNetworkTickHandler = new ConduitNetworkTickHandler();
FMLCommonHandler.instance().bus().register(conduitNetworkTickHandler);
wirelessChargerController = new WirelessChargerController();
FMLCommonHandler.instance().bus().register(wirelessChargerController);
}
public void onServerStarted(FMLServerStartedEvent event) {
HyperCubeRegister.load();
ServerChannelRegister.load();
}
public void onServerStopped(FMLServerStoppedEvent event) {
HyperCubeRegister.unload();
FMLCommonHandler.instance().bus().unregister(conduitNetworkTickHandler);
conduitNetworkTickHandler = null;
FMLCommonHandler.instance().bus().unregister(wirelessChargerController);
wirelessChargerController = null;
}
public final class TickTimer {
@SubscribeEvent
public void onTick(ServerTickEvent evt) {
if (evt.phase == Phase.END) {
onServerTick();
}
}
@SubscribeEvent
public void onTick(ClientTickEvent evt) {
if (evt.phase == Phase.END) {
onClientTick();
}
}
@SubscribeEvent
public void onTick(ClientTickEvent evt) {
if(evt.phase == Phase.END) {
onClientTick();
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,36 +1,36 @@
package crazypants.enderio;
import static crazypants.enderio.EnderIO.MODID;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import static crazypants.enderio.EnderIO.MODID;
public class EnderIOTab extends CreativeTabs {
public static final CreativeTabs tabEnderIO = new EnderIOTab();
public static final CreativeTabs tabEnderIO = new EnderIOTab();
public EnderIOTab() {
super(MODID);
}
public EnderIOTab() {
super(MODID);
}
@Override
@SideOnly(Side.CLIENT)
public String getTabLabel() {
return MODID;
}
@Override
@SideOnly(Side.CLIENT)
public String getTabLabel() {
return MODID;
}
@Override
@SideOnly(Side.CLIENT)
public String getTranslatedTabLabel() {
return MODID;
}
@Override
@SideOnly(Side.CLIENT)
public String getTranslatedTabLabel() {
return MODID;
}
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return EnderIO.itemEnderface;
}
@Override
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return EnderIO.itemEnderface;
}
}
@@ -6,81 +6,81 @@ import java.util.Map;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.common.network.IGuiHandler;
public class GuiHandler implements IGuiHandler {
public static final int GUI_ID_ENDERFACE = 1;
public static final int GUI_ID_PAINTER = 2;
public static final int GUI_ID_STIRLING_GEN = 3;
public static final int GUI_ID_ALLOY_SMELTER = 4;
public static final int GUI_ID_CAPACITOR_BANK = 5;
public static final int GUI_ID_CRUSHER = 6;
public static final int GUI_ID_HYPER_CUBE = 7;
public static final int GUI_ID_POWER_MONITOR = 8;
public static final int GUI_ID_ENDERFACE = 1;
public static final int GUI_ID_PAINTER = 2;
public static final int GUI_ID_STIRLING_GEN = 3;
public static final int GUI_ID_ALLOY_SMELTER = 4;
public static final int GUI_ID_CAPACITOR_BANK = 5;
public static final int GUI_ID_CRUSHER = 6;
public static final int GUI_ID_HYPER_CUBE = 7;
public static final int GUI_ID_POWER_MONITOR = 8;
public static final int GUI_ID_EXTERNAL_CONNECTION_BASE = 9;
public static final int GUI_ID_EXTERNAL_CONNECTION_UP = 9 + ForgeDirection.UP.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_DOWN = 9 + ForgeDirection.DOWN.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_NORTH = 9 + ForgeDirection.NORTH.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_SOUTH = 9 + ForgeDirection.SOUTH.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_EAST = 9 + ForgeDirection.EAST.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_WEST = 9 + ForgeDirection.WEST.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_SELECTOR = 16;
public static final int GUI_ID_EXTERNAL_CONNECTION_BASE = 9;
public static final int GUI_ID_EXTERNAL_CONNECTION_UP = 9 + ForgeDirection.UP.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_DOWN = 9 + ForgeDirection.DOWN.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_NORTH = 9 + ForgeDirection.NORTH.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_SOUTH = 9 + ForgeDirection.SOUTH.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_EAST = 9 + ForgeDirection.EAST.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_WEST = 9 + ForgeDirection.WEST.ordinal();
public static final int GUI_ID_EXTERNAL_CONNECTION_SELECTOR = 16;
public static final int GUI_ID_ME_ACCESS_TERMINAL = 17;
public static final int GUI_ID_ME_ACCESS_TERMINAL = 17;
public static final int GUI_ID_TRAVEL_ACCESSABLE = 18;
public static final int GUI_ID_TRAVEL_AUTH = 19;
public static final int GUI_ID_STILL = 20;
public static final int GUI_ID_COMBUSTION_GEN = 21;
public static final int GUI_ID_FARM_STATATION = 22;
public static final int GUI_ID_TANK = 86;
public static final int GUI_ID_CRAFTER = 87;
public static final int GUI_ID_ZOMBIE_GEN = 71;
public static final int GUI_ID_POWERED_SPAWNER = 88;
public static final int GUI_ID_VACUUM_CHEST = 89;
public static final int GUI_ID_WIRELESS_CHARGER = 90;
public static final int GUI_ID_ENCHANTER = 91;
public static final int GUI_ID_KILLER_JOE = 92;
public static final int GUI_ID_SOUL_BINDER = 93;
public static final int GUI_ID_SLICE_N_SPLICE = 94;
public static final int GUI_ID_ATTRACTOR = 95;
public static final int GUI_ID_SPAWN_GUARD = 96;
public static final int GUI_ID_TRANSCEIVER = 97;
public static final int GUI_ID_XP_OBELISK = 98;
public static final int GUI_ID_ANVIL = 99;
public static final int GUI_ID_BUFFER = 100;
public static final int GUI_ID_WEATHER_OBELISK = 101;
public static final int GUI_ID_TELEPAD = 102;
public static final int GUI_ID_TELEPAD_TRAVEL = 103;
public static final int GUI_ID_INHIBITOR = 104;
public static final int GUI_ID_INVENTORY_PANEL = 105;
public static final int GUI_ID_TRAVEL_ACCESSABLE = 18;
public static final int GUI_ID_TRAVEL_AUTH = 19;
public static final int GUI_ID_STILL = 20;
public static final int GUI_ID_COMBUSTION_GEN = 21;
public static final int GUI_ID_FARM_STATATION = 22;
public static final int GUI_ID_TANK = 86;
public static final int GUI_ID_CRAFTER = 87;
public static final int GUI_ID_ZOMBIE_GEN = 71;
public static final int GUI_ID_POWERED_SPAWNER = 88;
public static final int GUI_ID_VACUUM_CHEST = 89;
public static final int GUI_ID_WIRELESS_CHARGER = 90;
public static final int GUI_ID_ENCHANTER = 91;
public static final int GUI_ID_KILLER_JOE = 92;
public static final int GUI_ID_SOUL_BINDER = 93;
public static final int GUI_ID_SLICE_N_SPLICE = 94;
public static final int GUI_ID_ATTRACTOR = 95;
public static final int GUI_ID_SPAWN_GUARD = 96;
public static final int GUI_ID_TRANSCEIVER = 97;
public static final int GUI_ID_XP_OBELISK = 98;
public static final int GUI_ID_ANVIL = 99;
public static final int GUI_ID_BUFFER = 100;
public static final int GUI_ID_WEATHER_OBELISK = 101;
public static final int GUI_ID_TELEPAD = 102;
public static final int GUI_ID_TELEPAD_TRAVEL = 103;
public static final int GUI_ID_INHIBITOR = 104;
public static final int GUI_ID_INVENTORY_PANEL = 105;
public static final int GUI_ID_CAP_BANK = 142; // leave room for more machines
public static final int GUI_ID_CAP_BANK = 142; // leave room for more machines
protected final Map<Integer, IGuiHandler> guiHandlers = new HashMap<>();
protected final Map<Integer, IGuiHandler> guiHandlers = new HashMap<Integer, IGuiHandler>();
public void registerGuiHandler(int id, IGuiHandler handler) {
guiHandlers.put(id, handler);
public void registerGuiHandler(int id, IGuiHandler handler) {
guiHandlers.put(id, handler);
}
@Override
public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
IGuiHandler handler = guiHandlers.get(id);
if(handler != null) {
return handler.getServerGuiElement(id, player, world, x, y, z);
}
return null;
}
@Override
public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
IGuiHandler handler = guiHandlers.get(id);
if (handler != null) {
return handler.getServerGuiElement(id, player, world, x, y, z);
}
return null;
@Override
public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
IGuiHandler handler = guiHandlers.get(id);
if(handler != null) {
return handler.getClientGuiElement(id, player, world, x, y, z);
}
return null;
}
@Override
public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {
IGuiHandler handler = guiHandlers.get(id);
if (handler != null) {
return handler.getClientGuiElement(id, player, world, x, y, z);
}
return null;
}
}
+17 -17
View File
@@ -2,29 +2,29 @@ package crazypants.enderio;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
public final class Log {
public static final Logger LOGGER = LogManager.getLogger(EnderIO.MODID);
public static final Marker securityMarker = MarkerManager.getMarker("SuspiciousPackets");
public static final Logger LOGGER = LogManager.getLogger(EnderIO.MODID);
public static void warn(String msg) {
LOGGER.warn(msg);
}
public static void warn(String msg) {
LOGGER.warn(msg);
}
public static void error(String msg) {
LOGGER.error(msg);
}
public static void error(String msg) {
LOGGER.error(msg);
}
public static void info(String msg) {
LOGGER.info(msg);
}
public static void info(String msg) {
LOGGER.info(msg);
}
public static void debug(String msg) {
LOGGER.debug(msg);
}
public static void debug(String msg) {
LOGGER.debug(msg);
}
private Log() {
}
private Log() {}
}
+110 -112
View File
@@ -1,133 +1,131 @@
package crazypants.enderio;
public enum ModObject {
// Enderface
blockEnderIo,
itemEnderface,
// Enderface
blockEnderIo,
itemEnderface,
// Conduits
blockConduitBundle,
blockConduitFacade,
itemConduitFacade,
itemRedstoneConduit,
itemItemConduit,
itemGasConduit,
itemMEConduit,
itemOCConduit,
itemBasicFilterUpgrade,
itemBigFilterUpgrade,
itemExistingItemFilter,
itemModItemFilter,
itemPowerItemFilter,
itemExtractSpeedUpgrade,
itemFunctionUpgrade,
// Conduits
blockConduitBundle,
blockConduitFacade,
itemConduitFacade,
itemRedstoneConduit,
itemItemConduit,
itemGasConduit,
itemMEConduit,
itemOCConduit,
itemBasicFilterUpgrade,
itemBigFilterUpgrade,
itemExistingItemFilter,
itemLimitedItemFilter,
itemModItemFilter,
itemPowerItemFilter,
itemExtractSpeedUpgrade,
itemFunctionUpgrade,
// Power
itemPowerConduit,
itemPowerConduitEndergy,
// Power
itemPowerConduit,
itemPowerConduitEndergy,
// Liquid
itemLiquidConduit,
// Liquid
itemLiquidConduit,
// Materials
itemBasicCapacitor,
itemAlloy,
itemAlloyEndergy,
itemGrindingBall,
itemGrindingBallEndergy,
itemMaterial,
itemMachinePart,
itemPowderIngot,
blockFusedQuartz,
itemFusedQuartzFrame,
blockDarkIronBars,
blockSoulariumBars,
blockEndSteelBars,
// Materials
itemBasicCapacitor,
itemAlloy,
itemAlloyEndergy,
itemGrindingBall,
itemGrindingBallEndergy,
itemMaterial,
itemMachinePart,
itemPowderIngot,
blockFusedQuartz,
itemFusedQuartzFrame,
blockDarkIronBars,
blockSoulariumBars,
blockEndSteelBars,
// Machines
blockStirlingGenerator,
blockCombustionGenerator,
blockZombieGenerator,
blockFrankenzombieGenerator,
blockEnderGenerator,
blockReservoir,
blockAlloySmelter,
blockSolarPanel,
blockCapacitorBank,
blockCapBank,
blockSagMill,
blockHyperCube,
blockPowerMonitor,
blockVat,
blockFarmStation,
blockTank,
blockCrafter,
blockVacuumChest,
blockWirelessCharger,
blockEnchanter,
blockSoulBinder,
blockSliceAndSplice,
blockAttractor,
blockSpawnGuard,
blockExperienceObelisk,
blockWeatherObelisk,
blockInhibitorObelisk,
blockTransceiver,
blockBuffer,
blockInventoryPanel,
// Machines
blockStirlingGenerator,
blockCombustionGenerator,
blockZombieGenerator,
blockFrankenzombieGenerator,
blockEnderGenerator,
blockReservoir,
blockAlloySmelter,
blockSolarPanel,
blockCapBank,
blockSagMill,
blockHyperCube,
blockPowerMonitor,
blockVat,
blockFarmStation,
blockTank,
blockCrafter,
blockVacuumChest,
blockWirelessCharger,
blockEnchanter,
blockSoulBinder,
blockSliceAndSplice,
blockAttractor,
blockSpawnGuard,
blockExperienceObelisk,
blockWeatherObelisk,
blockInhibitorObelisk,
blockTransceiver,
blockBuffer,
blockInventoryPanel,
blockPoweredSpawner,
itemBrokenSpawner,
blockPoweredSpawner,
itemBrokenSpawner,
blockKillerJoe,
blockKillerJoe,
blockElectricLight,
blockLightNode,
blockLight,
blockElectricLight,
blockLightNode,
blockLight,
//Blocks
blockDarkSteelPressurePlate,
blockDarkSteelAnvil,
blockDarkSteelLadder,
blockReinforcedObsidian,
blockIngotStorage,
blockIngotStorageEndergy,
// Blocks
blockDarkSteelPressurePlate,
blockDarkSteelAnvil,
blockDarkSteelLadder,
blockReinforcedObsidian,
blockIngotStorage,
blockIngotStorageEndergy,
// Painter
blockPainter,
blockPaintedFence,
blockPaintedFenceGate,
blockPaintedWall,
blockPaintedStair,
blockPaintedSlab,
blockPaintedDoubleSlab,
blockPaintedGlowstone,
blockPaintedCarpet,
// Painter
blockPainter,
blockPaintedFence,
blockPaintedFenceGate,
blockPaintedWall,
blockPaintedStair,
blockPaintedSlab,
blockPaintedDoubleSlab,
blockPaintedGlowstone,
blockPaintedCarpet,
itemConduitProbe,
itemYetaWrench,
itemXpTransfer,
itemConduitProbe,
itemYetaWrench,
itemXpTransfer,
blockTravelAnchor,
blockTelePad,
itemCoordSelector,
itemTravelStaff,
itemMagnet,
itemGliderWing,
blockEndermanSkull,
itemSoulVessel,
itemFrankenSkull,
blockTravelAnchor,
blockTelePad,
itemCoordSelector,
itemTravelStaff,
itemMagnet,
itemGliderWing,
blockEndermanSkull,
itemSoulVessel,
itemFrankenSkull,
blockEnderRail,
blockEnderRail,
itemEnderFood;
itemEnderFood,
public final String unlocalisedName;
itemTeleportStaff;
private ModObject() {
unlocalisedName = name();
}
public final String unlocalisedName;
private ModObject() {
unlocalisedName = name();
}
}
@@ -3,5 +3,5 @@ package crazypants.enderio;
import com.enderio.core.common.TileEntityEnder;
public abstract class TileEntityEio extends TileEntityEnder {
// Nothing yet ;D
// Nothing yet ;D
}
@@ -1,8 +1,9 @@
package crazypants.enderio.api;
public final class EnderIOAPIProps {
private EnderIOAPIProps() {}
public static final String VERSION = "0.0.2";
private EnderIOAPIProps() {}
public static final String VERSION = "0.0.2";
}
+102 -83
View File
@@ -14,105 +14,124 @@ import crazypants.enderio.machine.vat.VatRecipeManager;
import crazypants.enderio.teleport.TravelController;
/**
* This class provides the keys for the IMC messages supported by EIO and links the the details of how the messages are
* processed. It is preferable not to refer to these constants directly to avoid a dependence on this class.
* This class provides the keys for the IMC messages supported by EIO and links
* the the details of how the messages are processed. It is preferable not to
* refer to these constants directly to avoid a dependence on this class.
*/
public final class IMC {
/**
* Key for a string message to add Vat recipes. Calls {@link VatRecipeManager#addCustomRecipes(String)} with the
* string value of the message.
*/
public static final String VAT_RECIPE = "recipe:vat";
/**
* Key for a string message to add Vat recipes. Calls
* {@link VatRecipeManager#addCustomRecipes(String)} with the string value of
* the message.
*/
public static final String VAT_RECIPE = "recipe:vat";
/**
* Key for a string message to add SAGMill recipes. Calls {@link CrusherRecipeManager#addCustomRecipes(String)} with
* the string value of the message.
*/
public static final String SAG_RECIPE = "recipe:sagmill";
/**
* Key for a string message to add SAGMill recipes. Calls
* {@link CrusherRecipeManager#addCustomRecipes(String)} with the string value
* of the message.
*/
public static final String SAG_RECIPE = "recipe:sagmill";
/**
* Key for a string message to add Alloy Smelter recipes. Calls {@link AlloyRecipeManager#addCustomRecipes(String)}
* with the string value of the message.
*/
public static final String ALLOY_RECIPE = "recipe:alloysmelter";
/**
* Key for a string message to add Alloy Smelter recipes. Calls
* {@link AlloyRecipeManager#addCustomRecipes(String)} with the string value
* of the message.
*/
public static final String ALLOY_RECIPE = "recipe:alloysmelter";
/**
* Key for a string message to add Enchanter recipes. Calls {@link EnchanterRecipeManager#addCustomRecipes(String)}
* with the string value of the message. The supplied xml is treated as if it was loaded from
* EnchanterRecipes_User.xm.
*/
public static final String ENCHANTER_RECIPE = "recipe:enchanter";
/**
* Key for a string message to add Enchanter recipes. Calls
* {@link EnchanterRecipeManager#addCustomRecipes(String)} with the string
* value of the message. The supplied xml is treated as if it was loaded from
* EnchanterRecipes_User.xm.
*/
public static final String ENCHANTER_RECIPE = "recipe:enchanter";
/**
* Key for a string message to add Slice'N'Splice recipes. Calls
* {@link SliceAndSpliceRecipeManager#addCustomRecipes(String)} with the string value of the message.
*/
public static final String SLINE_N_SPLICE_RECIPE = "recipe:slicensplice";
/**
* Key for a string message to add Slice'N'Splice recipes. Calls
* {@link SliceAndSpliceRecipeManager#addCustomRecipes(String)} with the
* string value of the message.
*/
public static final String SLINE_N_SPLICE_RECIPE = "recipe:slicensplice";
/**
* Key for an NBT message to add Soul Binder recipes. Calls
* {@link SoulBinderRecipeManager#addRecipeFromNBT(net.minecraft.nbt.NBTTagCompound)} with the NBT value of the
* message.
*/
public static final String SOUL_BINDER_RECIPE = "recipe:soulbinder";
/**
* Key for an NBT message to add Soul Binder recipes. Calls
* {@link SoulBinderRecipeManager#addRecipeFromNBT(net.minecraft.nbt.NBTTagCompound)}
* with the NBT value of the message.
*/
public static final String SOUL_BINDER_RECIPE = "recipe:soulbinder";
/**
* Key for an ItemStack message to add an item to the Painters paint source whitelist. Calls
* {@link PaintSourceValidator#addToWhitelist(net.minecraft.item.ItemStack)}
*/
public static final String PAINTER_WHITELIST_ADD = "painter:whitelist:add";
/**
* Key for an ItemStack message to add an item to the Painters paint source
* whitelist. Calls
* {@link PaintSourceValidator#addToWhitelist(net.minecraft.item.ItemStack)}
*/
public static final String PAINTER_WHITELIST_ADD = "painter:whitelist:add";
/**
* Key for an ItemStack message to add an item to the Painters paint source blacklist. Calls
* {@link PaintSourceValidator#addToBlacklist(net.minecraft.item.ItemStack)}
*/
public static final String PAINTER_BLACKLIST_ADD = "painter:blacklist:add";
/**
* Key for an ItemStack message to add an item to the Painters paint source
* blacklist. Calls
* {@link PaintSourceValidator#addToBlacklist(net.minecraft.item.ItemStack)}
*/
public static final String PAINTER_BLACKLIST_ADD = "painter:blacklist:add";
/**
* Key for a string message to add an entity to the Powered Spawner blacklist. Calls
* {@link PoweredSpawnerConfig#addToBlacklist(String)} with the string value of the message.
*/
public static final String POWERED_SPAWNER_BLACKLIST_ADD = "poweredSpawner:blacklist:add";
/**
* Key for a string message to add an entity to the Powered Spawner blacklist.
* Calls {@link PoweredSpawnerConfig#addToBlacklist(String)} with the string
* value of the message.
*/
public static final String POWERED_SPAWNER_BLACKLIST_ADD = "poweredSpawner:blacklist:add";
/**
* Key for an NBT message to specify a cost multiplier for spawning an entity in the Powered Spawner. Calls
* {@link PoweredSpawnerConfig#addEntityCostFromNBT(net.minecraft.nbt.NBTTagCompound)} with the NBT value of the
* message.
*/
public static final String POWERED_SPAWNER_COST_MULTIPLIER = "poweredSpawner:costMultiplier";
/**
* Key for an NBT message to specify a cost multiplier for spawning an entity
* in the Powered Spawner. Calls
* {@link PoweredSpawnerConfig#addEntityCostFromNBT(net.minecraft.nbt.NBTTagCompound)}
* with the NBT value of the message.
*/
public static final String POWERED_SPAWNER_COST_MULTIPLIER = "poweredSpawner:costMultiplier";
/**
* Key for a string message to add an entity to the Soul Vial blacklist. Calls
* {@link ItemSoulVessel#addEntityToBlackList(String)} with the string value of the message.
*/
public static final String SOUL_VIAL_BLACKLIST = "soulVial:blacklist:add";
/**
* Key for a string message to add an entity to the Soul Vial blacklist. Calls
* {@link ItemSoulVessel#addEntityToBlackList(String)} with the string value
* of the message.
*/
public static final String SOUL_VIAL_BLACKLIST = "soulVial:blacklist:add";
/**
* Key for an NBT message to register a fluid fuel. Calls
* {@link FluidFuelRegister#addFuel(net.minecraft.nbt.NBTTagCompound)} with the NBT value of the message.
*/
public static final String FLUID_FUEL_ADD = "fluidFuel:add";
/**
* Key for an NBT message to register a fluid fuel. Calls
* {@link FluidFuelRegister#addFuel(net.minecraft.nbt.NBTTagCompound)} with
* the NBT value of the message.
*/
public static final String FLUID_FUEL_ADD = "fluidFuel:add";
/**
* Key for an NBT message to register a fluid coolant. Calls
* {@link FluidFuelRegister#addCoolant(net.minecraft.nbt.NBTTagCompound)} with the NBT value of the message.
*/
public static final String FLUID_COOLANT_ADD = "fluidCoolant:add";
/**
* Key for an NBT message to register a fluid coolant. Calls
* {@link FluidFuelRegister#addCoolant(net.minecraft.nbt.NBTTagCompound)} with
* the NBT value of the message.
*/
public static final String FLUID_COOLANT_ADD = "fluidCoolant:add";
/**
* Key for a string message to add a block to the list of blocks that cannot be teleported through using the Staff
* of Travel or Dark Steel Travel Upgrade. Value must be in the form: 'modid:blockName' Calls
* {@link TravelController#addBlockToBlinkBlackList(String)} with the string value of the message.
*/
public static final String TELEPORT_BLACKLIST_ADD = "teleport:blacklist:add";
/**
* Key for a string message to add a block to the list of blocks that cannot
* be teleported through using the Staff of Travel or Dark Steel Travel
* Upgrade. Value must be in the form: 'modid:blockName' Calls
* {@link TravelController#addBlockToBlinkBlackList(String)} with the string
* value of the message.
*/
public static final String TELEPORT_BLACKLIST_ADD = "teleport:blacklist:add";
/**
* Key for an NBT message to register a block or tile entity as connectable to insulated redstone conduits. Calls
* {@link InsulatedRedstoneConduit#addConnectableBlock(net.minecraft.nbt.NBTTagCompound)} with the NBT value of the
* message.
*/
public static final String REDSTONE_CONNECTABLE_ADD = "redstone:connectable:add";
/**
* Key for an NBT message to register a block or tile entity as connectable to
* insulated redstone conduits. Calls
* {@link InsulatedRedstoneConduit#addConnectableBlock(net.minecraft.nbt.NBTTagCompound)}
* with the NBT value of the message.
*/
public static final String REDSTONE_CONNECTABLE_ADD = "redstone:connectable:add";
private IMC() {
}
private IMC() {}
}
@@ -2,3 +2,4 @@
package crazypants.enderio.api;
import cpw.mods.fml.common.API;
@@ -4,12 +4,13 @@ import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
/**
* Implement this on your Block or TileEntity to control whether insulated restone conduits will automatically connect
* to your block.
* Implement this on your Block or TileEntity to control whether insulated
* restone conduits will automatically connect to your block.
* <p>
* Implementing on both is not recommended and will likely not work as expected.
*/
public interface IRedstoneConnectable {
boolean shouldRedstoneConduitConnect(World world, int x, int y, int z, ForgeDirection from);
boolean shouldRedstoneConduitConnect(World world, int x, int y, int z, ForgeDirection from);
}
@@ -3,3 +3,4 @@ package crazypants.enderio.api.redstone;
import cpw.mods.fml.common.API;
import crazypants.enderio.api.EnderIOAPIProps;
@@ -2,22 +2,12 @@ package crazypants.enderio.api.teleport;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import cofh.api.energy.IEnergyContainerItem;
import crazypants.enderio.config.Config;
public interface IItemOfTravel extends IEnergyContainerItem {
boolean isActive(EntityPlayer ep, ItemStack equipped);
boolean isActive(EntityPlayer ep, ItemStack equipped);
void extractInternal(ItemStack equipped, int power);
void extractInternal(ItemStack equipped, int power);
/**
* @param equipped player who is currently holding this item. caller will ensure the item held has your Item as item
* type
* @return -1 if method not supported, or max(can extract, power), e.g. 0 if item is empty.
*/
default int canExtractInternal(ItemStack equipped, int power) {
return Config.strictTPItemChecking ? 0 : -1;
}
}
@@ -3,117 +3,134 @@ package crazypants.enderio.api.teleport;
import javax.annotation.Nullable;
import net.minecraft.entity.Entity;
import com.enderio.core.common.util.BlockCoord;
public interface ITelePad extends ITravelAccessable {
/**
* If this piece of the telepad is the master, meaning it is connected on all 4 sides. This does <i>not</i>
* guarantee that it is in a connected state.
*
* @return True if this TE is the master TE, false otherwise.
*/
boolean isMaster();
/**
* If this piece of the telepad is the master, meaning it is connected on all
* 4 sides. This does <i>not</i> guarantee that it is in a connected state.
*
* @return True if this TE is the master TE, false otherwise.
*/
boolean isMaster();
/**
* Gets the master telepad that this one is connected to.
*
* @return The master telepad TE. {@code null} if not in a network. Itself if it is the master.
*/
@Nullable
ITelePad getMaster();
/**
* Gets the master telepad that this one is connected to.
*
* @return The master telepad TE. {@code null} if not in a network. Itself if
* it is the master.
*/
@Nullable
ITelePad getMaster();
/**
* If this telepad piece is in a network, meaning it is connected and in a valid configuration.
*
* @return True if this TE is in a network, false otherwise.
*/
boolean inNetwork();
/**
* If this telepad piece is in a network, meaning it is connected and in a
* valid configuration.
*
* @return True if this TE is in a network, false otherwise.
*/
boolean inNetwork();
/**
* The X coordinate stored in this telepad network. Always 0 if this is {@link #inNetwork()} returns false.
*
* @return The target X coordinate.
*/
int getX();
/**
* The X coordinate stored in this telepad network. Always 0 if this is
* {@link #inNetwork()} returns false.
*
* @return The target X coordinate.
*/
int getX();
/**
* The Y coordinate stored in this telepad network. Always 0 if this is {@link #inNetwork()} returns false.
*
* @return The target Y coordinate.
*/
int getY();
/**
* The Y coordinate stored in this telepad network. Always 0 if this is
* {@link #inNetwork()} returns false.
*
* @return The target Y coordinate.
*/
int getY();
/**
* The Z coordinate stored in this telepad network. Always 0 if this is {@link #inNetwork()} returns false.
*
* @return The target Z coordinate.
*/
int getZ();
/**
* The Z coordinate stored in this telepad network. Always 0 if this is
* {@link #inNetwork()} returns false.
*
* @return The target Z coordinate.
*/
int getZ();
/**
* The target dimension ID for the telepad. Defaults to the dimension the block is placed in.
*
* @return An int dimension ID.
*/
int getTargetDim();
/**
* The target dimension ID for the telepad. Defaults to the dimension the
* block is placed in.
*
* @return An int dimension ID.
*/
int getTargetDim();
/**
* Sets the target X coordinate of the network. Has no effect if {@link #inNetwork()} returns false.
*
* @param x The X coord.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setX(int x);
/**
* Sets the target X coordinate of the network. Has no effect if
* {@link #inNetwork()} returns false.
*
* @param x
* The X coord.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setX(int x);
/**
* Sets the target Y coordinate of the network. Has no effect if {@link #inNetwork()} returns false.
*
* @param y The Y coord.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setY(int y);
/**
* Sets the target Y coordinate of the network. Has no effect if
* {@link #inNetwork()} returns false.
*
* @param y
* The Y coord.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setY(int y);
/**
* Sets the target Z coordinate of the network. Has no effect if {@link #inNetwork()} returns false.
*
* @param z The Z coord.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setZ(int z);
/**
* Sets the target Z coordinate of the network. Has no effect if
* {@link #inNetwork()} returns false.
*
* @param z
* The Z coord.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setZ(int z);
/**
* Sets the target dimension of the network. Has no effect if {@link #inNetwork()} returns false.
*
* @param dimID The dimension ID.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setTargetDim(int dimID);
/**
* Sets the target dimension of the network. Has no effect if
* {@link #inNetwork()} returns false.
*
* @param dimID
* The dimension ID.
* @return The master telepad TE. DOES NOT ALWAYS return itself.
*/
ITelePad setTargetDim(int dimID);
/**
* Util method to set all coords using a {@link BlockCoord} object.
*
* @param coords The coords to set this telepad to.
* @see #setX(int)
* @see #setY(int)
* @see #setZ(int)
*/
void setCoords(BlockCoord coords);
/**
* Util method to set all coords using a {@link BlockCoord} object.
*
* @see #setX(int)
* @see #setY(int)
* @see #setZ(int)
*
* @param coords
* The coords to set this telepad to.
*/
void setCoords(BlockCoord coords);
/**
* Teleports a specific entity to the destination if:
* <ul>
* <li>The entity is in range (standing on top)</li>
* <li>There is sufficient power to perform the operation</li>
* </ul>
*
* @param entity The entity to teleport
*/
void teleportSpecific(Entity entity);
/**
* Teleports a specific entity to the destination if:
* <ul>
* <li>The entity is in range (standing on top)</li>
* <li>There is sufficient power to perform the operation</li>
* </ul>
*
* @param entity
* The entity to teleport
*/
void teleportSpecific(Entity entity);
/**
* Teleports all entities in range (in no particular order) until either there are none left or the power runs out.
*/
void teleportAll();
/**
* Teleports all entities in range (in no particular order) until either there
* are none left or the power runs out.
*/
void teleportAll();
}
@@ -13,60 +13,62 @@ import crazypants.util.UserIdent;
public interface ITravelAccessable {
enum AccessMode {
PUBLIC,
PRIVATE,
PROTECTED
}
enum AccessMode {
PUBLIC,
PRIVATE,
PROTECTED
}
boolean canBlockBeAccessed(EntityPlayer playerName);
boolean canBlockBeAccessed(EntityPlayer playerName);
boolean canSeeBlock(EntityPlayer playerName);
boolean canSeeBlock(EntityPlayer playerName);
boolean canUiBeAccessed(EntityPlayer username);
boolean canUiBeAccessed(EntityPlayer username);
boolean getRequiresPassword(EntityPlayer username);
boolean getRequiresPassword(EntityPlayer username);
boolean authoriseUser(EntityPlayer username, ItemStack[] password);
boolean authoriseUser(EntityPlayer username, ItemStack[] password);
AccessMode getAccessMode();
AccessMode getAccessMode();
void setAccessMode(AccessMode accessMode);
void setAccessMode(AccessMode accessMode);
ItemStack[] getPassword();
ItemStack[] getPassword();
void setPassword(ItemStack[] password);
void setPassword(ItemStack[] password);
ItemStack getItemLabel();
void setItemLabel(ItemStack lableIcon);
String getLabel();
void setLabel(String label);
ItemStack getItemLabel();
@Deprecated
UUID getPlacedBy();
void setItemLabel(ItemStack lableIcon);
@Nonnull
UserIdent getOwner();
String getLabel();
void setPlacedBy(EntityPlayer player);
void setLabel(String label);
void clearAuthorisedUsers();
@Deprecated
UUID getPlacedBy();
BlockCoord getLocation();
@Nonnull
UserIdent getOwner();
/**
* Is this block a travel target for the staff or a travel anchor?
*/
default boolean isTravelSource() {
return true;
}
void setPlacedBy(EntityPlayer player);
default boolean isVisible() {
return true;
}
void clearAuthorisedUsers();
default void setVisible(boolean visible) {
}
BlockCoord getLocation();
/**
* Is this block a travel target for the staff or a travel anchor?
*/
default boolean isTravelSource() {
return true;
}
default boolean isVisible() {
return true;
}
default void setVisible(boolean visible) {}
}
@@ -2,7 +2,6 @@ package crazypants.enderio.api.teleport;
import net.minecraft.entity.Entity;
import net.minecraftforge.event.entity.EntityEvent;
import cpw.mods.fml.common.eventhandler.Cancelable;
/**
@@ -14,32 +13,38 @@ import cpw.mods.fml.common.eventhandler.Cancelable;
* <li>Staff of travelling</li>
* <li>Telepad</li>
* </ul>
* <p>
* As well as any externally added teleports, assuming they fire this event manually.
*
* As well as any externally added teleports, assuming they fire this event
* manually.
*
*/
@Cancelable
public class TeleportEntityEvent extends EntityEvent {
/**
* The target coords. These can be edited by event handlers.
*/
public int targetX, targetY, targetZ;
/**
* The target coords. These can be edited by event handlers.
*/
public int targetX, targetY, targetZ;
public final TravelSource source;
public final TravelSource source;
/**
* Fired before an entity teleports to the given location.
*
* @param entity The entity teleporting
* @param x The target X coord
* @param y The target Y coord
* @param z The target Z coord
*/
public TeleportEntityEvent(Entity entity, TravelSource source, int x, int y, int z) {
super(entity);
this.targetX = x;
this.targetY = y;
this.targetZ = z;
this.source = source;
}
/**
* Fired before an entity teleports to the given location.
*
* @param entity
* The entity teleporting
* @param x
* The target X coord
* @param y
* The target Y coord
* @param z
* The target Z coord
*/
public TeleportEntityEvent(Entity entity, TravelSource source, int x, int y, int z) {
super(entity);
this.targetX = x;
this.targetY = y;
this.targetZ = z;
this.source = source;
}
}
@@ -1,117 +1,72 @@
package crazypants.enderio.api.teleport;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.EnderIO;
import crazypants.enderio.config.Config;
import crazypants.enderio.teleport.TravelController;
public enum TravelSource {
BLOCK() {
@Override
public int getMaxDistanceTravelled() {
return Config.travelAnchorMaxDistance;
}
},
STAFF() {
@Override
public int getMaxDistanceTravelled() {
return Config.travelStaffMaxDistance;
}
@Override
public float getPowerCostPerBlockTraveledRF() {
return Config.travelStaffPowerPerBlockRF;
}
},
STAFF_BLINK() {
@Override
public int getMaxDistanceTravelled() {
return Config.travelStaffMaxBlinkDistance;
}
@Override
public float getPowerCostPerBlockTraveledRF() {
return Config.travelStaffPowerPerBlockRF;
}
},
TELEPORT_STAFF() {
@Override
public int getMaxDistanceTravelled() {
return Config.teleportStaffMaxDistance;
}
@Override
public float getPowerCostPerBlockTraveledRF() {
return 0f;
}
},
TELEPORT_STAFF_BLINK() {
@Override
public int getMaxDistanceTravelled() {
return Config.teleportStaffMaxBlinkDistance;
}
@Override
public float getPowerCostPerBlockTraveledRF() {
return 0f;
}
},
TELEPAD(EnderIO.DOMAIN + ":telepad.teleport");
public static int getMaxDistance() {
return STAFF.getMaxDistanceTravelledSq();
}
@SideOnly(Side.CLIENT)
public static int getMaxDistanceSq() {
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player == null) {
return 0;
}
TravelSource source = TravelController.instance.getTravelItemTravelSource(player, false);
if (source == null) {
return TravelSource.BLOCK.getMaxDistanceTravelledSq();
} else {
return source.getMaxDistanceTravelledSq();
}
}
public final String sound;
private TravelSource() {
this("mob.endermen.portal");
}
private TravelSource(String sound) {
this.sound = sound;
}
public boolean getConserveMomentum() {
return this == STAFF_BLINK;
}
BLOCK() {
@Override
public int getMaxDistanceTravelled() {
return 0;
}
public int getMaxDistanceTravelledSq() {
return getMaxDistanceTravelled() * getMaxDistanceTravelled();
return Config.travelAnchorMaxDistance;
}
},
STAFF() {
@Override
public int getMaxDistanceTravelled() {
return Config.travelStaffMaxDistance;
}
@Override
public float getPowerCostPerBlockTraveledRF() {
return 0;
return Config.travelStaffPowerPerBlockRF;
}
}
},
STAFF_BLINK() {
@Override
public int getMaxDistanceTravelled() {
return Config.travelStaffMaxBlinkDistance;
}
@Override
public float getPowerCostPerBlockTraveledRF() {
return Config.travelStaffPowerPerBlockRF;
}
},
TELEPAD(EnderIO.DOMAIN + ":telepad.teleport");
public static int getMaxDistance() {
return STAFF.getMaxDistanceTravelledSq();
}
public static int getMaxDistanceSq() {
return STAFF.getMaxDistanceTravelledSq();
}
public final String sound;
private TravelSource() {
this("mob.endermen.portal");
}
private TravelSource(String sound) {
this.sound = sound;
}
public boolean getConserveMomentum() {
return this == STAFF_BLINK;
}
public int getMaxDistanceTravelled() {
return 0;
}
public int getMaxDistanceTravelledSq() {
return getMaxDistanceTravelled() * getMaxDistanceTravelled();
}
public float getPowerCostPerBlockTraveledRF() {
return 0;
}
}
@@ -3,3 +3,4 @@ package crazypants.enderio.api.teleport;
import cpw.mods.fml.common.API;
import crazypants.enderio.api.EnderIOAPIProps;
@@ -8,12 +8,16 @@ import net.minecraft.item.ItemStack;
*/
public interface IConduitControl extends IHideFacades {
/**
* Controls whether the overlay is shown and the player can change the display mode.
*
* @param stack The itemstack
* @param player The player holding the itemstack
* @return True if the overlay should be rendered and the player should be able to change modes. False otherwise.
*/
boolean showOverlay(ItemStack stack, EntityPlayer player);
/**
* Controls whether the overlay is shown and the player can change the display
* mode.
*
* @param stack
* The itemstack
* @param player
* The player holding the itemstack
* @return True if the overlay should be rendered and the player should be
* able to change modes. False otherwise.
*/
boolean showOverlay(ItemStack stack, EntityPlayer player);
}
@@ -4,6 +4,7 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public interface IHideFacades {
boolean shouldHideFacades(ItemStack stack, EntityPlayer player);
boolean shouldHideFacades(ItemStack stack, EntityPlayer player);
}
@@ -3,9 +3,11 @@ package crazypants.enderio.api.tool;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public interface ITool extends IHideFacades {
boolean canUse(ItemStack stack, EntityPlayer player, int x, int y, int z);
boolean canUse(ItemStack stack, EntityPlayer player, int x, int y, int z);
void used(ItemStack stack, EntityPlayer player, int x, int y, int z);
void used(ItemStack stack, EntityPlayer player, int x, int y, int z);
}
@@ -3,3 +3,4 @@ package crazypants.enderio.api.tool;
import cpw.mods.fml.common.API;
import crazypants.enderio.api.EnderIOAPIProps;
@@ -1,101 +0,0 @@
package crazypants.enderio.betterbuilderswands;
import java.util.function.BiFunction;
import java.util.function.IntFunction;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import com.github.bsideup.jabel.Desugar;
import crazypants.enderio.EnderIO;
import crazypants.enderio.machine.painter.BlockPaintedCarpet;
import crazypants.enderio.machine.painter.BlockPaintedFence;
import crazypants.enderio.machine.painter.BlockPaintedFenceGate;
import crazypants.enderio.machine.painter.BlockPaintedGlowstone;
import crazypants.enderio.machine.painter.BlockPaintedSlab;
import crazypants.enderio.machine.painter.BlockPaintedStair;
import crazypants.enderio.machine.painter.BlockPaintedWall;
import crazypants.enderio.machine.painter.TileEntityPaintedBlock;
import portablejim.bbw.BetterBuildersWandsMod;
import portablejim.bbw.basics.Point3d;
import portablejim.bbw.core.conversion.ICustomMapping;
import portablejim.bbw.shims.IPlayerShim;
import portablejim.bbw.shims.IWorldShim;
@Desugar
public record PaintedCustomMapping(Block lookBlock, BiFunction<Block, Integer, ItemStack> itemStackGetter, int meta)
implements ICustomMapping {
@Override
public Block getLookBlock() {
return lookBlock;
}
@Override
public int getMeta() {
return meta;
}
@Override
public ItemStack getItems(IWorldShim world, IPlayerShim player, Point3d point) {
if (world.getTile(point) instanceof TileEntityPaintedBlock painted) {
return itemStackGetter.apply(painted.getSourceBlock(), painted.getSourceBlockMetadata());
}
return null;
}
@Override
public boolean shouldCopyTileNBT() {
return true;
}
public static void registerMappings() {
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedGlowstone,
BlockPaintedGlowstone::createItemStackForSourceBlock,
i));
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedStair,
BlockPaintedStair::createItemStackForSourceBlock,
i));
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedFence,
BlockPaintedFence::createItemStackForSourceBlock,
i));
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedFenceGate,
BlockPaintedFenceGate::createItemStackForSourceBlock,
i));
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedCarpet,
BlockPaintedCarpet::createItemStackForSourceBlock,
i));
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedSlab,
BlockPaintedSlab::createItemStackForSourceBlock,
i));
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedWall,
BlockPaintedWall::createItemStackForSourceBlock,
i));
register(
i -> new PaintedCustomMapping(
EnderIO.blockPaintedDoubleSlab,
BlockPaintedSlab::createItemStackForSourceBlock,
i));
}
private static void register(IntFunction<ICustomMapping> mapping) {
for (int i = 0; i < 16; i++) {
BetterBuildersWandsMod.instance.mappingManager.setMapping(mapping.apply(i));
}
}
}
@@ -1,5 +1,7 @@
package crazypants.enderio.block;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import net.minecraft.block.BlockAnvil;
import net.minecraft.client.gui.GuiRepair;
import net.minecraft.client.renderer.texture.IIconRegister;
@@ -9,9 +11,6 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import cpw.mods.fml.common.network.IGuiHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
@@ -23,78 +22,83 @@ import crazypants.enderio.ModObject;
public class BlockDarkSteelAnvil extends BlockAnvil implements IResourceTooltipProvider {
private static final String[] anvilIconNames = new String[] { "anvil_0", "anvil_1", "anvil_2" };
private static final String[] anvilIconNames = new String[] { "anvil_0", "anvil_1", "anvil_2" };
@SideOnly(Side.CLIENT)
private IIcon[] anvilIcons;
@SideOnly(Side.CLIENT)
private IIcon[] anvilIcons;
public static BlockDarkSteelAnvil create() {
BlockDarkSteelAnvil res = new BlockDarkSteelAnvil();
res.init();
return res;
public static BlockDarkSteelAnvil create() {
BlockDarkSteelAnvil res = new BlockDarkSteelAnvil();
res.init();
return res;
}
private BlockDarkSteelAnvil() {
super();
setHardness(5.0F);
setStepSound(soundTypeAnvil);
setResistance(2000.0F);
setBlockName(ModObject.blockDarkSteelAnvil.unlocalisedName);
setCreativeTab(EnderIOTab.tabEnderIO);
}
protected void init() {
GameRegistry.registerBlock(this, ItemAnvilBlock.class, ModObject.blockDarkSteelAnvil.unlocalisedName);
EnderIO.guiHandler.registerGuiHandler(GuiHandler.GUI_ID_ANVIL, new IGuiHandler() {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return new ContainerDarkSteelAnvil(player.inventory, world, x, y, z, player);
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return new GuiRepair(player.inventory, world, x, y, z);
}
});
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return this.getUnlocalizedName();
}
@Override
public boolean onBlockActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY, float hitZ) {
p.openGui(EnderIO.instance, GuiHandler.GUI_ID_ANVIL, w, x, y, z);
return true;
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int p_149691_1_, int p_149691_2_)
{
if(this.anvilRenderSide == 3 && p_149691_1_ == 1)
{
int k = (p_149691_2_ >> 2) % this.anvilIcons.length;
return this.anvilIcons[k];
}
private BlockDarkSteelAnvil() {
super();
setHardness(5.0F);
setStepSound(soundTypeAnvil);
setResistance(2000.0F);
setBlockName(ModObject.blockDarkSteelAnvil.unlocalisedName);
setCreativeTab(EnderIOTab.tabEnderIO);
else
{
return this.blockIcon;
}
}
protected void init() {
GameRegistry.registerBlock(this, ItemAnvilBlock.class, ModObject.blockDarkSteelAnvil.unlocalisedName);
EnderIO.guiHandler.registerGuiHandler(GuiHandler.GUI_ID_ANVIL, new IGuiHandler() {
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister register)
{
this.blockIcon = register.registerIcon(EnderIO.DOMAIN + ":anvil_base");
this.anvilIcons = new IIcon[anvilIconNames.length];
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return new ContainerDarkSteelAnvil(player.inventory, world, x, y, z, player);
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return new GuiRepair(player.inventory, world, x, y, z);
}
});
for (int i = 0; i < this.anvilIcons.length; ++i)
{
this.anvilIcons[i] = register.registerIcon(EnderIO.DOMAIN + ":" + anvilIconNames[i]);
}
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return this.getUnlocalizedName();
}
@Override
public boolean onBlockActivated(World w, int x, int y, int z, EntityPlayer p, int side, float hitX, float hitY,
float hitZ) {
p.openGui(EnderIO.instance, GuiHandler.GUI_ID_ANVIL, w, x, y, z);
return true;
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int p_149691_1_, int p_149691_2_) {
if (this.anvilRenderSide == 3 && p_149691_1_ == 1) {
int k = (p_149691_2_ >> 2) % this.anvilIcons.length;
return this.anvilIcons[k];
} else {
return this.blockIcon;
}
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister register) {
this.blockIcon = register.registerIcon(EnderIO.DOMAIN + ":anvil_base");
this.anvilIcons = new IIcon[anvilIconNames.length];
for (int i = 0; i < this.anvilIcons.length; ++i) {
this.anvilIcons[i] = register.registerIcon(EnderIO.DOMAIN + ":" + anvilIconNames[i]);
}
}
@Override
public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) {
return new ItemStack(this, 1, world.getBlockMetadata(x, y, z) >> 2);
}
@Override
public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) {
return new ItemStack(this, 1, world.getBlockMetadata(x, y, z) >> 2);
}
}
@@ -1,5 +1,7 @@
package crazypants.enderio.block;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLadder;
import net.minecraft.block.material.Material;
@@ -7,9 +9,6 @@ import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import cpw.mods.fml.common.registry.GameRegistry;
import crazypants.enderio.EnderIO;
import crazypants.enderio.EnderIOTab;
@@ -17,53 +16,50 @@ import crazypants.enderio.ModObject;
import crazypants.enderio.config.Config;
public class BlockDarkSteelLadder extends BlockLadder implements IResourceTooltipProvider {
public static BlockDarkSteelLadder create() {
BlockDarkSteelLadder res = new BlockDarkSteelLadder();
res.init();
return res;
}
public static BlockDarkSteelLadder create() {
BlockDarkSteelLadder res = new BlockDarkSteelLadder();
res.init();
return res;
protected BlockDarkSteelLadder() {
super();
setBlockName(ModObject.blockDarkSteelLadder.unlocalisedName);
setBlockTextureName(EnderIO.DOMAIN + ":" + ModObject.blockDarkSteelLadder.unlocalisedName);
setStepSound(Block.soundTypeMetal);
setCreativeTab(EnderIOTab.tabEnderIO);
setHardness(0.4F);
}
protected void init() {
GameRegistry.registerBlock(this, ModObject.blockDarkSteelLadder.unlocalisedName);
}
@Override
public Material getMaterial() {
return Material.iron;
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) {
if (entity.onGround || entity.isCollidedVertically) {
return;
}
protected BlockDarkSteelLadder() {
super();
setBlockName(ModObject.blockDarkSteelLadder.unlocalisedName);
setBlockTextureName(EnderIO.DOMAIN + ":" + ModObject.blockDarkSteelLadder.unlocalisedName);
setStepSound(Block.soundTypeMetal);
setCreativeTab(EnderIOTab.tabEnderIO);
setHardness(0.4F);
if(entity.motionY >= 0.1) {
entity.setPosition(entity.posX, entity.posY + Config.darkSteelLadderSpeedBoost, entity.posZ);
} else if(entity.motionY <= -0.1) {
Block blockUnder = entity.worldObj.getBlock(MathHelper.floor_double(entity.posX), MathHelper.floor_double(entity.posY) - 3, MathHelper.floor_double(entity.posZ));
if (blockUnder == null || blockUnder == this) { // prevent clipping into block
entity.setPosition(entity.posX, entity.posY - Config.darkSteelLadderSpeedBoost, entity.posZ);
}
}
}
protected void init() {
GameRegistry.registerBlock(this, ModObject.blockDarkSteelLadder.unlocalisedName);
}
@Override
public Material getMaterial() {
return Material.iron;
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) {
if (entity.onGround || entity.isCollidedVertically) {
return;
}
if (entity.motionY >= 0.1) {
entity.setPosition(entity.posX, entity.posY + Config.darkSteelLadderSpeedBoost, entity.posZ);
} else if (entity.motionY <= -0.1) {
Block blockUnder = entity.worldObj.getBlock(
MathHelper.floor_double(entity.posX),
MathHelper.floor_double(entity.posY) - 3,
MathHelper.floor_double(entity.posZ));
if (blockUnder == null || blockUnder == this) { // prevent clipping into block
entity.setPosition(entity.posX, entity.posY - Config.darkSteelLadderSpeedBoost, entity.posZ);
}
}
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return getUnlocalizedName();
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return getUnlocalizedName();
}
}
@@ -18,8 +18,6 @@ import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import com.enderio.core.common.util.Util;
import com.google.common.collect.Lists;
import cpw.mods.fml.common.registry.GameRegistry;
@@ -36,194 +34,190 @@ import crazypants.enderio.machine.painter.PaintSourceValidator;
import crazypants.enderio.machine.painter.PainterUtil;
import crazypants.enderio.machine.painter.TileEntityPaintedBlock;
public class BlockDarkSteelPressurePlate extends BlockPressurePlate
implements IResourceTooltipProvider, ITileEntityProvider, IPaintedBlock {
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import com.enderio.core.common.util.Util;
public static BlockDarkSteelPressurePlate create() {
BlockDarkSteelPressurePlate res = new BlockDarkSteelPressurePlate();
res.init();
return res;
public class BlockDarkSteelPressurePlate extends BlockPressurePlate implements IResourceTooltipProvider, ITileEntityProvider, IPaintedBlock {
public static BlockDarkSteelPressurePlate create() {
BlockDarkSteelPressurePlate res = new BlockDarkSteelPressurePlate();
res.init();
return res;
}
public BlockDarkSteelPressurePlate() {
super(ModObject.blockDarkSteelPressurePlate.unlocalisedName, Material.iron, Sensitivity.players);
setBlockName(ModObject.blockDarkSteelPressurePlate.unlocalisedName);
setStepSound(Block.soundTypeMetal);
setCreativeTab(EnderIOTab.tabEnderIO);
setHardness(2.0f);
}
protected void init() {
GameRegistry.registerBlock(this, BlockItemDarkSteelPressurePlate.class, ModObject.blockDarkSteelPressurePlate.unlocalisedName);
GameRegistry.registerTileEntity(TileEntityDarkSteelPressurePlate.class, ModObject.blockDarkSteelPressurePlate.unlocalisedName + "TileEntity");
MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.unlocalisedName, new PainterTemplate(this));
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iIconRegister) {
blockIcon = iIconRegister.registerIcon("enderio:" + ModObject.blockDarkSteelPressurePlate.unlocalisedName);
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
if(itemStack != null && itemStack.getItemDamage() == 1) {
return getUnlocalizedName() + ".silent";
}
return getUnlocalizedName();
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int blockSide) {
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TileEntityPaintedBlock) {
TileEntityPaintedBlock tef = (TileEntityPaintedBlock) te;
if(tef.getSourceBlock() != null) {
return tef.getSourceBlock().getIcon(blockSide, tef.getSourceBlockMetadata());
}
}
return super.getIcon(world, x, y, z, blockSide);
}
@Override
public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) {
if(willHarvest) {
return true;
}
return super.removedByPlayer(world, player, x, y, z, willHarvest);
}
@Override
public void harvestBlock(World world, EntityPlayer player, int x, int y, int z, int meta) {
super.harvestBlock(world, player, x, y, z, meta);
world.setBlockToAir(x, y, z);
}
@Override
public final ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) {
TileEntityDarkSteelPressurePlate tepb = (TileEntityDarkSteelPressurePlate) world.getTileEntity(x, y, z);
ItemStack stack = new ItemStack(this, 1, tepb.isSilent() ? 1 : 0);
if(tepb.getSourceBlock() != null) {
PainterUtil.setSourceBlock(stack, tepb.getSourceBlock(), tepb.getSourceBlockMetadata());
}
return Lists.newArrayList(stack);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) {
Block b = PainterUtil.getSourceBlock(stack);
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TileEntityDarkSteelPressurePlate) {
TileEntityDarkSteelPressurePlate tef = (TileEntityDarkSteelPressurePlate) te;
tef.setSourceBlock(b);
tef.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(stack));
tef.setSilent(stack.getItemDamage() == 1);
}
world.markBlockForUpdate(x, y, z);
super.onBlockPlacedBy(world, x, y, z, player, stack);
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityDarkSteelPressurePlate();
}
@Override
@SideOnly(Side.CLIENT)
public int colorMultiplier(IBlockAccess world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TileEntityPaintedBlock) {
TileEntityPaintedBlock tef = (TileEntityPaintedBlock) te;
if(tef.getSourceBlock() != null) {
return tef.getSourceBlock().colorMultiplier(world, x, y, z);
}
}
return super.colorMultiplier(world, x, y, z);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item arg0, CreativeTabs arg1, List items) {
items.add(new ItemStack(this, 1, 0));
items.add(new ItemStack(this, 1, 1));
}
@Override
protected void func_150062_a(World world, int x, int y, int z, int p_150062_5_) {
int i1 = func_150065_e(world, x, y, z);
boolean flag = p_150062_5_ > 0;
boolean flag1 = i1 > 0;
if(p_150062_5_ != i1) {
world.setBlockMetadataWithNotify(x, y, z, func_150066_d(i1), 2);
func_150064_a_(world, x, y, z);
world.markBlockRangeForRenderUpdate(x, y, z, x, y, z);
}
public BlockDarkSteelPressurePlate() {
super(ModObject.blockDarkSteelPressurePlate.unlocalisedName, Material.iron, Sensitivity.players);
setBlockName(ModObject.blockDarkSteelPressurePlate.unlocalisedName);
setStepSound(Block.soundTypeMetal);
setCreativeTab(EnderIOTab.tabEnderIO);
setHardness(2.0f);
boolean playSound = true;
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof TileEntityDarkSteelPressurePlate && ((TileEntityDarkSteelPressurePlate)te).isSilent()) {
playSound = false;
}
if(playSound) {
if(!flag1 && flag) {
world.playSoundEffect(x + 0.5D, y + 0.1D, z + 0.5D, "random.click", 0.3F, 0.5F);
} else if(flag1 && !flag) {
world.playSoundEffect(x + 0.5D, y + 0.1D, z + 0.5D, "random.click", 0.3F, 0.6F);
}
}
protected void init() {
GameRegistry.registerBlock(
this,
BlockItemDarkSteelPressurePlate.class,
ModObject.blockDarkSteelPressurePlate.unlocalisedName);
GameRegistry.registerTileEntity(
TileEntityDarkSteelPressurePlate.class,
ModObject.blockDarkSteelPressurePlate.unlocalisedName + "TileEntity");
MachineRecipeRegistry.instance
.registerRecipe(ModObject.blockPainter.unlocalisedName, new PainterTemplate(this));
if(flag1) {
world.scheduleBlockUpdate(x, y, z, this, tickRate(world));
}
}
public static final class PainterTemplate extends BasicPainterTemplate {
public PainterTemplate(Block dspp) {
super(dspp);
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iIconRegister) {
blockIcon = iIconRegister.registerIcon("enderio:" + ModObject.blockDarkSteelPressurePlate.unlocalisedName);
public boolean isValidPaintSource(ItemStack paintSource) {
if(PaintSourceValidator.instance.isValidSourceDefault(paintSource)) {
return true;
}
if(paintSource == null) {
return false;
}
Block block = Util.getBlockFromItemId(paintSource);
if(block == null) {
return false;
}
return Block.getBlockFromItem(paintSource.getItem()) == EnderIO.blockFusedQuartz;
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
if (itemStack != null && itemStack.getItemDamage() == 1) {
return getUnlocalizedName() + ".silent";
}
return getUnlocalizedName();
public ResultStack[] getCompletedResult(float chance, MachineRecipeInput... inputs) {
ItemStack paintSource = MachineRecipeInput.getInputForSlot(1, inputs);
if(paintSource == null) {
return new ResultStack[0];
}
ItemStack target = MachineRecipeInput.getInputForSlot(0, inputs);
ItemStack resultStack = createItemStackForSourceBlock(Block.getBlockFromItem(paintSource.getItem()), paintSource.getItemDamage());
resultStack.setItemDamage(target.getItemDamage());
return new ResultStack[] { new ResultStack(resultStack) };
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int blockSide) {
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof TileEntityPaintedBlock) {
TileEntityPaintedBlock tef = (TileEntityPaintedBlock) te;
if (tef.getSourceBlock() != null) {
return tef.getSourceBlock().getIcon(blockSide, tef.getSourceBlockMetadata());
}
}
return super.getIcon(world, x, y, z, blockSide);
public static ItemStack createItemStackForSourceBlock(Block block, int damage) {
ItemStack result = new ItemStack(EnderIO.blockDarkSteelPressurePlate, 1, damage);
PainterUtil.setSourceBlock(result, block, damage);
return result;
}
}
@Override
public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) {
if (willHarvest) {
return true;
}
return super.removedByPlayer(world, player, x, y, z, willHarvest);
}
@Override
public void harvestBlock(World world, EntityPlayer player, int x, int y, int z, int meta) {
super.harvestBlock(world, player, x, y, z, meta);
world.setBlockToAir(x, y, z);
}
@Override
public final ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) {
TileEntityDarkSteelPressurePlate tepb = (TileEntityDarkSteelPressurePlate) world.getTileEntity(x, y, z);
ItemStack stack = new ItemStack(this, 1, tepb.isSilent() ? 1 : 0);
if (tepb.getSourceBlock() != null) {
PainterUtil.setSourceBlock(stack, tepb.getSourceBlock(), tepb.getSourceBlockMetadata());
}
return Lists.newArrayList(stack);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) {
Block b = PainterUtil.getSourceBlock(stack);
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof TileEntityDarkSteelPressurePlate) {
TileEntityDarkSteelPressurePlate tef = (TileEntityDarkSteelPressurePlate) te;
tef.setSourceBlock(b);
tef.setSourceBlockMetadata(PainterUtil.getSourceBlockMetadata(stack));
tef.setSilent(stack.getItemDamage() == 1);
}
world.markBlockForUpdate(x, y, z);
super.onBlockPlacedBy(world, x, y, z, player, stack);
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityDarkSteelPressurePlate();
}
@Override
@SideOnly(Side.CLIENT)
public int colorMultiplier(IBlockAccess world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof TileEntityPaintedBlock) {
TileEntityPaintedBlock tef = (TileEntityPaintedBlock) te;
if (tef.getSourceBlock() != null) {
return tef.getSourceBlock().colorMultiplier(world, x, y, z);
}
}
return super.colorMultiplier(world, x, y, z);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item arg0, CreativeTabs arg1, List<ItemStack> items) {
items.add(new ItemStack(this, 1, 0));
items.add(new ItemStack(this, 1, 1));
}
@Override
protected void func_150062_a(World world, int x, int y, int z, int p_150062_5_) {
int i1 = func_150065_e(world, x, y, z);
boolean flag = p_150062_5_ > 0;
boolean flag1 = i1 > 0;
if (p_150062_5_ != i1) {
world.setBlockMetadataWithNotify(x, y, z, func_150066_d(i1), 2);
func_150064_a_(world, x, y, z);
world.markBlockRangeForRenderUpdate(x, y, z, x, y, z);
}
boolean playSound = true;
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof TileEntityDarkSteelPressurePlate && ((TileEntityDarkSteelPressurePlate) te).isSilent()) {
playSound = false;
}
if (playSound) {
if (!flag1 && flag) {
world.playSoundEffect(x + 0.5D, y + 0.1D, z + 0.5D, "random.click", 0.3F, 0.5F);
} else if (flag1 && !flag) {
world.playSoundEffect(x + 0.5D, y + 0.1D, z + 0.5D, "random.click", 0.3F, 0.6F);
}
}
if (flag1) {
world.scheduleBlockUpdate(x, y, z, this, tickRate(world));
}
}
public static final class PainterTemplate extends BasicPainterTemplate {
public PainterTemplate(Block dspp) {
super(dspp);
}
@Override
public boolean isValidPaintSource(ItemStack paintSource) {
if (PaintSourceValidator.instance.isValidSourceDefault(paintSource)) {
return true;
}
if (paintSource == null) {
return false;
}
Block block = Util.getBlockFromItemId(paintSource);
if (block == null) {
return false;
}
return Block.getBlockFromItem(paintSource.getItem()) == EnderIO.blockFusedQuartz;
}
@Override
public ResultStack[] getCompletedResult(float chance, MachineRecipeInput... inputs) {
ItemStack paintSource = MachineRecipeInput.getInputForSlot(1, inputs);
if (paintSource == null) {
return new ResultStack[0];
}
ItemStack target = MachineRecipeInput.getInputForSlot(0, inputs);
ItemStack resultStack = createItemStackForSourceBlock(
Block.getBlockFromItem(paintSource.getItem()),
paintSource.getItemDamage());
resultStack.setItemDamage(target.getItemDamage());
return new ResultStack[] { new ResultStack(resultStack) };
}
public static ItemStack createItemStackForSourceBlock(Block block, int damage) {
ItemStack result = new ItemStack(EnderIO.blockDarkSteelPressurePlate, 1, damage);
PainterUtil.setSourceBlock(result, block, damage);
return result;
}
}
}
@@ -5,12 +5,13 @@ import net.minecraft.item.ItemBlockWithMetadata;
public class BlockItemDarkSteelPressurePlate extends ItemBlockWithMetadata {
public BlockItemDarkSteelPressurePlate(Block block) {
super(block, block);
}
public BlockItemDarkSteelPressurePlate(Block block) {
super(block, block);
}
@Override
public int getMetadata(int p_77647_1_) {
return 0;
}
@Override
public int getMetadata(int p_77647_1_) {
return 0;
}
}
@@ -2,6 +2,8 @@ package crazypants.enderio.block;
import java.util.List;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
@@ -10,9 +12,6 @@ import net.minecraft.item.ItemStack;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import com.enderio.core.api.client.gui.IResourceTooltipProvider;
import crazypants.enderio.BlockEio;
import crazypants.enderio.ModObject;
import crazypants.enderio.config.Config;
@@ -20,56 +19,56 @@ import crazypants.enderio.waila.IWailaInfoProvider;
public class BlockReinforcedObsidian extends BlockEio implements IResourceTooltipProvider, IWailaInfoProvider {
public static BlockReinforcedObsidian create() {
BlockReinforcedObsidian result = new BlockReinforcedObsidian();
result.init();
return result;
public static BlockReinforcedObsidian create() {
BlockReinforcedObsidian result = new BlockReinforcedObsidian();
result.init();
return result;
}
private BlockReinforcedObsidian() {
super(ModObject.blockReinforcedObsidian.unlocalisedName, null, Material.rock);
setHardness(50.0F);
setResistance(2000.0F);
setStepSound(soundTypePiston);
if(!Config.reinforcedObsidianEnabled) {
setCreativeTab(null);
}
}
public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) {
return false;
}
@Override
public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) {
;
}
@Override
public boolean canDropFromExplosion(Explosion p_149659_1_) {
return false;
}
public MapColor getMapColor(int p_149728_1_) {
return MapColor.obsidianColor;
}
private BlockReinforcedObsidian() {
super(ModObject.blockReinforcedObsidian.unlocalisedName, null, Material.rock);
setHardness(50.0F);
setResistance(2000.0F);
setStepSound(soundTypePiston);
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return getUnlocalizedName();
}
@Override
protected boolean shouldWrench(World world, int x, int y, int z, EntityPlayer entityPlayer, int side) {
return false;
}
if (!Config.reinforcedObsidianEnabled) {
setCreativeTab(null);
}
}
@Override
public void getWailaInfo(List<String> tooltip, EntityPlayer player, World world, int x, int y, int z) {}
public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) {
return false;
}
@Override
public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) {
;
}
@Override
public boolean canDropFromExplosion(Explosion p_149659_1_) {
return false;
}
public MapColor getMapColor(int p_149728_1_) {
return MapColor.obsidianColor;
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return getUnlocalizedName();
}
@Override
protected boolean shouldWrench(World world, int x, int y, int z, EntityPlayer entityPlayer, int side) {
return false;
}
@Override
public void getWailaInfo(List<String> tooltip, EntityPlayer player, World world, int x, int y, int z) {}
@Override
public int getDefaultDisplayMask(World world, int x, int y, int z) {
return IWailaInfoProvider.BIT_BASIC;
}
@Override
public int getDefaultDisplayMask(World world, int x, int y, int z) {
return IWailaInfoProvider.BIT_BASIC;
}
}
@@ -9,99 +9,93 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.ReflectionHelper;
import crazypants.enderio.EnderIO;
import crazypants.enderio.config.Config;
public class ContainerDarkSteelAnvil extends ContainerRepair {
private final int x;
private final int y;
private final int z;
private int x, y, z;
public ContainerDarkSteelAnvil(InventoryPlayer playerInv, final World world, final int x, final int y, final int z,
EntityPlayer player) {
super(playerInv, world, x, y, z, player);
private final Field _outputSlot = ReflectionHelper.findField(ContainerRepair.class, "outputSlot", "field_82852_f");
private final Field _inputSlots = ReflectionHelper.findField(ContainerRepair.class, "inputSlots", "field_82853_g");
private final Field _materialCost = ReflectionHelper.findField(ContainerRepair.class, "materialCost", "stackSizeToBeUsedInRepair", "field_82856_l");
final IInventory outputSlot, inputSlots;
final int materialCost;
@SuppressWarnings("unchecked")
public ContainerDarkSteelAnvil(InventoryPlayer playerInv, final World world, final int x, final int y, final int z, EntityPlayer player) {
super(playerInv, world, x, y, z, player);
try {
Field _outputSlot = ReflectionHelper.findField(ContainerRepair.class, "outputSlot", "field_82852_f");
outputSlot = (IInventory) _outputSlot.get(this);
Field _inputSlots = ReflectionHelper.findField(ContainerRepair.class, "inputSlots", "field_82853_g");
inputSlots = (IInventory) _inputSlots.get(this);
Field _materialCost = ReflectionHelper
.findField(ContainerRepair.class, "materialCost", "stackSizeToBeUsedInRepair", "field_82856_l");
materialCost = _materialCost.getInt(this);
} catch (Exception e) {
throw new RuntimeException(e);
final IInventory outputSlot, inputSlots;
final int materialCost;
try {
outputSlot = (IInventory) _outputSlot.get(this);
inputSlots = (IInventory) _inputSlots.get(this);
materialCost = _materialCost.getInt(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
this.x = x;
this.y = y;
this.z = z;
this.inventorySlots.set(2, new Slot(outputSlot, 2, 134, 47) {
public boolean isItemValid(ItemStack stack) {
return false;
}
public boolean canTakeStack(EntityPlayer stack) {
return (stack.capabilities.isCreativeMode || stack.experienceLevel >= ContainerDarkSteelAnvil.this.maximumCost)
&& ContainerDarkSteelAnvil.this.maximumCost > 0 && this.getHasStack();
}
public void onPickupFromSlot(EntityPlayer player, ItemStack stack) {
if(!player.capabilities.isCreativeMode) {
player.addExperienceLevel(-ContainerDarkSteelAnvil.this.maximumCost);
}
this.x = x;
this.y = y;
this.z = z;
inputSlots.setInventorySlotContents(0, (ItemStack) null);
this.inventorySlots.set(2, new Slot(outputSlot, 2, 134, 47) {
if(materialCost > 0) {
ItemStack itemstack1 = inputSlots.getStackInSlot(1);
public boolean isItemValid(ItemStack stack) {
return false;
}
if(itemstack1 != null && itemstack1.stackSize > materialCost) {
itemstack1.stackSize -= materialCost;
inputSlots.setInventorySlotContents(1, itemstack1);
} else {
inputSlots.setInventorySlotContents(1, (ItemStack) null);
}
} else {
inputSlots.setInventorySlotContents(1, (ItemStack) null);
}
public boolean canTakeStack(EntityPlayer stack) {
return (stack.capabilities.isCreativeMode
|| stack.experienceLevel >= ContainerDarkSteelAnvil.this.maximumCost)
&& ContainerDarkSteelAnvil.this.maximumCost > 0
&& this.getHasStack();
}
ContainerDarkSteelAnvil.this.maximumCost = 0;
public void onPickupFromSlot(EntityPlayer player, ItemStack stack) {
if (!player.capabilities.isCreativeMode) {
player.addExperienceLevel(-ContainerDarkSteelAnvil.this.maximumCost);
}
if(!player.capabilities.isCreativeMode && !world.isRemote && world.getBlock(x, y, z) == EnderIO.blockDarkSteelAnvil
&& player.getRNG().nextFloat() < Config.darkSteelAnvilDamageChance) {
int i1 = world.getBlockMetadata(x, y, z);
int k = i1 & 3;
int l = i1 >> 2;
++l;
inputSlots.setInventorySlotContents(0, (ItemStack) null);
if(l > 2) {
world.setBlockToAir(x, y, z);
world.playAuxSFX(1020, x, y, z, 0);
} else {
world.setBlockMetadataWithNotify(x, y, z, k | l << 2, 2);
world.playAuxSFX(1021, x, y, z, 0);
}
} else if(!world.isRemote) {
world.playAuxSFX(1021, x, y, z, 0);
}
}
});
}
if (materialCost > 0) {
ItemStack itemstack1 = inputSlots.getStackInSlot(1);
if (itemstack1 != null && itemstack1.stackSize > materialCost) {
itemstack1.stackSize -= materialCost;
inputSlots.setInventorySlotContents(1, itemstack1);
} else {
inputSlots.setInventorySlotContents(1, (ItemStack) null);
}
} else {
inputSlots.setInventorySlotContents(1, (ItemStack) null);
}
ContainerDarkSteelAnvil.this.maximumCost = 0;
if (!player.capabilities.isCreativeMode && !world.isRemote
&& world.getBlock(x, y, z) == EnderIO.blockDarkSteelAnvil
&& player.getRNG().nextFloat() < Config.darkSteelAnvilDamageChance) {
int i1 = world.getBlockMetadata(x, y, z);
int k = i1 & 3;
int l = i1 >> 2;
++l;
if (l > 2) {
world.setBlockToAir(x, y, z);
world.playAuxSFX(1020, x, y, z, 0);
} else {
world.setBlockMetadataWithNotify(x, y, z, k | l << 2, 2);
world.playAuxSFX(1021, x, y, z, 0);
}
} else if (!world.isRemote) {
world.playAuxSFX(1021, x, y, z, 0);
}
}
});
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return player.worldObj.getBlock(this.x, this.y, this.z) == EnderIO.blockDarkSteelAnvil;
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return player.worldObj.getBlock(this.x, this.y, this.z) == EnderIO.blockDarkSteelAnvil;
}
}
@@ -1,30 +1,32 @@
package crazypants.enderio.block;
import net.minecraft.nbt.NBTTagCompound;
import crazypants.enderio.machine.painter.TileEntityPaintedBlock;
public class TileEntityDarkSteelPressurePlate extends TileEntityPaintedBlock {
private boolean silent;
private boolean silent;
public boolean isSilent() {
return silent;
}
public boolean isSilent() {
return silent;
}
public void setSilent(boolean silent) {
this.silent = silent;
}
public void setSilent(boolean silent) {
this.silent = silent;
}
@Override
public void readCustomNBT(NBTTagCompound nbtRoot) {
super.readCustomNBT(nbtRoot);
silent = nbtRoot.getBoolean("silent");
}
@Override
public void readCustomNBT(NBTTagCompound nbtRoot) {
super.readCustomNBT(nbtRoot);
silent = nbtRoot.getBoolean("silent");
}
@Override
public void writeCustomNBT(NBTTagCompound nbtRoot) {
super.writeCustomNBT(nbtRoot);
nbtRoot.setBoolean("silent", silent);
}
@Override
public void writeCustomNBT(NBTTagCompound nbtRoot) {
super.writeCustomNBT(nbtRoot);
nbtRoot.setBoolean("silent", silent);
}
}
File diff suppressed because it is too large. Load diff
@@ -7,99 +7,97 @@ import java.util.List;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import crazypants.enderio.EnderIO;
// I=base type, I is the base class of the implementations accepted by the network
//I=base type, I is the base class of the implementations accepted by the network
public abstract class AbstractConduitNetwork<T extends IConduit, I extends T> {
protected final List<I> conduits = new ArrayList<>();
protected final List<I> conduits = new ArrayList<I>();
protected final Class<I> implClass;
protected final Class<T> baseConduitClass;
protected final Class<I> implClass;
protected final Class<T> baseConduitClass;
protected AbstractConduitNetwork(Class<I> implClass, Class<T> baseConduitClass) {
this.implClass = implClass;
this.baseConduitClass = baseConduitClass;
protected AbstractConduitNetwork(Class<I> implClass, Class<T> baseConduitClass) {
this.implClass = implClass;
this.baseConduitClass = baseConduitClass;
}
public void init(IConduitBundle tile, Collection<I> connections, World world) {
if(world.isRemote) {
throw new UnsupportedOperationException();
}
public void init(IConduitBundle tile, Collection<I> connections, World world) {
// Destroy all existing redstone networks around this block
for (I con : connections) {
AbstractConduitNetwork<?, ?> network = con.getNetwork();
if(network != null) {
network.destroyNetwork();
}
}
setNetwork(world, tile);
notifyNetworkOfUpdate();
}
if (world.isRemote) {
throw new UnsupportedOperationException();
public final Class<T> getBaseConduitType() {
return baseConduitClass;
}
protected void setNetwork(World world, IConduitBundle tile) {
T conduit = tile.getConduit(getBaseConduitType());
if(conduit != null && implClass.isAssignableFrom(conduit.getClass()) && conduit.setNetwork(this)) {
addConduit(implClass.cast(conduit));
TileEntity te = tile.getEntity();
Collection<T> connections = ConduitUtil.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, getBaseConduitType());
for (T con : connections) {
if(con.getNetwork() == null) {
setNetwork(world, con.getBundle());
} else if(con.getNetwork() != this) {
con.getNetwork().destroyNetwork();
setNetwork(world, con.getBundle());
}
// Destroy all existing redstone networks around this block
for (I con : connections) {
AbstractConduitNetwork<?, ?> network = con.getNetwork();
if (network != null) {
network.destroyNetwork();
}
}
setNetwork(world, tile);
notifyNetworkOfUpdate();
}
}
}
public final Class<T> getBaseConduitType() {
return baseConduitClass;
public void addConduit(I con) {
if(!conduits.contains(con)) {
if(conduits.isEmpty()) {
ConduitNetworkTickHandler.instance.registerNetwork(this);
}
conduits.add(con);
}
}
protected void setNetwork(World world, IConduitBundle tile) {
T conduit = tile.getConduit(getBaseConduitType());
if (conduit != null && implClass.isAssignableFrom(conduit.getClass()) && conduit.setNetwork(this)) {
addConduit(implClass.cast(conduit));
TileEntity te = tile.getEntity();
Collection<T> connections = ConduitUtil
.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, getBaseConduitType());
for (T con : connections) {
if (con.getNetwork() == null) {
setNetwork(world, con.getBundle());
} else if (con.getNetwork() != this) {
con.getNetwork().destroyNetwork();
setNetwork(world, con.getBundle());
}
}
}
public void destroyNetwork() {
for (I con : conduits) {
con.setNetwork(null);
}
conduits.clear();
ConduitNetworkTickHandler.instance.unregisterNetwork(this);
}
public void addConduit(I con) {
if (!conduits.contains(con)) {
if (conduits.isEmpty()) {
EnderIO.proxy.conduitNetworkTickHandler.registerNetwork(this);
}
conduits.add(con);
}
public List<I> getConduits() {
return conduits;
}
public void notifyNetworkOfUpdate() {
for (I con : conduits) {
TileEntity te = con.getBundle().getEntity();
te.getWorldObj().markBlockForUpdate(te.xCoord, te.yCoord, te.zCoord);
}
}
public void destroyNetwork() {
for (I con : conduits) {
con.setNetwork(null);
}
conduits.clear();
EnderIO.proxy.conduitNetworkTickHandler.unregisterNetwork(this);
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (IConduit con : conduits) {
sb.append(con.getLocation());
sb.append(", ");
}
return "AbstractConduitNetwork [conduits=" + sb.toString() + "]";
}
public List<I> getConduits() {
return conduits;
}
public void notifyNetworkOfUpdate() {
for (I con : conduits) {
TileEntity te = con.getBundle().getEntity();
te.getWorldObj().markBlockForUpdate(te.xCoord, te.yCoord, te.zCoord);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (IConduit con : conduits) {
sb.append(con.getLocation());
sb.append(", ");
}
return "AbstractConduitNetwork [conduits=" + sb.toString() + "]";
}
public void doNetworkTick() {}
public void doNetworkTick() {
}
}
@@ -2,6 +2,10 @@ package crazypants.enderio.conduit;
import java.util.List;
import mods.immibis.microblocks.api.IMicroblockCoverSystem;
import mods.immibis.microblocks.api.IMicroblockSupporterTile;
import mods.immibis.microblocks.api.MicroblockAPIUtils;
import mods.immibis.microblocks.api.Part;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
@@ -24,177 +28,176 @@ import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.EnderIO;
import crazypants.enderio.EnderIOTab;
import crazypants.enderio.ModObject;
import crazypants.util.ForgeDirections;
import mods.immibis.microblocks.api.IMicroblockCoverSystem;
import mods.immibis.microblocks.api.IMicroblockSupporterTile;
import mods.immibis.microblocks.api.MicroblockAPIUtils;
import mods.immibis.microblocks.api.Part;
public abstract class AbstractItemConduit extends Item implements IConduitItem {
protected ModObject modObj;
protected ModObject modObj;
protected ItemConduitSubtype[] subtypes;
protected ItemConduitSubtype[] subtypes;
protected IIcon[] icons;
protected IIcon[] icons;
protected AbstractItemConduit(ModObject modObj, ItemConduitSubtype... subtypes) {
this.modObj = modObj;
this.subtypes = subtypes;
setCreativeTab(EnderIOTab.tabEnderIO);
setUnlocalizedName(modObj.unlocalisedName);
setMaxStackSize(64);
setHasSubtypes(true);
protected AbstractItemConduit(ModObject modObj, ItemConduitSubtype... subtypes) {
this.modObj = modObj;
this.subtypes = subtypes;
setCreativeTab(EnderIOTab.tabEnderIO);
setUnlocalizedName(modObj.unlocalisedName);
setMaxStackSize(64);
setHasSubtypes(true);
}
protected void init() {
GameRegistry.registerItem(this, modObj.unlocalisedName);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister IIconRegister) {
icons = new IIcon[subtypes.length];
int index = 0;
for (ItemConduitSubtype subtype : subtypes) {
icons[index] = IIconRegister.registerIcon(subtype.iconKey);
index++;
}
}
protected void init() {
GameRegistry.registerItem(this, modObj.unlocalisedName);
@Override
public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
if (MicroblocksUtil.supportMicroblocks() && tryAddToMicroblocks(stack, player, world, x, y, z, side)) {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister IIconRegister) {
icons = new IIcon[subtypes.length];
int index = 0;
for (ItemConduitSubtype subtype : subtypes) {
icons[index] = IIconRegister.registerIcon(subtype.iconKey);
index++;
BlockCoord placeAt = Util.canPlaceItem(stack, EnderIO.blockConduitBundle, player, world, x, y, z, side);
if(placeAt != null) {
if(!world.isRemote) {
if(world.setBlock(placeAt.x, placeAt.y, placeAt.z, EnderIO.blockConduitBundle, 0, 1)) {
TileEntity te = world.getTileEntity(placeAt.x, placeAt.y, placeAt.z);
if(te instanceof IConduitBundle) {
IConduitBundle bundle = (IConduitBundle) te;
bundle.addConduit(createConduit(stack, player));
ConduitUtil.playBreakSound(Block.soundTypeMetal, world, placeAt.x, placeAt.y, placeAt.z);
}
}
}
}
if(!player.capabilities.isCreativeMode) {
stack.stackSize--;
}
return true;
@Override
public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side,
float hitX, float hitY, float hitZ) {
if (MicroblocksUtil.supportMicroblocks() && tryAddToMicroblocks(stack, player, world, x, y, z, side)) {
return true;
} else {
ForgeDirection dir = ForgeDirection.values()[side];
int placeX = x + dir.offsetX;
int placeY = y + dir.offsetY;
int placeZ = z + dir.offsetZ;
if(world.getBlock(placeX, placeY, placeZ) == EnderIO.blockConduitBundle) {
IConduitBundle bundle = (TileConduitBundle) world.getTileEntity(placeX, placeY, placeZ);
if(bundle == null) {
System.out.println("AbstractItemConduit.onItemUse: Bundle null");
return false;
}
BlockCoord placeAt = Util.canPlaceItem(stack, EnderIO.blockConduitBundle, player, world, x, y, z, side);
if (placeAt != null) {
if (!world.isRemote) {
if (world.setBlock(placeAt.x, placeAt.y, placeAt.z, EnderIO.blockConduitBundle, 0, 1)) {
TileEntity te = world.getTileEntity(placeAt.x, placeAt.y, placeAt.z);
if (te instanceof IConduitBundle) {
IConduitBundle bundle = (IConduitBundle) te;
bundle.addConduit(createConduit(stack, player));
ConduitUtil.playBreakSound(Block.soundTypeMetal, world, placeAt.x, placeAt.y, placeAt.z);
}
}
if(!bundle.hasType(getBaseConduitType())) {
if(!world.isRemote) {
IConduit con = createConduit(stack, player);
if(con == null) {
System.out.println("AbstractItemConduit.onItemUse: Conduit null.");
return false;
}
if (!player.capabilities.isCreativeMode) {
stack.stackSize--;
bundle.addConduit(con);
ConduitUtil.playBreakSound(Block.soundTypeMetal, world, placeX, placeY, placeZ);
if(!player.capabilities.isCreativeMode) {
stack.stackSize--;
}
return true;
} else {
ForgeDirection dir = ForgeDirections.DIRECTIONS[side];
int placeX = x + dir.offsetX;
int placeY = y + dir.offsetY;
int placeZ = z + dir.offsetZ;
}
return true;
}
}
}
if (world.getBlock(placeX, placeY, placeZ) == EnderIO.blockConduitBundle) {
return false;
}
IConduitBundle bundle = (TileConduitBundle) world.getTileEntity(placeX, placeY, placeZ);
if (bundle == null) {
System.out.println("AbstractItemConduit.onItemUse: Bundle null");
return false;
}
if (!bundle.hasType(getBaseConduitType())) {
if (!world.isRemote) {
IConduit con = createConduit(stack, player);
if (con == null) {
System.out.println("AbstractItemConduit.onItemUse: Conduit null.");
return false;
}
bundle.addConduit(con);
ConduitUtil.playBreakSound(Block.soundTypeMetal, world, placeX, placeY, placeZ);
if (!player.capabilities.isCreativeMode) {
stack.stackSize--;
}
}
return true;
}
private boolean tryAddToMicroblocks(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side) {
TileEntity te = world.getTileEntity(x, y, z);
if (te != null && te.getClass().getName().equals("mods.immibis.microblocks.TileMicroblockContainer")) {
IMicroblockCoverSystem covers = ((IMicroblockSupporterTile) te).getCoverSystem();
world.setBlock(x, y, z, EnderIO.blockConduitBundle);
EnderIO.blockConduitBundle.onBlockActivated(world, x, y, z, player, side, 0, 0, 0);
IMicroblockCoverSystem newCovers = MicroblockAPIUtils.createMicroblockCoverSystem((IMicroblockSupporterTile) world.getTileEntity(x, y, z));
for (Part p : covers.getAllParts()) {
newCovers.addPart(p);
}
((TileConduitBundle)world.getTileEntity(x, y, z)).covers = newCovers;
return true;
}
return false;
}
@Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
// Conduit replacement
if (player.isSneaking()) {
return false;
}
TileEntity te = world.getTileEntity(x, y, z);
if (te == null || !(te instanceof IConduitBundle)) {
return false;
}
IConduitBundle bundle = (IConduitBundle) te;
IConduit existingConduit = bundle.getConduit(getBaseConduitType());
if (existingConduit == null) {
return false;
}
ItemStack existingConduitAsItemStack = existingConduit.createItem();
if (!ItemUtil.areStacksEqual(existingConduitAsItemStack, stack)) {
if (!world.isRemote) {
IConduit newConduit = createConduit(stack, player);
if (newConduit == null) {
System.out.println("AbstractItemConduit.onItemUse: Conduit null.");
return false;
}
bundle.removeConduit(existingConduit);
bundle.addConduit(newConduit);
if (!player.capabilities.isCreativeMode) {
stack.stackSize--;
for (ItemStack drop : existingConduit.getDrops()) {
if (!player.inventory.addItemStackToInventory(drop)) {
ItemUtil.spawnItemInWorldWithRandomMotion(world, drop, x, y, z);
}
}
player.inventoryContainer.detectAndSendChanges();
}
return false;
return true;
} else {
player.swingItem();
}
}
return false;
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int damage) {
damage = MathHelper.clamp_int(damage, 0, subtypes.length - 1);
return icons[damage];
}
private boolean tryAddToMicroblocks(ItemStack stack, EntityPlayer player, World world, int x, int y, int z,
int side) {
TileEntity te = world.getTileEntity(x, y, z);
if (te != null && te.getClass().getName().equals("mods.immibis.microblocks.TileMicroblockContainer")) {
IMicroblockCoverSystem covers = ((IMicroblockSupporterTile) te).getCoverSystem();
world.setBlock(x, y, z, EnderIO.blockConduitBundle);
EnderIO.blockConduitBundle.onBlockActivated(world, x, y, z, player, side, 0, 0, 0);
IMicroblockCoverSystem newCovers = MicroblockAPIUtils
.createMicroblockCoverSystem((IMicroblockSupporterTile) world.getTileEntity(x, y, z));
for (Part p : covers.getAllParts()) {
newCovers.addPart(p);
}
((TileConduitBundle) world.getTileEntity(x, y, z)).covers = newCovers;
return true;
}
return false;
}
@Override
public String getUnlocalizedName(ItemStack par1ItemStack) {
int i = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, subtypes.length - 1);
return subtypes[i].unlocalisedName;
@Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side,
float hitX, float hitY, float hitZ) {
// Conduit replacement
if (player.isSneaking()) {
return false;
}
TileEntity te = world.getTileEntity(x, y, z);
if (te == null || !(te instanceof IConduitBundle)) {
return false;
}
IConduitBundle bundle = (IConduitBundle) te;
IConduit existingConduit = bundle.getConduit(getBaseConduitType());
if (existingConduit == null) {
return false;
}
ItemStack existingConduitAsItemStack = existingConduit.createItem();
if (!ItemUtil.areStacksEqual(existingConduitAsItemStack, stack)) {
if (!world.isRemote) {
IConduit newConduit = createConduit(stack, player);
if (newConduit == null) {
System.out.println("AbstractItemConduit.onItemUse: Conduit null.");
return false;
}
bundle.replaceConduit(existingConduit, newConduit);
if (!player.capabilities.isCreativeMode) {
stack.stackSize--;
for (ItemStack drop : existingConduit.getDrops()) {
if (!player.inventory.addItemStackToInventory(drop)) {
ItemUtil.spawnItemInWorldWithRandomMotion(world, drop, x, y, z);
}
}
player.inventoryContainer.detectAndSendChanges();
}
return true;
} else {
player.swingItem();
}
}
return false;
}
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int damage) {
damage = MathHelper.clamp_int(damage, 0, subtypes.length - 1);
return icons[damage];
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
@SideOnly(Side.CLIENT)
public void getSubItems(Item par1, CreativeTabs par2CreativeTabs, List par3List) {
for (int j = 0; j < subtypes.length; ++j) {
par3List.add(new ItemStack(this, 1, j));
}
}
@Override
public String getUnlocalizedName(ItemStack par1ItemStack) {
int i = MathHelper.clamp_int(par1ItemStack.getItemDamage(), 0, subtypes.length - 1);
return subtypes[i].unlocalisedName;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item par1, CreativeTabs par2CreativeTabs, List<ItemStack> par3List) {
for (int j = 0; j < subtypes.length; ++j) {
par3List.add(new ItemStack(this, 1, j));
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,5 @@
package crazypants.enderio.conduit;
import static crazypants.enderio.gui.IconEIO.CROSS;
import static crazypants.enderio.gui.IconEIO.TICK;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_FLUID;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_FLUID_OFF;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_ITEM;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_ITEM_OFF;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_POWER;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_POWER_OFF;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_REDSTONE;
import static crazypants.enderio.gui.IconEIO.WRENCH_OVERLAY_REDSTONE_OFF;
import java.util.List;
import javax.annotation.Nonnull;
@@ -29,208 +18,226 @@ import crazypants.enderio.conduit.item.IItemConduit;
import crazypants.enderio.conduit.liquid.ILiquidConduit;
import crazypants.enderio.conduit.power.IPowerConduit;
import crazypants.enderio.conduit.redstone.IRedstoneConduit;
import static crazypants.enderio.gui.IconEIO.*;
public class ConduitDisplayMode {
public static final ConduitDisplayMode ALL = new ConduitDisplayMode("all", TICK, TICK);
public static final ConduitDisplayMode NONE = new ConduitDisplayMode("none", CROSS, CROSS);
public static final ConduitDisplayMode ALL = new ConduitDisplayMode("all", TICK, TICK);
public static final ConduitDisplayMode NONE = new ConduitDisplayMode("none", CROSS, CROSS);
private static final List<ConduitDisplayMode> registrar;
private static final List<ConduitDisplayMode> registrar;
// @formatter:off
static {
registrar = Lists.newArrayList(
NONE,
ALL,
new ConduitDisplayMode(IItemConduit.class, WRENCH_OVERLAY_ITEM, WRENCH_OVERLAY_ITEM_OFF),
new ConduitDisplayMode(ILiquidConduit.class, WRENCH_OVERLAY_FLUID, WRENCH_OVERLAY_FLUID_OFF),
new ConduitDisplayMode(IPowerConduit.class, WRENCH_OVERLAY_POWER, WRENCH_OVERLAY_POWER_OFF),
new ConduitDisplayMode(IRedstoneConduit.class, WRENCH_OVERLAY_REDSTONE, WRENCH_OVERLAY_REDSTONE_OFF)
);
}
// @formatter:on
// @formatter:off
static {
registrar = Lists.newArrayList(
NONE,
ALL,
new ConduitDisplayMode(IItemConduit.class, WRENCH_OVERLAY_ITEM, WRENCH_OVERLAY_ITEM_OFF),
new ConduitDisplayMode(ILiquidConduit.class, WRENCH_OVERLAY_FLUID, WRENCH_OVERLAY_FLUID_OFF),
new ConduitDisplayMode(IPowerConduit.class, WRENCH_OVERLAY_POWER, WRENCH_OVERLAY_POWER_OFF),
new ConduitDisplayMode(IRedstoneConduit.class, WRENCH_OVERLAY_REDSTONE, WRENCH_OVERLAY_REDSTONE_OFF));
public static void registerDisplayMode(ConduitDisplayMode mode) {
if (!registrar.contains(mode)) {
registrar.add(mode);
}
// @formatter:on
}
public static void registerDisplayMode(ConduitDisplayMode mode) {
if (!registrar.contains(mode)) {
registrar.add(mode);
}
private final Class<? extends IConduit> conduitType;
private final IWidgetIcon widgetSelected, widgetUnselected;
private String overrideName = null;
/**
* Use this constructor if you have custom display logic, it will use
* {@code IConduit.class} as the conduitType, and the passed name as the
* override name.
*
* @see #ConduitDisplayMode(Class, IWidgetIcon, IWidgetIcon)
*
* @param name
* The override name.
* @param widgetSelected
* The widget to render when this type is selected.
* @param widgetUnselected
* The widget to render when this type is unselected.
*/
public ConduitDisplayMode(String name, IWidgetIcon widgetSelected, IWidgetIcon widgetUnselected) {
this(IConduit.class, widgetSelected, widgetUnselected);
setName(name);
}
/**
* Creates a new display mode for any {@link IConduitControl} wrench. Contains
* data about which conduit type this is for, and the icons to render while
* holding the wrench. wrench.
*
* @param conduitType
* The base class for your conduit type, typically an interface (e.g.
* {@code IPowerConduit}).
* @param widgetSelected
* The widget to render when this type is selected.
* @param widgetUnselected
* The widget to render when this type is unselected.
*/
public ConduitDisplayMode(@Nonnull Class<? extends IConduit> conduitType, IWidgetIcon widgetSelected, IWidgetIcon widgetUnselected) {
this.conduitType = conduitType;
this.widgetSelected = widgetSelected;
this.widgetUnselected = widgetUnselected;
}
@Nullable
public Class<? extends IConduit> getConduitType() {
return conduitType;
}
public boolean renderConduit(Class<? extends IConduit> conduitType) {
if (this == ALL) {
return true;
} else if (this == NONE) {
return false;
} else {
return this.conduitType.isAssignableFrom(conduitType);
}
}
private final Class<? extends IConduit> conduitType;
private final IWidgetIcon widgetSelected, widgetUnselected;
@Nonnull
public String getName() {
return overrideName == null ? conduitType.getSimpleName() : overrideName;
}
private String overrideName = null;
/**
* The name is null by default, and will use the simple class name of the
* conduit type.
*
* @param name
* The override name to set.
*/
public void setName(@Nullable String name) {
this.overrideName = name;
}
/**
* Use this constructor if you have custom display logic, it will use {@code IConduit.class} as the conduitType, and
* the passed name as the override name.
*
* @param name The override name.
* @param widgetSelected The widget to render when this type is selected.
* @param widgetUnselected The widget to render when this type is unselected.
* @see #ConduitDisplayMode(Class, IWidgetIcon, IWidgetIcon)
*/
public ConduitDisplayMode(String name, IWidgetIcon widgetSelected, IWidgetIcon widgetUnselected) {
this(IConduit.class, widgetSelected, widgetUnselected);
setName(name);
public IWidgetIcon getWidgetSelected() {
return widgetSelected;
}
public IWidgetIcon getWidgetUnselected() {
return widgetUnselected;
}
public static ConduitDisplayMode next(ConduitDisplayMode mode) {
int index = registrar.indexOf(mode) + 1;
if (index >= registrar.size()) {
index = 0;
}
return registrar.get(index);
}
/**
* Creates a new display mode for any {@link IConduitControl} wrench. Contains data about which conduit type this is
* for, and the icons to render while holding the wrench. wrench.
*
* @param conduitType The base class for your conduit type, typically an interface (e.g.
* {@code IPowerConduit}).
* @param widgetSelected The widget to render when this type is selected.
* @param widgetUnselected The widget to render when this type is unselected.
*/
public ConduitDisplayMode(@Nonnull Class<? extends IConduit> conduitType, IWidgetIcon widgetSelected,
IWidgetIcon widgetUnselected) {
this.conduitType = conduitType;
this.widgetSelected = widgetSelected;
this.widgetUnselected = widgetUnselected;
public static ConduitDisplayMode previous(ConduitDisplayMode mode) {
int index = registrar.indexOf(mode) - 1;
if (index < 0) {
index = registrar.size() - 1;
}
return registrar.get(index);
}
@Nullable
public Class<? extends IConduit> getConduitType() {
return conduitType;
}
public boolean renderConduit(Class<? extends IConduit> conduitType) {
if (this == ALL) {
return true;
} else if (this == NONE) {
return false;
} else {
return this.conduitType.isAssignableFrom(conduitType);
}
}
@Nonnull
public String getName() {
return overrideName == null ? conduitType.getSimpleName() : overrideName;
}
/**
* The name is null by default, and will use the simple class name of the conduit type.
*
* @param name The override name to set.
*/
public void setName(@Nullable String name) {
this.overrideName = name;
}
public IWidgetIcon getWidgetSelected() {
return widgetSelected;
}
public IWidgetIcon getWidgetUnselected() {
return widgetUnselected;
}
public static ConduitDisplayMode next(ConduitDisplayMode mode) {
int index = registrar.indexOf(mode) + 1;
if (index >= registrar.size()) {
index = 0;
}
return registrar.get(index);
}
public static ConduitDisplayMode previous(ConduitDisplayMode mode) {
int index = registrar.indexOf(mode) - 1;
if (index < 0) {
index = registrar.size() - 1;
}
return registrar.get(index);
}
public static ConduitDisplayMode fromName(String name) {
for (ConduitDisplayMode mode : registrar) {
if (mode.getName().equals(name)) {
return mode;
}
}
return null;
}
private static final String NBT_KEY = "enderio.displaymode";
public static ConduitDisplayMode getDisplayMode(ItemStack equipped) {
if (equipped == null || !(equipped.getItem() instanceof IConduitControl)) {
return ALL;
}
initDisplayModeTag(equipped);
String name = equipped.stackTagCompound.getString(NBT_KEY);
ConduitDisplayMode mode = fromName(name);
if (mode == null) { // backwards compat
setDisplayMode(equipped, ALL);
return ALL;
}
public static ConduitDisplayMode fromName(String name) {
for (ConduitDisplayMode mode : registrar) {
if (mode.getName().equals(name)) {
return mode;
}
}
return null;
}
public static void setDisplayMode(ItemStack equipped, ConduitDisplayMode mode) {
if (mode == null || equipped == null || !(equipped.getItem() instanceof IConduitControl)) {
return;
}
initDisplayModeTag(equipped);
equipped.stackTagCompound.setString(NBT_KEY, mode.getName());
private static final String NBT_KEY = "enderio.displaymode";
public static ConduitDisplayMode getDisplayMode(ItemStack equipped) {
if (equipped == null || !(equipped.getItem() instanceof IConduitControl)) {
return ALL;
}
private static void initDisplayModeTag(ItemStack stack) {
if (stack.stackTagCompound == null) {
stack.stackTagCompound = new NBTTagCompound();
stack.stackTagCompound.setString(NBT_KEY, ConduitDisplayMode.ALL.getName());
}
initDisplayModeTag(equipped);
String name = equipped.stackTagCompound.getString(NBT_KEY);
ConduitDisplayMode mode = fromName(name);
if (mode == null) { // backwards compat
setDisplayMode(equipped, ALL);
return ALL;
}
return mode;
}
public ConduitDisplayMode next() {
return next(this);
public static void setDisplayMode(ItemStack equipped, ConduitDisplayMode mode) {
if (mode == null || equipped == null || !(equipped.getItem() instanceof IConduitControl)) {
return;
}
initDisplayModeTag(equipped);
equipped.stackTagCompound.setString(NBT_KEY, mode.getName());
}
public ConduitDisplayMode previous() {
return previous(this);
private static void initDisplayModeTag(ItemStack stack) {
if (stack.stackTagCompound == null) {
stack.stackTagCompound = new NBTTagCompound();
stack.stackTagCompound.setString(NBT_KEY, ConduitDisplayMode.ALL.getName());
}
}
public static int registrySize() {
return registrar.size() - 2;
}
public ConduitDisplayMode next() {
return next(this);
}
public static Iterable<ConduitDisplayMode> getRenderableModes() {
return FluentIterable.from(registrar).filter(new Predicate<>() {
public ConduitDisplayMode previous() {
return previous(this);
}
@Override
public boolean apply(ConduitDisplayMode input) {
return input != ALL && input != NONE;
}
});
}
public static int registrySize() {
return registrar.size() - 2;
}
@Override
public String toString() {
return getName();
}
public static Iterable<ConduitDisplayMode> getRenderableModes() {
return FluentIterable.from(registrar).filter(new Predicate<ConduitDisplayMode>() {
@Override
public boolean apply(ConduitDisplayMode input) {
return input != ALL && input != NONE;
}
});
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((conduitType == null) ? 0 : conduitType.hashCode());
result = prime * result + ((overrideName == null) ? 0 : overrideName.hashCode());
return result;
}
@Override
public String toString() {
return getName();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((conduitType == null) ? 0 : conduitType.hashCode());
result = prime * result + ((overrideName == null) ? 0 : overrideName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ConduitDisplayMode other = (ConduitDisplayMode) obj;
if (conduitType == null) {
if (other.conduitType != null) return false;
} else if (!conduitType.equals(other.conduitType)) return false;
if (overrideName == null) {
if (other.overrideName != null) return false;
} else if (!overrideName.equals(other.overrideName)) return false;
return true;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConduitDisplayMode other = (ConduitDisplayMode) obj;
if (conduitType == null) {
if (other.conduitType != null)
return false;
} else if (!conduitType.equals(other.conduitType))
return false;
if (overrideName == null) {
if (other.overrideName != null)
return false;
} else if (!overrideName.equals(other.overrideName))
return false;
return true;
}
}
@@ -10,54 +10,58 @@ import cpw.mods.fml.common.gameevent.TickEvent.Phase;
public class ConduitNetworkTickHandler {
public interface TickListener {
public static final ConduitNetworkTickHandler instance = new ConduitNetworkTickHandler();
void tickStart(TickEvent.ServerTickEvent evt);
public static interface TickListener {
public void tickStart(TickEvent.ServerTickEvent evt);
void tickEnd(TickEvent.ServerTickEvent evt);
public void tickEnd(TickEvent.ServerTickEvent evt);
}
private final List<TickListener> listeners = new ArrayList<TickListener>();
private final IdentityHashMap<AbstractConduitNetwork<?,?>, Boolean> networks =
new IdentityHashMap<AbstractConduitNetwork<?, ?>, Boolean>();
public void addListener(TickListener listener) {
listeners.add(listener);
}
public void removeListener(TickListener listener) {
listeners.remove(listener);
}
public void registerNetwork(AbstractConduitNetwork<?,?> cn) {
networks.put(cn, Boolean.TRUE);
}
public void unregisterNetwork(AbstractConduitNetwork<?,?> cn) {
networks.remove(cn);
}
@SubscribeEvent
public void onServerTick(TickEvent.ServerTickEvent event) {
if(event.phase == Phase.START) {
tickStart(event);
} else {
tickEnd(event);
}
}
private final List<TickListener> listeners = new ArrayList<>();
private final IdentityHashMap<AbstractConduitNetwork<?, ?>, Boolean> networks = new IdentityHashMap<>();
public void addListener(TickListener listener) {
listeners.add(listener);
public void tickStart(TickEvent.ServerTickEvent event) {
for (TickListener h : listeners) {
h.tickStart(event);
}
}
public void removeListener(TickListener listener) {
listeners.remove(listener);
public void tickEnd(TickEvent.ServerTickEvent event) {
for (TickListener h : listeners) {
h.tickEnd(event);
}
listeners.clear();
for(AbstractConduitNetwork<?,?> cn : networks.keySet()) {
cn.doNetworkTick();
}
}
public void registerNetwork(AbstractConduitNetwork<?, ?> cn) {
networks.put(cn, Boolean.TRUE);
}
public void unregisterNetwork(AbstractConduitNetwork<?, ?> cn) {
networks.remove(cn);
}
@SubscribeEvent
public void onServerTick(TickEvent.ServerTickEvent event) {
if (event.phase == Phase.START) {
tickStart(event);
} else {
tickEnd(event);
}
}
public void tickStart(TickEvent.ServerTickEvent event) {
for (TickListener h : listeners) {
h.tickStart(event);
}
}
public void tickEnd(TickEvent.ServerTickEvent event) {
for (TickListener h : listeners) {
h.tickEnd(event);
}
listeners.clear();
for (AbstractConduitNetwork<?, ?> cn : networks.keySet()) {
cn.doNetworkTick();
}
}
}
@@ -1,29 +1,11 @@
package crazypants.enderio.conduit;
import static crazypants.enderio.ModObject.blockPainter;
import static crazypants.enderio.material.Alloy.CONDUCTIVE_IRON;
import static crazypants.enderio.material.Alloy.ELECTRICAL_STEEL;
import static crazypants.enderio.material.Alloy.END_STEEL;
import static crazypants.enderio.material.Alloy.ENERGETIC_ALLOY;
import static crazypants.enderio.material.Alloy.PHASED_GOLD;
import static crazypants.enderio.material.Alloy.REDSTONE_ALLOY;
import static crazypants.enderio.material.Material.CONDUIT_BINDER;
import static crazypants.enderio.material.Material.PHASED_IRON_NUGGET;
import static crazypants.enderio.material.endergy.AlloyEndergy.CRUDE_STEEL;
import static crazypants.enderio.material.endergy.AlloyEndergy.CRYSTALLINE_ALLOY;
import static crazypants.enderio.material.endergy.AlloyEndergy.CRYSTALLINE_PINK_SLIME;
import static crazypants.enderio.material.endergy.AlloyEndergy.ENERGETIC_SILVER;
import static crazypants.enderio.material.endergy.AlloyEndergy.MELODIC_ALLOY;
import static crazypants.enderio.material.endergy.AlloyEndergy.STELLAR_ALLOY;
import static crazypants.util.RecipeUtil.addShaped;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import appeng.api.AEApi;
import cpw.mods.fml.common.Optional.Method;
import cpw.mods.fml.common.registry.GameRegistry;
@@ -45,658 +27,215 @@ import crazypants.enderio.material.BlockFusedQuartz;
import crazypants.enderio.material.FrankenSkull;
import crazypants.enderio.material.Material;
import static crazypants.enderio.ModObject.blockPainter;
import static crazypants.enderio.material.Alloy.*;
import static crazypants.enderio.material.endergy.AlloyEndergy.*;
import static crazypants.enderio.material.Material.*;
import static crazypants.util.RecipeUtil.addShaped;
public class ConduitRecipes {
public static void addRecipes() {
public static void addRecipes() {
// Crafting Components
ItemStack redstoneConduit = new ItemStack(EnderIO.itemRedstoneConduit, 1, 0);
//Crafting Components
ItemStack redstoneConduit = new ItemStack(EnderIO.itemRedstoneConduit, 1, 0);
ItemStack fusedQuartz = new ItemStack(EnderIO.blockFusedQuartz, 1, 0);
ItemStack fusedGlass = new ItemStack(EnderIO.blockFusedQuartz, 1, BlockFusedQuartz.Type.GLASS.ordinal());
ItemStack fusedQuartz = new ItemStack(EnderIO.blockFusedQuartz, 1, 0);
ItemStack fusedGlass = new ItemStack(EnderIO.blockFusedQuartz, 1, BlockFusedQuartz.Type.GLASS.ordinal());
String crudeSteel = CRUDE_STEEL.getOreIngot();
String energeticSilver = ENERGETIC_SILVER.getOreIngot();
String crystallineAlloy = CRYSTALLINE_ALLOY.getOreIngot();
String crystallinePinkSlime = CRYSTALLINE_PINK_SLIME.getOreIngot();
String melodicAlloy = MELODIC_ALLOY.getOreIngot();
String stellarAlloy = STELLAR_ALLOY.getOreIngot();
String crudeSteel = CRUDE_STEEL.getOreIngot();
String energeticSilver = ENERGETIC_SILVER.getOreIngot();
String crystallineAlloy = CRYSTALLINE_ALLOY.getOreIngot();
String crystallinePinkSlime = CRYSTALLINE_PINK_SLIME.getOreIngot();
String melodicAlloy = MELODIC_ALLOY.getOreIngot();
String stellarAlloy = STELLAR_ALLOY.getOreIngot();
String electricalSteel = ELECTRICAL_STEEL.getOreIngot();
String phasedGold = PHASED_GOLD.getOreIngot();
String conductiveIron = CONDUCTIVE_IRON.getOreIngot();
String energeticGold = ENERGETIC_ALLOY.getOreIngot();
String phasedIronNugget = PHASED_IRON_NUGGET.oreDict;
String redstoneAlloy = REDSTONE_ALLOY.getOreIngot();
String electricalSteel = ELECTRICAL_STEEL.getOreIngot();
String phasedGold = PHASED_GOLD.getOreIngot();
String conductiveIron = CONDUCTIVE_IRON.getOreIngot();
String energeticGold = ENERGETIC_ALLOY.getOreIngot();
String phasedIronNugget = PHASED_IRON_NUGGET.oreDict;
String redstoneAlloy = REDSTONE_ALLOY.getOreIngot();
String binder = CONDUIT_BINDER.oreDict;
String binder = CONDUIT_BINDER.oreDict;
ItemStack zombieController = new ItemStack(
EnderIO.itemFrankenSkull,
1,
FrankenSkull.ZOMBIE_CONTROLLER.ordinal());
ItemStack skeletalContractor = new ItemStack(
EnderIO.itemFrankenSkull,
1,
FrankenSkull.SKELETAL_CONTRACTOR.ordinal());
ItemStack zombieController = new ItemStack(EnderIO.itemFrankenSkull, 1, FrankenSkull.ZOMBIE_CONTROLLER.ordinal());
ItemStack skeletalContractor = new ItemStack(EnderIO.itemFrankenSkull, 1, FrankenSkull.SKELETAL_CONTRACTOR.ordinal());
// Recipes
addShaped(
new ItemStack(EnderIO.itemConduitFacade, 1, FacadeType.BASIC.ordinal()),
"bbb",
"b b",
"bbb",
'b',
binder);
GameRegistry.addRecipe(
new ShapedOreRecipe(
new ItemStack(EnderIO.itemConduitFacade, 1, FacadeType.HARDENED.ordinal()),
" o ",
"oFo",
" o ",
'F',
EnderIO.itemConduitFacade,
'o',
"dustObsidian"));
//Recipes
addShaped(new ItemStack(EnderIO.itemConduitFacade, 1, FacadeType.BASIC.ordinal()), "bbb", "b b", "bbb", 'b', binder);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(EnderIO.itemConduitFacade, 1, FacadeType.HARDENED.ordinal()), " o ", "oFo", " o ", 'F',
EnderIO.itemConduitFacade, 'o', "dustObsidian"));
int numConduits = Config.numConduitsPerRecipe;
addShaped(
new ItemStack(EnderIO.itemLiquidConduit, numConduits, 0),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
fusedGlass);
addShaped(
new ItemStack(EnderIO.itemLiquidConduit, numConduits, 1),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
fusedQuartz);
addShaped(
new ItemStack(EnderIO.itemLiquidConduit, numConduits, EnderLiquidConduit.METADATA),
"bbb",
"#p#",
"bbb",
'b',
binder,
'#',
fusedQuartz,
'p',
phasedGold);
addShaped(
new ItemStack(EnderIO.itemLiquidConduit, numConduits, CrystallineEnderLiquidConduit.METADATA),
"bbb",
"#p#",
"bbb",
'b',
binder,
'#',
fusedQuartz,
'p',
crystallineAlloy);
addShaped(
new ItemStack(EnderIO.itemLiquidConduit, numConduits, CrystallinePinkSlimeEnderLiquidConduit.METADATA),
"bbb",
"#p#",
"bbb",
'b',
binder,
'#',
fusedQuartz,
'p',
crystallinePinkSlime);
addShaped(
new ItemStack(EnderIO.itemLiquidConduit, numConduits, MelodicEnderLiquidConduit.METADATA),
"bbb",
"#p#",
"bbb",
'b',
binder,
'#',
fusedQuartz,
'p',
melodicAlloy);
addShaped(
new ItemStack(EnderIO.itemLiquidConduit, numConduits, StellarEnderLiquidConduit.METADATA),
"bbb",
"#p#",
"bbb",
'b',
binder,
'#',
fusedQuartz,
'p',
stellarAlloy);
addShaped(new ItemStack(EnderIO.itemRedstoneConduit, numConduits, 0), "###", '#', redstoneAlloy);
addShaped(
new ItemStack(EnderIO.itemRedstoneConduit, 1, 1),
"lbl",
"bcb",
"lbl",
'b',
binder,
'c',
redstoneConduit,
'l',
Blocks.lever);
addShaped(
new ItemStack(EnderIO.itemRedstoneConduit, numConduits, 2),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
redstoneAlloy);
int numConduits = Config.numConduitsPerRecipe;
addShaped(new ItemStack(EnderIO.itemLiquidConduit, numConduits, 0), "bbb", "###", "bbb", 'b', binder, '#', fusedGlass);
addShaped(new ItemStack(EnderIO.itemLiquidConduit, numConduits, 1), "bbb", "###", "bbb", 'b', binder, '#', fusedQuartz);
addShaped(new ItemStack(EnderIO.itemLiquidConduit, numConduits, EnderLiquidConduit.METADATA), "bbb", "#p#", "bbb", 'b', binder, '#', fusedQuartz, 'p', phasedGold);
addShaped(new ItemStack(EnderIO.itemLiquidConduit, numConduits, CrystallineEnderLiquidConduit.METADATA), "bbb", "#p#", "bbb", 'b', binder, '#', fusedQuartz, 'p', crystallineAlloy);
addShaped(new ItemStack(EnderIO.itemLiquidConduit, numConduits, CrystallinePinkSlimeEnderLiquidConduit.METADATA), "bbb", "#p#", "bbb", 'b', binder, '#', fusedQuartz, 'p', crystallinePinkSlime);
addShaped(new ItemStack(EnderIO.itemLiquidConduit, numConduits, MelodicEnderLiquidConduit.METADATA), "bbb", "#p#", "bbb", 'b', binder, '#', fusedQuartz, 'p', melodicAlloy);
addShaped(new ItemStack(EnderIO.itemLiquidConduit, numConduits, StellarEnderLiquidConduit.METADATA), "bbb", "#p#", "bbb", 'b', binder, '#', fusedQuartz, 'p', stellarAlloy);
addShaped(new ItemStack(EnderIO.itemRedstoneConduit, numConduits, 0), "###", '#', redstoneAlloy);
addShaped(new ItemStack(EnderIO.itemRedstoneConduit, 1, 1), "lbl", "bcb", "lbl", 'b', binder, 'c', redstoneConduit, 'l', Blocks.lever);
addShaped(new ItemStack(EnderIO.itemRedstoneConduit, numConduits, 2), "bbb", "###", "bbb", 'b', binder, '#', redstoneAlloy);
if (Config.useHardRecipes) {
if(Config.useHardRecipes) {
ItemStack lastTier;
ItemStack lastTier;
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 0),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
crudeSteel);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 0);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 0), "bbb", "###", "bbb", 'b', binder, '#', crudeSteel);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 0);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 1),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
"ingotIron");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 1);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 1), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', "ingotIron");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 1);
if (OreDictionary.doesOreNameExist("ingotAluminum") || OreDictionary.doesOreNameExist("ingotAluminium")) {
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 2),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
"ingotAluminum");
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 2),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
"ingotAluminium");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 2);
}
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 3),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
"ingotGold");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 3);
if (OreDictionary.doesOreNameExist("ingotCopper") && OreDictionary.getOres("ingotCopper").size() > 0) {
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 4),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
"ingotCopper");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 4);
}
addShaped(
new ItemStack(EnderIO.itemPowerConduit, numConduits, 0),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
conductiveIron);
lastTier = new ItemStack(EnderIO.itemPowerConduit, 1, 0);
if (OreDictionary.doesOreNameExist("ingotSilver")) {
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 5),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
"ingotSilver");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 5);
}
if (OreDictionary.doesOreNameExist("ingotElectrum")) {
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 6),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
"ingotElectrum");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 6);
}
addShaped(
new ItemStack(EnderIO.itemPowerConduit, numConduits, 1),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
energeticGold);
lastTier = new ItemStack(EnderIO.itemPowerConduit, 1, 1);
if (OreDictionary.doesOreNameExist("ingotSilver")) {
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 7),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
energeticSilver);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 7);
}
addShaped(
new ItemStack(EnderIO.itemPowerConduit, numConduits, 2),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
phasedGold);
lastTier = new ItemStack(EnderIO.itemPowerConduit, 1, 2);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 8),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
crystallineAlloy);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 8);
if (OreDictionary.doesOreNameExist("slimeballPink")) {
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 9),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
crystallinePinkSlime);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 9);
}
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 10),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
melodicAlloy);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 10);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 11),
"b#b",
"ccc",
"b#b",
'c',
lastTier,
'b',
binder,
'#',
stellarAlloy);
} else {
addShaped(
new ItemStack(EnderIO.itemPowerConduit, numConduits, 0),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
conductiveIron);
addShaped(
new ItemStack(EnderIO.itemPowerConduit, numConduits, 1),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
energeticGold);
addShaped(
new ItemStack(EnderIO.itemPowerConduit, numConduits, 2),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
phasedGold);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 0),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
crudeSteel);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 1),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
"ingotIron");
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 2),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
"ingotAluminum");
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 3),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
"ingotGold");
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 4),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
"ingotCopper");
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 5),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
"ingotSilver");
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 6),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
"ingotElectrum");
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 7),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
energeticSilver);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 8),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
crystallineAlloy);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 9),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
crystallinePinkSlime);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 10),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
melodicAlloy);
addShaped(
new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 11),
"bbb",
"###",
"bbb",
'b',
binder,
'#',
stellarAlloy);
}
if (GasUtil.isGasConduitEnabled()) {
addShaped(
new ItemStack(EnderIO.itemGasConduit, numConduits, 0),
"bbb",
"#g#",
"bbb",
'b',
binder,
'#',
electricalSteel,
'g',
fusedGlass);
if(OreDictionary.doesOreNameExist("ingotAluminum")||OreDictionary.doesOreNameExist("ingotAluminium")) {
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 2), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', "ingotAluminum");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 2), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', "ingotAluminium");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 2);
}
ItemStack itemConduit = new ItemStack(EnderIO.itemItemConduit, numConduits, 0);
addShaped(itemConduit, "bbb", "###", "bbb", 'b', binder, '#', phasedIronNugget);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 3), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', "ingotGold");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 3);
MachineRecipeRegistry.instance
.registerRecipe(blockPainter.unlocalisedName, EnderIO.itemConduitFacade.new FacadePainterRecipe());
if(OreDictionary.doesOreNameExist("ingotCopper") && OreDictionary.getOres("ingotCopper").size()>0) {
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 4), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', "ingotCopper");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 4);
}
// Filter Recipes
ItemStack basicFilter = new ItemStack(EnderIO.itemBasicFilterUpgrade, 1, 0);
addShaped(basicFilter, " p ", "php", " p ", 'p', Items.paper, 'h', Blocks.hopper);
addShaped(new ItemStack(EnderIO.itemPowerConduit, numConduits, 0), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', conductiveIron);
lastTier = new ItemStack(EnderIO.itemPowerConduit, 1, 0);
ItemStack advFilter = new ItemStack(EnderIO.itemBasicFilterUpgrade, 1, 1);
addShaped(advFilter, "rpr", "pzp", "rpr", 'p', Items.paper, 'z', zombieController, 'r', "dustRedstone");
if(OreDictionary.doesOreNameExist("ingotSilver")) {
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 5), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', "ingotSilver");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 5);
}
ItemStack bigFilter = new ItemStack(EnderIO.itemBigFilterUpgrade, 1, 0);
addShaped(bigFilter, "opo", "psp", "opo", 'p', Items.paper, 's', skeletalContractor, 'o', "dustObsidian");
if(OreDictionary.doesOreNameExist("ingotElectrum")) {
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 6), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', "ingotElectrum");
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 6);
}
ItemStack bigAdvFilter = new ItemStack(EnderIO.itemBigFilterUpgrade, 1, 1);
addShaped(bigAdvFilter, "eme", "mfm", "eme", 'm', melodicAlloy, 'f', bigFilter, 'e', END_STEEL.getOreIngot());
addShaped(new ItemStack(EnderIO.itemPowerConduit, numConduits, 1), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', energeticGold);
lastTier = new ItemStack(EnderIO.itemPowerConduit, 1, 1);
ItemStack modFilter = new ItemStack(EnderIO.itemModItemFilter, 1, 0);
addShaped(modFilter, " p ", "pwp", " p ", 'p', Items.paper, 'w', EnderIO.itemYetaWench);
if(OreDictionary.doesOreNameExist("ingotSilver")) {
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 7), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', energeticSilver);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 7);
}
ItemStack exFilt = new ItemStack(EnderIO.itemExistingItemFilter);
addShaped(
exFilt,
" r ",
"rfr",
" c ",
'c',
new ItemStack(Items.comparator, 1, 0),
'r',
"dustRedstone",
'f',
advFilter);
addShaped(new ItemStack(EnderIO.itemPowerConduit, numConduits, 2), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', phasedGold);
lastTier = new ItemStack(EnderIO.itemPowerConduit, 1, 2);
ItemStack limitedFilter = new ItemStack(EnderIO.itemLimitedItemFilter, 1, 0);
addShaped(limitedFilter, " ", "cfc", " ", 'c', new ItemStack(Items.comparator, 1, 0), 'f', advFilter);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 8), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', crystallineAlloy);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 8);
ItemStack powerFilt = new ItemStack(EnderIO.itemPowerItemFilter);
addShaped(powerFilt, " p ", "pcp", " p ", 'p', Items.paper, 'c', EnderIO.itemConduitProbe);
if(OreDictionary.doesOreNameExist("slimeballPink")) {
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 9), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', crystallinePinkSlime);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 9);
}
ClearFilterRecipe clearRec = new ClearFilterRecipe();
MinecraftForge.EVENT_BUS.register(clearRec);
GameRegistry.addRecipe(clearRec);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 10), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', melodicAlloy);
lastTier = new ItemStack(EnderIO.itemPowerConduitEndergy, 1, 10);
CopyFilterRecipe copyRec = new CopyFilterRecipe();
GameRegistry.addRecipe(copyRec);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 11), "b#b", "ccc", "b#b", 'c', lastTier, 'b', binder, '#', stellarAlloy);
ItemStack speedUpgrade = new ItemStack(EnderIO.itemExtractSpeedUpgrade, 1, 0);
addShaped(
speedUpgrade,
"iii",
"epe",
"ere",
'p',
Blocks.piston,
'e',
electricalSteel,
'r',
Blocks.redstone_torch,
'i',
"ingotIron");
ItemStack speedDowngrade = new ItemStack(EnderIO.itemExtractSpeedUpgrade, 1, 1);
addShaped(
speedDowngrade,
"iii",
"ese",
"ete",
's',
"slimeball",
'e',
electricalSteel,
't',
"stickWood",
'i',
"ingotIron");
addShaped(
speedDowngrade,
"iii",
"ese",
"ete",
's',
"slimeball",
'e',
electricalSteel,
't',
"woodStick",
'i',
"ingotIron");
if (MEUtil.isMEEnabled()) {
addAeRecipes();
}
if (OCUtil.isOCEnabled()) {
addOCRecipes();
}
}
private static void addOCRecipes() {
int numConduits = Config.numConduitsPerRecipe;
String redstoneAlloy = REDSTONE_ALLOY.getOreIngot();
String binder = CONDUIT_BINDER.oreDict;
else {
addShaped(new ItemStack(EnderIO.itemPowerConduit, numConduits, 0), "bbb", "###", "bbb", 'b', binder, '#', conductiveIron);
addShaped(new ItemStack(EnderIO.itemPowerConduit, numConduits, 1), "bbb", "###", "bbb", 'b', binder, '#', energeticGold);
addShaped(new ItemStack(EnderIO.itemPowerConduit, numConduits, 2), "bbb", "###", "bbb", 'b', binder, '#', phasedGold);
addShaped(
new ItemStack(EnderIO.itemOCConduit, numConduits, 0),
"bbb",
"rir",
"bbb",
'b',
binder,
'r',
redstoneAlloy,
'i',
"ingotIron");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 0), "bbb", "###", "bbb", 'b', binder, '#', crudeSteel);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 1), "bbb", "###", "bbb", 'b', binder, '#', "ingotIron");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 2), "bbb", "###", "bbb", 'b', binder, '#', "ingotAluminum");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 3), "bbb", "###", "bbb", 'b', binder, '#', "ingotGold");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 4), "bbb", "###", "bbb", 'b', binder, '#', "ingotCopper");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 5), "bbb", "###", "bbb", 'b', binder, '#', "ingotSilver");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 6), "bbb", "###", "bbb", 'b', binder, '#', "ingotElectrum");
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 7), "bbb", "###", "bbb", 'b', binder, '#', energeticSilver);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 8), "bbb", "###", "bbb", 'b', binder, '#', crystallineAlloy);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 9), "bbb", "###", "bbb", 'b', binder, '#', crystallinePinkSlime);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 10), "bbb", "###", "bbb", 'b', binder, '#', melodicAlloy);
addShaped(new ItemStack(EnderIO.itemPowerConduitEndergy, numConduits, 11), "bbb", "###", "bbb", 'b', binder, '#', stellarAlloy);
}
if (GasUtil.isGasConduitEnabled()) {
addShaped(new ItemStack(EnderIO.itemGasConduit, numConduits, 0), "bbb", "#g#", "bbb", 'b', binder, '#', electricalSteel, 'g', fusedGlass);
}
@Method(modid = "appliedenergistics2")
private static void addAeRecipes() {
String fluix = "crystalFluix";
String pureFluix = "crystalPureFluix";
ItemStack itemConduit = new ItemStack(EnderIO.itemItemConduit, numConduits, 0);
addShaped(itemConduit, "bbb", "###", "bbb", 'b', binder, '#', phasedIronNugget);
ItemStack quartzFiber = AEApi.instance().definitions().parts().quartzFiber().maybeStack(1).get().copy();
ItemStack conduitBinder = new ItemStack(EnderIO.itemMaterial, 1, Material.CONDUIT_BINDER.ordinal());
ItemStack res = new ItemStack(EnderIO.itemMEConduit, Config.numConduitsPerRecipe / 2);
MachineRecipeRegistry.instance.registerRecipe(blockPainter.unlocalisedName, EnderIO.itemConduitFacade.new FacadePainterRecipe());
addShaped(res.copy(), "bbb", "fqf", "bbb", 'b', conduitBinder, 'f', fluix, 'q', quartzFiber);
addShaped(res.copy(), "bbb", "fqf", "bbb", 'b', conduitBinder, 'f', pureFluix, 'q', quartzFiber);
//Filter Recipes
ItemStack basicFilter = new ItemStack(EnderIO.itemBasicFilterUpgrade, 1, 0);
addShaped(basicFilter, " p ", "php", " p ", 'p', Items.paper, 'h', Blocks.hopper);
res.stackSize = 1;
ItemStack resDense = new ItemStack(EnderIO.itemMEConduit, 1, 1);
addShaped(resDense, "bCb", "CbC", "bCb", 'b', conduitBinder, 'C', res);
ItemStack advFilter = new ItemStack(EnderIO.itemBasicFilterUpgrade, 1, 1);
addShaped(advFilter, "rpr", "pzp", "rpr", 'p', Items.paper, 'z', zombieController, 'r', "dustRedstone");
ItemStack bigFilter = new ItemStack(EnderIO.itemBigFilterUpgrade, 1, 0);
addShaped(bigFilter, "opo", "psp", "opo", 'p', Items.paper, 's', skeletalContractor, 'o', "dustObsidian");
ItemStack bigAdvFilter = new ItemStack(EnderIO.itemBigFilterUpgrade, 1, 1);
addShaped(bigAdvFilter, "eme", "mfm", "eme", 'm', melodicAlloy, 'f', bigFilter, 'e', END_STEEL.getOreIngot());
ItemStack modFilter = new ItemStack(EnderIO.itemModItemFilter, 1, 0);
addShaped(modFilter, " p ", "pwp", " p ", 'p', Items.paper, 'w', EnderIO.itemYetaWench);
ItemStack exFilt = new ItemStack(EnderIO.itemExistingItemFilter);
addShaped(exFilt, " r ", "rfr", " c ", 'c', new ItemStack(Items.comparator, 1, 0), 'r', "dustRedstone", 'f', advFilter);
ItemStack powerFilt = new ItemStack(EnderIO.itemPowerItemFilter);
addShaped(powerFilt, " p ", "pcp", " p ", 'p', Items.paper, 'c', EnderIO.itemConduitProbe);
ClearFilterRecipe clearRec = new ClearFilterRecipe();
MinecraftForge.EVENT_BUS.register(clearRec);
GameRegistry.addRecipe(clearRec);
CopyFilterRecipe copyRec = new CopyFilterRecipe();
GameRegistry.addRecipe(copyRec);
ItemStack speedUpgrade = new ItemStack(EnderIO.itemExtractSpeedUpgrade, 1, 0);
addShaped(speedUpgrade, "iii", "epe", "ere", 'p', Blocks.piston, 'e', electricalSteel, 'r', Blocks.redstone_torch, 'i', "ingotIron");
ItemStack speedDowngrade = new ItemStack(EnderIO.itemExtractSpeedUpgrade, 1, 1);
addShaped(speedDowngrade, "iii", "ese", "ete", 's', "slimeball", 'e', electricalSteel, 't', "stickWood", 'i', "ingotIron");
addShaped(speedDowngrade, "iii", "ese", "ete", 's', "slimeball", 'e', electricalSteel, 't', "woodStick", 'i', "ingotIron");
if (MEUtil.isMEEnabled()) {
addAeRecipes();
}
if (OCUtil.isOCEnabled()) {
addOCRecipes();
}
}
private static void addOCRecipes() {
int numConduits = Config.numConduitsPerRecipe;
String redstoneAlloy = REDSTONE_ALLOY.getOreIngot();
String binder = CONDUIT_BINDER.oreDict;
addShaped(new ItemStack(EnderIO.itemOCConduit, numConduits, 0), "bbb", "rir", "bbb", 'b', binder, 'r', redstoneAlloy, 'i',
"ingotIron");
}
@Method(modid = "appliedenergistics2")
private static void addAeRecipes() {
String fluix = "crystalFluix";
String pureFluix = "crystalPureFluix";
ItemStack quartzFiber = AEApi.instance().parts().partQuartzFiber.stack(1).copy();
ItemStack conduitBinder = new ItemStack(EnderIO.itemMaterial, 1, Material.CONDUIT_BINDER.ordinal());
ItemStack res = new ItemStack(EnderIO.itemMEConduit, Config.numConduitsPerRecipe / 2);
addShaped(res.copy(), "bbb", "fqf", "bbb", 'b', conduitBinder, 'f', fluix, 'q', quartzFiber);
addShaped(res.copy(), "bbb", "fqf", "bbb", 'b', conduitBinder, 'f', pureFluix, 'q', quartzFiber);
res.stackSize = 1;
addShaped(new ItemStack(EnderIO.itemMEConduit, 1, 1), "bCb", "CbC", "bCb", 'b', conduitBinder, 'C', res);
}
}
@@ -41,425 +41,380 @@ import crazypants.enderio.tool.ToolUtil;
public class ConduitUtil {
public static final Random RANDOM = new Random();
public static final Random RANDOM = new Random();
@SuppressWarnings("unchecked")
public static void ensureValidNetwork(IConduit conduit) {
TileEntity te = conduit.getBundle().getEntity();
World world = te.getWorldObj();
Collection<? extends IConduit> connections = ConduitUtil
.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, conduit.getBaseConduitType());
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void ensureValidNetwork(IConduit conduit) {
TileEntity te = conduit.getBundle().getEntity();
World world = te.getWorldObj();
Collection<? extends IConduit> connections = ConduitUtil.getConnectedConduits(world, te.xCoord, te.yCoord, te.zCoord, conduit.getBaseConduitType());
if (reuseNetwork(conduit, connections, world)) {
return;
}
@SuppressWarnings("rawtypes")
AbstractConduitNetwork res = conduit.createNetworkForType();
res.init(conduit.getBundle(), connections, world);
return;
if(reuseNetwork(conduit, connections, world)) {
return;
}
@SuppressWarnings("unchecked")
private static boolean reuseNetwork(IConduit con, Collection<? extends IConduit> connections, World world) {
@SuppressWarnings("rawtypes")
AbstractConduitNetwork network = null;
for (IConduit conduit : connections) {
if (network == null) {
network = conduit.getNetwork();
} else if (network != conduit.getNetwork()) {
return false;
}
}
if (network == null) {
return false;
}
if (con.setNetwork(network)) {
network.addConduit(con);
network.notifyNetworkOfUpdate();
return true;
}
AbstractConduitNetwork res = conduit.createNetworkForType();
res.init(conduit.getBundle(), connections, world);
return;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static boolean reuseNetwork(IConduit con, Collection<? extends IConduit> connections, World world) {
AbstractConduitNetwork network = null;
for (IConduit conduit : connections) {
if(network == null) {
network = conduit.getNetwork();
} else if(network != conduit.getNetwork()) {
return false;
}
}
if(network == null) {
return false;
}
if(con.setNetwork(network)) {
network.addConduit(con);
network.notifyNetworkOfUpdate();
return true;
}
return false;
}
public static <T extends IConduit> void disconectConduits(T con, ForgeDirection connDir) {
con.conduitConnectionRemoved(connDir);
BlockCoord loc = con.getLocation().getLocation(connDir);
IConduit neighbour = ConduitUtil.getConduit(con.getBundle().getEntity().getWorldObj(), loc.x, loc.y, loc.z, con.getBaseConduitType());
if(neighbour != null) {
neighbour.conduitConnectionRemoved(connDir.getOpposite());
if(neighbour.getNetwork() != null) {
neighbour.getNetwork().destroyNetwork();
}
}
if(con.getNetwork() != null) { //this should have been destroyed when destroying the neighbours network but lets just make sure
con.getNetwork().destroyNetwork();
}
con.connectionsChanged();
if(neighbour != null) {
neighbour.connectionsChanged();
}
}
public static <T extends IConduit> boolean joinConduits(T con, ForgeDirection faceHit) {
BlockCoord loc = con.getLocation().getLocation(faceHit);
IConduit neighbour = ConduitUtil.getConduit(con.getBundle().getEntity().getWorldObj(), loc.x, loc.y, loc.z, con.getBaseConduitType());
if(neighbour != null && con.canConnectToConduit(faceHit, neighbour) && neighbour.canConnectToConduit(faceHit.getOpposite(), con)) {
con.conduitConnectionAdded(faceHit);
neighbour.conduitConnectionAdded(faceHit.getOpposite());
if(con.getNetwork() != null) {
con.getNetwork().destroyNetwork();
}
if(neighbour.getNetwork() != null) {
neighbour.getNetwork().destroyNetwork();
}
con.connectionsChanged();
neighbour.connectionsChanged();
return true;
}
return false;
}
public static boolean forceSkylightRecalculation(World worldObj, int xCoord, int yCoord, int zCoord) {
int height = worldObj.getHeightValue(xCoord, zCoord);
if(height <= yCoord) {
for (int i = 1; i < 12; i++) {
if(worldObj.isAirBlock(xCoord, yCoord + i, zCoord)) {
//We need to force the re-lighting of the column due to a change
//in the light reaching bellow the block from the sky. To avoid
//modifying core classes to expose this functionality I am just placing then breaking
//a block above this one to force the check
worldObj.setBlock(xCoord, yCoord + i, zCoord, Blocks.stone, 0, 3);
worldObj.setBlockToAir(xCoord, yCoord + i, zCoord);
return true;
}
}
}
return false;
}
@SideOnly(Side.CLIENT)
public static FacadeRenderState getRequiredFacadeRenderState(IConduitBundle bundle, EntityPlayer player) {
if(!bundle.hasFacade()) {
return FacadeRenderState.NONE;
}
if(isFacadeHidden(bundle, player)) {
return FacadeRenderState.WIRE_FRAME;
}
return FacadeRenderState.FULL;
}
public static boolean isSolidFacadeRendered(IConduitBundle bundle, EntityPlayer player) {
return bundle.getFacadeId() != null && !isFacadeHidden(bundle, player);
}
public static boolean isFacadeHidden(IConduitBundle bundle, EntityPlayer player) {
return bundle.getFacadeId() != null && shouldHeldItemHideFacades(player);
}
public static ConduitDisplayMode getDisplayMode(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if(player == null) {
return ConduitDisplayMode.ALL;
}
ItemStack equipped = player.getCurrentEquippedItem();
if(equipped == null) {
return ConduitDisplayMode.ALL;
}
public static <T extends IConduit> void disconectConduits(T con, ForgeDirection connDir) {
con.conduitConnectionRemoved(connDir);
BlockCoord loc = con.getLocation().getLocation(connDir);
IConduit neighbour = ConduitUtil
.getConduit(con.getBundle().getEntity().getWorldObj(), loc.x, loc.y, loc.z, con.getBaseConduitType());
if (neighbour != null) {
neighbour.conduitConnectionRemoved(connDir.getOpposite());
if (neighbour.getNetwork() != null) {
neighbour.getNetwork().destroyNetwork();
}
}
if (con.getNetwork() != null) { // this should have been destroyed when destroying the neighbours network but
// lets just make
// sure
con.getNetwork().destroyNetwork();
}
con.connectionsChanged();
if (neighbour != null) {
neighbour.connectionsChanged();
ConduitDisplayMode result = ConduitDisplayMode.getDisplayMode(equipped);
if(result == null) {
return ConduitDisplayMode.ALL;
}
return result;
}
public static boolean renderConduit(EntityPlayer player, IConduit con) {
if(player == null || con == null) {
return true;
}
return renderConduit(player, con.getBaseConduitType());
}
public static boolean renderConduit(EntityPlayer player, Class<? extends IConduit> conduitType) {
if(player == null || conduitType == null) {
return true;
}
ConduitDisplayMode mode = getDisplayMode(player);
return mode.renderConduit(conduitType);
}
public static boolean shouldHeldItemHideFacades(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if(player == null) {
return false;
}
ItemStack held = player.getCurrentEquippedItem();
if(held != null && held.getItem() instanceof IHideFacades) {
return ((IHideFacades) held.getItem()).shouldHideFacades(held, player);
}
return ToolUtil.isToolEquipped(player);
}
public static boolean isConduitEquipped(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if(player == null) {
return false;
}
ItemStack equipped = player.getCurrentEquippedItem();
if(equipped == null) {
return false;
}
return equipped.getItem() instanceof IConduitItem;
}
public static boolean isProbeEquipped(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if(player == null) {
return false;
}
ItemStack equipped = player.getCurrentEquippedItem();
if(equipped == null) {
return false;
}
return equipped.getItem() == EnderIO.itemConduitProbe;
}
public static <T extends IConduit> T getConduit(World world, int x, int y, int z, Class<T> type) {
if(world == null || !world.blockExists(x, y, z)) {
return null;
}
TileEntity te = world.getTileEntity(x, y, z);
if(te instanceof IConduitBundle) {
IConduitBundle con = (IConduitBundle) te;
return con.getConduit(type);
}
return null;
}
public static <T extends IConduit> T getConduit(World world, TileEntity te, ForgeDirection dir, Class<T> type) {
return ConduitUtil.getConduit(world, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, type);
}
public static <T extends IConduit> Collection<T> getConnectedConduits(World world, int x, int y, int z, Class<T> type) {
TileEntity te = world.getTileEntity(x, y, z);
if(!(te instanceof IConduitBundle)) {
return Collections.emptyList();
}
List<T> result = new ArrayList<T>();
IConduitBundle root = (IConduitBundle) te;
T con = root.getConduit(type);
if(con != null) {
for (ForgeDirection dir : con.getConduitConnections()) {
T connected = getConduit(world, root.getEntity(), dir, type);
if(connected != null) {
result.add(connected);
}
}
}
return result;
}
public static void writeToNBT(IConduit conduit, NBTTagCompound conduitRoot) {
if(conduit == null) {
return;
}
public static <T extends IConduit> boolean joinConduits(T con, ForgeDirection faceHit) {
BlockCoord loc = con.getLocation().getLocation(faceHit);
IConduit neighbour = ConduitUtil
.getConduit(con.getBundle().getEntity().getWorldObj(), loc.x, loc.y, loc.z, con.getBaseConduitType());
if (neighbour != null && con.canConnectToConduit(faceHit, neighbour)
&& neighbour.canConnectToConduit(faceHit.getOpposite(), con)) {
con.conduitConnectionAdded(faceHit);
neighbour.conduitConnectionAdded(faceHit.getOpposite());
if (con.getNetwork() != null) {
con.getNetwork().destroyNetwork();
}
if (neighbour.getNetwork() != null) {
neighbour.getNetwork().destroyNetwork();
}
con.connectionsChanged();
neighbour.connectionsChanged();
return true;
}
return false;
NBTTagCompound conduitBody = new NBTTagCompound();
conduit.writeToNBT(conduitBody);
conduitRoot.setString("conduitType", conduit.getClass().getCanonicalName());
conduitRoot.setTag("conduit", conduitBody);
}
public static IConduit readConduitFromNBT(NBTTagCompound conduitRoot, short nbtVersion) {
String typeName = conduitRoot.getString("conduitType");
NBTTagCompound conduitBody = conduitRoot.getCompoundTag("conduit");
if(typeName == null || conduitBody == null) {
return null;
}
if ((typeName.contains("conduit.oc") && !OCUtil.isOCEnabled()) || (typeName.contains("conduit.me") && !MEUtil.isMEEnabled())
|| (typeName.contains("conduit.gas") && !GasUtil.isGasConduitEnabled())) {
return null;
}
if (nbtVersion == 0 && "crazypants.enderio.conduit.liquid.LiquidConduit".equals(typeName)) {
Log.debug("ConduitUtil.readConduitFromNBT: Converted pre 0.7.3 fluid conduit to advanced fluid conduit.");
typeName = "crazypants.enderio.conduit.liquid.AdvancedLiquidConduit";
} else if ("crazypants.enderio.conduit.liquid.AdvancedEnderLiquidConduit".equals(typeName)) {
Log.debug("ConduitUtil.readConduitFromNBT: Converted advanced ender fluid conduit to crystalline ender fluid conduit.");
typeName = "crazypants.enderio.conduit.liquid.CrystallineEnderLiquidConduit";
}
IConduit result;
try {
result = (IConduit) Class.forName(typeName).newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not create an instance of the conduit with name: " + typeName, e);
}
result.readFromNBT(conduitBody, nbtVersion);
return result;
}
public static boolean isRedstoneControlModeMet(IConduitBundle bundle, RedstoneControlMode mode, DyeColor col) {
if(mode == RedstoneControlMode.IGNORE) {
return true;
} else if(mode == RedstoneControlMode.NEVER) {
return false;
} else if(mode == null) {
return false;
}
public static boolean forceSkylightRecalculation(World worldObj, int xCoord, int yCoord, int zCoord) {
int height = worldObj.getHeightValue(xCoord, zCoord);
if (height <= yCoord) {
for (int i = 1; i < 12; i++) {
if (worldObj.isAirBlock(xCoord, yCoord + i, zCoord)) {
// We need to force the re-lighting of the column due to a change
// in the light reaching bellow the block from the sky. To avoid
// modifying core classes to expose this functionality I am just placing then breaking
// a block above this one to force the check
worldObj.setBlock(xCoord, yCoord + i, zCoord, Blocks.stone, 0, 3);
worldObj.setBlockToAir(xCoord, yCoord + i, zCoord);
return true;
}
}
}
return false;
int signalStrength = getInternalSignalForColor(bundle, col);
if(signalStrength < 15 && DyeColor.RED == col && bundle != null && bundle.getEntity() != null) {
TileEntity te = bundle.getEntity();
signalStrength = Math.max(signalStrength, te.getWorldObj().getStrongestIndirectPower(te.xCoord, te.yCoord, te.zCoord));
}
return RedstoneControlMode.isConditionMet(mode, signalStrength);
}
@SideOnly(Side.CLIENT)
public static FacadeRenderState getRequiredFacadeRenderState(IConduitBundle bundle, EntityPlayer player) {
if (!bundle.hasFacade()) {
return FacadeRenderState.NONE;
}
if (isFacadeHidden(bundle, player)) {
return FacadeRenderState.WIRE_FRAME;
}
return FacadeRenderState.FULL;
public static int getInternalSignalForColor(IConduitBundle bundle, DyeColor col) {
int signalStrength = 0;
if(bundle == null) {
return 0;
}
public static boolean isSolidFacadeRendered(IConduitBundle bundle, EntityPlayer player) {
return bundle.getFacadeId() != null && !isFacadeHidden(bundle, player);
IRedstoneConduit rsCon = bundle.getConduit(IRedstoneConduit.class);
if(rsCon != null) {
Set<Signal> signals = rsCon.getNetworkOutputs(ForgeDirection.UNKNOWN);
for (Signal sig : signals) {
if(sig.color == col) {
if(sig.strength > signalStrength) {
signalStrength = sig.strength;
}
}
}
}
return signalStrength;
}
public static boolean isFacadeHidden(IConduitBundle bundle, EntityPlayer player) {
return bundle != null && bundle.getFacadeId() != null && shouldHeldItemHideFacades(player);
public static boolean isFluidValid(FluidStack fluidStack) {
if(fluidStack != null) {
String name = FluidRegistry.getFluidName(fluidStack);
if(name != null && !name.trim().isEmpty()) {
return true;
}
}
public static ConduitDisplayMode getDisplayMode(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if (player == null) {
return ConduitDisplayMode.ALL;
}
ItemStack equipped = player.getCurrentEquippedItem();
if (equipped == null) {
return ConduitDisplayMode.ALL;
}
ConduitDisplayMode result = ConduitDisplayMode.getDisplayMode(equipped);
if (result == null) {
return ConduitDisplayMode.ALL;
}
return result;
return false;
}
public static void openConduitGui(World world, int x, int y, int z, EntityPlayer player) {
TileEntity te = world.getTileEntity(x, y, z);
if(! (te instanceof TileConduitBundle) ) {
return;
}
public static boolean renderConduit(EntityPlayer player, IConduit con) {
if (player == null || con == null) {
return true;
}
return renderConduit(player, con.getBaseConduitType());
IConduitBundle cb = (IConduitBundle) te;
Set<ForgeDirection> cons = new HashSet<ForgeDirection>();
boolean hasInsulated = false;
for (IConduit con : cb.getConduits()) {
cons.addAll(con.getExternalConnections());
if(con instanceof IInsulatedRedstoneConduit) {
hasInsulated = true;
}
}
public static boolean renderConduit(EntityPlayer player, Class<? extends IConduit> conduitType) {
if (player == null || conduitType == null) {
return true;
}
ConduitDisplayMode mode = getDisplayMode(player);
return mode.renderConduit(conduitType);
if(cons.isEmpty() && !hasInsulated) {
return;
}
public static boolean shouldHeldItemHideFacades(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if (player == null) {
return false;
}
ItemStack held = player.getCurrentEquippedItem();
if (held != null && held.getItem() instanceof IHideFacades) {
return ((IHideFacades) held.getItem()).shouldHideFacades(held, player);
}
return ToolUtil.isToolEquipped(player);
if(cons.size() == 1) {
player.openGui(EnderIO.instance, GuiHandler.GUI_ID_EXTERNAL_CONNECTION_BASE + cons.iterator().next().ordinal(), world, x, y, z);
return;
}
player.openGui(EnderIO.instance, GuiHandler.GUI_ID_EXTERNAL_CONNECTION_SELECTOR, world, x, y, z);
}
public static boolean isConduitEquipped(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if (player == null) {
return false;
}
ItemStack equipped = player.getCurrentEquippedItem();
if (equipped == null) {
return false;
}
return equipped.getItem() instanceof IConduitItem;
public static void playBreakSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(x + 0.5, y + 0.5, z + 0.5, snd.getBreakSound(), (snd.getVolume() + 1.0F) / 2.0F, snd.getPitch() * 0.8F);
} else {
playClientBreakSound(snd);
}
}
public static boolean isProbeEquipped(EntityPlayer player) {
player = player == null ? EnderIO.proxy.getClientPlayer() : player;
if (player == null) {
return false;
}
ItemStack equipped = player.getCurrentEquippedItem();
if (equipped == null) {
return false;
}
return equipped.getItem() == EnderIO.itemConduitProbe;
private static void playClientBreakSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity().playSound(snd.getBreakSound(), (snd.getVolume() + 1.0F) / 2.0F, snd.getPitch() * 0.8F);
}
public static void playHitSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(x + 0.5, y + 0.5, z + 0.5, snd.getStepResourcePath(), (snd.getVolume() + 1.0F) / 2.0F, snd.getPitch() * 0.8F);
} else {
playClientHitSound(snd);
}
}
public static <T extends IConduit> T getConduit(World world, int x, int y, int z, Class<T> type) {
if (world == null || !world.blockExists(x, y, z)) {
return null;
}
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof IConduitBundle) {
IConduitBundle con = (IConduitBundle) te;
return con.getConduit(type);
}
return null;
private static void playClientHitSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity().playSound(snd.getStepResourcePath(), (snd.getVolume() + 1.0F) / 8.0F, snd.getPitch() * 0.5F);
}
public static void playStepSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(x + 0.5, y + 0.5, z + 0.5, snd.getStepResourcePath(), (snd.getVolume() + 1.0F) / 2.0F, snd.getPitch() * 0.8F);
} else {
playClientStepSound(snd);
}
}
public static <T extends IConduit> T getConduit(World world, TileEntity te, ForgeDirection dir, Class<T> type) {
return ConduitUtil
.getConduit(world, te.xCoord + dir.offsetX, te.yCoord + dir.offsetY, te.zCoord + dir.offsetZ, type);
private static void playClientStepSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity().playSound(snd.getStepResourcePath(), (snd.getVolume() + 1.0F) / 8.0F, snd.getPitch());
}
public static void playPlaceSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(x + 0.5, y + 0.5, z + 0.5, snd.func_150496_b(), (snd.getVolume() + 1.0F) / 2.0F, snd.getPitch() * 0.8F);
} else {
playClientPlaceSound(snd);
}
}
public static <T extends IConduit> Collection<T> getConnectedConduits(World world, int x, int y, int z,
Class<T> type) {
TileEntity te = world.blockExists(x, y, z) ? world.getTileEntity(x, y, z) : null;
if (!(te instanceof IConduitBundle)) {
return Collections.emptyList();
}
List<T> result = new ArrayList<>();
IConduitBundle root = (IConduitBundle) te;
T con = root.getConduit(type);
if (con != null) {
for (ForgeDirection dir : con.getConduitConnections()) {
T connected = getConduit(world, root.getEntity(), dir, type);
if (connected != null) {
result.add(connected);
}
}
}
return result;
}
public static void writeToNBT(IConduit conduit, NBTTagCompound conduitRoot) {
if (conduit == null) {
return;
}
NBTTagCompound conduitBody = new NBTTagCompound();
conduit.writeToNBT(conduitBody);
conduitRoot.setString("conduitType", conduit.getClass().getCanonicalName());
conduitRoot.setTag("conduit", conduitBody);
}
public static IConduit readConduitFromNBT(NBTTagCompound conduitRoot, short nbtVersion) {
String typeName = conduitRoot.getString("conduitType");
NBTTagCompound conduitBody = conduitRoot.getCompoundTag("conduit");
if (typeName == null || conduitBody == null) {
return null;
}
if ((typeName.contains("conduit.oc") && !OCUtil.isOCEnabled())
|| (typeName.contains("conduit.me") && !MEUtil.isMEEnabled())
|| (typeName.contains("conduit.gas") && !GasUtil.isGasConduitEnabled())) {
return null;
}
if (nbtVersion == 0 && "crazypants.enderio.conduit.liquid.LiquidConduit".equals(typeName)) {
Log.debug("ConduitUtil.readConduitFromNBT: Converted pre 0.7.3 fluid conduit to advanced fluid conduit.");
typeName = "crazypants.enderio.conduit.liquid.AdvancedLiquidConduit";
} else if ("crazypants.enderio.conduit.liquid.AdvancedEnderLiquidConduit".equals(typeName)) {
Log.debug(
"ConduitUtil.readConduitFromNBT: Converted advanced ender fluid conduit to crystalline ender fluid conduit.");
typeName = "crazypants.enderio.conduit.liquid.CrystallineEnderLiquidConduit";
}
IConduit result;
try {
result = (IConduit) Class.forName(typeName).newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not create an instance of the conduit with name: " + typeName, e);
}
result.readFromNBT(conduitBody, nbtVersion);
return result;
}
public static boolean isRedstoneControlModeMet(IConduitBundle bundle, RedstoneControlMode mode, DyeColor col) {
if (mode == RedstoneControlMode.IGNORE) {
return true;
} else if (mode == RedstoneControlMode.NEVER) {
return false;
} else if (mode == null) {
return false;
}
int signalStrength = getInternalSignalForColor(bundle, col);
if (signalStrength < 15 && bundle != null && bundle.getEntity() != null) {
TileEntity te = bundle.getEntity();
signalStrength = Math
.max(signalStrength, te.getWorldObj().getStrongestIndirectPower(te.xCoord, te.yCoord, te.zCoord));
}
return RedstoneControlMode.isConditionMet(mode, signalStrength);
}
public static int getInternalSignalForColor(IConduitBundle bundle, DyeColor col) {
int signalStrength = 0;
if (bundle == null) {
return 0;
}
IRedstoneConduit rsCon = bundle.getConduit(IRedstoneConduit.class);
if (rsCon != null) {
Set<Signal> signals = rsCon.getNetworkOutputs(ForgeDirection.UNKNOWN);
for (Signal sig : signals) {
if (sig.color == col) {
if (sig.strength > signalStrength) {
signalStrength = sig.strength;
}
}
}
}
return signalStrength;
}
public static boolean isFluidValid(FluidStack fluidStack) {
if (fluidStack != null) {
String name = FluidRegistry.getFluidName(fluidStack);
if (name != null && !name.trim().isEmpty()) {
return true;
}
}
return false;
}
public static void openConduitGui(World world, int x, int y, int z, EntityPlayer player) {
TileEntity te = world.getTileEntity(x, y, z);
if (!(te instanceof TileConduitBundle)) {
return;
}
IConduitBundle cb = (IConduitBundle) te;
Set<ForgeDirection> cons = new HashSet<>();
boolean hasInsulated = false;
for (IConduit con : cb.getConduits()) {
cons.addAll(con.getExternalConnections());
if (con instanceof IInsulatedRedstoneConduit) {
hasInsulated = true;
}
}
if (cons.isEmpty() && !hasInsulated) {
return;
}
if (cons.size() == 1) {
player.openGui(
EnderIO.instance,
GuiHandler.GUI_ID_EXTERNAL_CONNECTION_BASE + cons.iterator().next().ordinal(),
world,
x,
y,
z);
return;
}
player.openGui(EnderIO.instance, GuiHandler.GUI_ID_EXTERNAL_CONNECTION_SELECTOR, world, x, y, z);
}
public static void playBreakSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(
x + 0.5,
y + 0.5,
z + 0.5,
snd.getBreakSound(),
(snd.getVolume() + 1.0F) / 2.0F,
snd.getPitch() * 0.8F);
} else {
playClientBreakSound(snd);
}
}
private static void playClientBreakSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity()
.playSound(snd.getBreakSound(), (snd.getVolume() + 1.0F) / 2.0F, snd.getPitch() * 0.8F);
}
public static void playHitSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(
x + 0.5,
y + 0.5,
z + 0.5,
snd.getStepResourcePath(),
(snd.getVolume() + 1.0F) / 2.0F,
snd.getPitch() * 0.8F);
} else {
playClientHitSound(snd);
}
}
private static void playClientHitSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity()
.playSound(snd.getStepResourcePath(), (snd.getVolume() + 1.0F) / 8.0F, snd.getPitch() * 0.5F);
}
public static void playStepSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(
x + 0.5,
y + 0.5,
z + 0.5,
snd.getStepResourcePath(),
(snd.getVolume() + 1.0F) / 2.0F,
snd.getPitch() * 0.8F);
} else {
playClientStepSound(snd);
}
}
private static void playClientStepSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity()
.playSound(snd.getStepResourcePath(), (snd.getVolume() + 1.0F) / 8.0F, snd.getPitch());
}
public static void playPlaceSound(SoundType snd, World world, int x, int y, int z) {
if (!world.isRemote) {
world.playSoundEffect(
x + 0.5,
y + 0.5,
z + 0.5,
snd.func_150496_b(),
(snd.getVolume() + 1.0F) / 2.0F,
snd.getPitch() * 0.8F);
} else {
playClientPlaceSound(snd);
}
}
private static void playClientPlaceSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity()
.playSound(snd.func_150496_b(), (snd.getVolume() + 1.0F) / 8.0F, snd.getPitch());
}
private static void playClientPlaceSound(SoundType snd) {
FMLClientHandler.instance().getClientPlayerEntity().playSound(snd.func_150496_b(), (snd.getVolume() + 1.0F) / 8.0F, snd.getPitch());
}
}
@@ -2,54 +2,51 @@ package crazypants.enderio.conduit;
import crazypants.enderio.EnderIO;
public enum ConnectionMode {
IN_OUT("gui.conduit.ioMode.inOut"),
INPUT("gui.conduit.ioMode.input"),
OUTPUT("gui.conduit.ioMode.output"),
DISABLED("gui.conduit.ioMode.disabled"),
NOT_SET("gui.conduit.ioMode.notSet");
IN_OUT("gui.conduit.ioMode.inOut"),
INPUT("gui.conduit.ioMode.input"),
OUTPUT("gui.conduit.ioMode.output"),
DISABLED("gui.conduit.ioMode.disabled"),
NOT_SET("gui.conduit.ioMode.notSet");
/**
* Cached values() array for frequent read-only operations, the array should NOT be mutated.
*/
public static final ConnectionMode[] VALUES = values();
private final String unlocalisedName;
private final String unlocalisedName;
ConnectionMode(String unlocalisedName) {
this.unlocalisedName = unlocalisedName;
ConnectionMode(String unlocalisedName) {
this.unlocalisedName = unlocalisedName;
}
public String getUnlocalisedName() {
return unlocalisedName;
}
public static ConnectionMode getNext(ConnectionMode mode) {
int ord = mode.ordinal() + 1;
if(ord >= ConnectionMode.values().length) {
ord = 0;
}
return ConnectionMode.values()[ord];
}
public String getUnlocalisedName() {
return unlocalisedName;
public static ConnectionMode getPrevious(ConnectionMode mode) {
int ord = mode.ordinal() - 1;
if(ord < 0) {
ord = ConnectionMode.values().length - 1;
}
return ConnectionMode.values()[ord];
}
public static ConnectionMode getNext(ConnectionMode mode) {
int ord = mode.ordinal() + 1;
if (ord >= ConnectionMode.VALUES.length) {
ord = 0;
}
return ConnectionMode.VALUES[ord];
}
public boolean acceptsInput() {
return this == IN_OUT || this == INPUT;
}
public static ConnectionMode getPrevious(ConnectionMode mode) {
public boolean acceptsOutput() {
return this == IN_OUT || this == OUTPUT;
}
int ord = mode.ordinal() - 1;
if (ord < 0) {
ord = ConnectionMode.VALUES.length - 1;
}
return ConnectionMode.VALUES[ord];
}
public boolean acceptsInput() {
return this == IN_OUT || this == INPUT;
}
public boolean acceptsOutput() {
return this == IN_OUT || this == OUTPUT;
}
public String getLocalisedName() {
return EnderIO.lang.localize(unlocalisedName);
}
public String getLocalisedName() {
return EnderIO.lang.localize(unlocalisedName);
}
}
@@ -17,131 +17,130 @@ import com.enderio.core.common.util.BlockCoord;
import crazypants.enderio.conduit.geom.CollidableCache.CacheKey;
import crazypants.enderio.conduit.geom.CollidableComponent;
import crazypants.enderio.conduit.render.ConduitRenderer;
public interface IConduit {
// Base functionality
Class<? extends IConduit> getBaseConduitType();
// Base functionality
Class<? extends IConduit> getBaseConduitType();
ItemStack createItem();
ItemStack createItem();
List<ItemStack> getDrops();
List<ItemStack> getDrops();
int getLightValue();
int getLightValue();
boolean isActive();
boolean isActive();
void setActive(boolean active);
void setActive(boolean active);
void writeToNBT(NBTTagCompound conduitBody);
void writeToNBT(NBTTagCompound conduitBody);
void readFromNBT(NBTTagCompound conduitBody, short nbtVersion);
void readFromNBT(NBTTagCompound conduitBody, short nbtVersion);
// Container
// Container
void setBundle(IConduitBundle tileConduitBundle);
void setBundle(IConduitBundle tileConduitBundle);
IConduitBundle getBundle();
IConduitBundle getBundle();
void onAddedToBundle();
void onAddedToBundle();
void onRemovedFromBundle();
void onRemovedFromBundle();
BlockCoord getLocation();
BlockCoord getLocation();
// Conections
boolean hasConnections();
// Conections
boolean hasConnections();
boolean hasExternalConnections();
boolean hasExternalConnections();
boolean hasConduitConnections();
boolean hasConduitConnections();
// Conduit Connections
// Conduit Connections
boolean canConnectToConduit(ForgeDirection direction, IConduit conduit);
boolean canConnectToConduit(ForgeDirection direction, IConduit conduit);
Set<ForgeDirection> getConduitConnections();
Set<ForgeDirection> getConduitConnections();
boolean containsConduitConnection(ForgeDirection dir);
boolean containsConduitConnection(ForgeDirection dir);
void conduitConnectionAdded(ForgeDirection fromDirection);
void conduitConnectionAdded(ForgeDirection fromDirection);
void conduitConnectionRemoved(ForgeDirection fromDirection);
void conduitConnectionRemoved(ForgeDirection fromDirection);
void connectionsChanged();
void connectionsChanged();
AbstractConduitNetwork<?, ?> getNetwork();
AbstractConduitNetwork<?, ?> getNetwork();
boolean setNetwork(AbstractConduitNetwork<?, ?> network);
boolean setNetwork(AbstractConduitNetwork<?, ?> network);
// External Connections
// External Connections
boolean canConnectToExternal(ForgeDirection direction, boolean ignoreConnectionMode);
boolean canConnectToExternal(ForgeDirection direction, boolean ignoreConnectionMode);
Set<ForgeDirection> getExternalConnections();
Set<ForgeDirection> getExternalConnections();
boolean containsExternalConnection(ForgeDirection dir);
boolean containsExternalConnection(ForgeDirection dir);
void externalConnectionAdded(ForgeDirection fromDirection);
void externalConnectionAdded(ForgeDirection fromDirection);
void externalConnectionRemoved(ForgeDirection fromDirection);
void externalConnectionRemoved(ForgeDirection fromDirection);
boolean isConnectedTo(ForgeDirection dir);
boolean isConnectedTo(ForgeDirection dir);
ConnectionMode getConnectionMode(ForgeDirection dir);
ConnectionMode getConnectionMode(ForgeDirection dir);
void setConnectionMode(ForgeDirection dir, ConnectionMode mode);
void setConnectionMode(ForgeDirection dir, ConnectionMode mode);
boolean hasConnectionMode(ConnectionMode mode);
boolean hasConnectionMode(ConnectionMode mode);
ConnectionMode getNextConnectionMode(ForgeDirection dir);
ConnectionMode getNextConnectionMode(ForgeDirection dir);
ConnectionMode getPreviousConnectionMode(ForgeDirection dir);
ConnectionMode getPreviousConnectionMode(ForgeDirection dir);
// rendering, only needed us default rendering is used
// rendering, only needed us default rendering is used
IIcon getTextureForState(CollidableComponent component);
IIcon getTextureForState(CollidableComponent component);
IIcon getTransmitionTextureForState(CollidableComponent component);
IIcon getTransmitionTextureForState(CollidableComponent component);
float getTransmitionGeometryScale();
float getTransmitionGeometryScale();
float getSelfIlluminationForState(CollidableComponent component);
float getSelfIlluminationForState(CollidableComponent component);
// geometry
// geometry
boolean haveCollidablesChangedSinceLastCall();
boolean haveCollidablesChangedSinceLastCall();
Collection<CollidableComponent> getCollidableComponents();
Collection<CollidableComponent> getCollidableComponents();
Collection<CollidableComponent> createCollidables(CacheKey key);
Collection<CollidableComponent> createCollidables(CacheKey key);
Class<? extends IConduit> getCollidableType();
Class<? extends IConduit> getCollidableType();
// Actions
// Actions
boolean onBlockActivated(EntityPlayer player, RaytraceResult res, List<RaytraceResult> all);
boolean onBlockActivated(EntityPlayer player, RaytraceResult res, List<RaytraceResult> all);
void onChunkUnload(World worldObj);
void onChunkUnload(World worldObj);
void updateEntity(World worldObj);
void updateEntity(World worldObj);
boolean onNeighborBlockChange(Block blockId);
boolean onNeighborChange(IBlockAccess world, int x, int y, int z, int tileX, int tileY, int tileZ);
boolean onNeighborBlockChange(Block blockId);
//For Copy/Paste of connection settings
boolean writeConnectionSettingsToNBT(ForgeDirection dir, NBTTagCompound nbt);
boolean onNeighborChange(IBlockAccess world, int x, int y, int z, int tileX, int tileY, int tileZ);
boolean readConduitSettingsFromNBT(ForgeDirection dir, NBTTagCompound nbt);
public AbstractConduitNetwork<?, ?> createNetworkForType();
// For Copy/Paste of connection settings
boolean writeConnectionSettingsToNBT(ForgeDirection dir, NBTTagCompound nbt);
/**
* Should the texture of the conduit connectors be mirrored around the conduit
* node?
*/
boolean shouldMirrorTexture();
boolean readConduitSettingsFromNBT(ForgeDirection dir, NBTTagCompound nbt);
public AbstractConduitNetwork<?, ?> createNetworkForType();
/**
* Should the texture of the conduit connectors be mirrored around the conduit node?
*/
boolean shouldMirrorTexture();
ConduitRenderer getRenderer();
}
@@ -4,17 +4,22 @@ import java.util.Collection;
import java.util.List;
import java.util.Set;
import li.cil.oc.api.network.Environment;
import li.cil.oc.api.network.SidedEnvironment;
import li.cil.oc.api.network.Node;
import mekanism.api.gas.IGasHandler;
import mods.immibis.microblocks.api.IMicroblockSupporterTile;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.IFluidHandler;
import appeng.api.networking.IGridHost;
import cofh.api.transport.IItemDuct;
import com.enderio.core.common.util.BlockCoord;
import appeng.api.networking.IGridHost;
import cofh.api.transport.IItemDuct;
import cpw.mods.fml.common.Optional.Interface;
import cpw.mods.fml.common.Optional.InterfaceList;
import cpw.mods.fml.relauncher.Side;
@@ -23,101 +28,97 @@ import crazypants.enderio.conduit.facade.ItemConduitFacade.FacadeType;
import crazypants.enderio.conduit.geom.CollidableComponent;
import crazypants.enderio.conduit.geom.Offset;
import crazypants.enderio.power.IInternalPowerHandler;
import li.cil.oc.api.network.Environment;
import li.cil.oc.api.network.SidedEnvironment;
import mekanism.api.gas.IGasHandler;
import mods.immibis.microblocks.api.IMicroblockSupporterTile;
@InterfaceList({ @Interface(iface = "appeng.api.networking.IGridHost", modid = "appliedenergistics2"),
@Interface(iface = "mekanism.api.gas.IGasHandler", modid = "MekanismAPI|gas"),
@Interface(iface = "mods.immibis.microblocks.api.IMicroblockSupporterTile", modid = "ImmibisMicroblocks"),
@Interface(iface = "li.cil.oc.api.network.Environment", modid = "OpenComputersAPI|Network"),
@Interface(iface = "li.cil.oc.api.network.SidedEnvironment", modid = "OpenComputersAPI|Network") })
@InterfaceList({
@Interface(iface = "appeng.api.networking.IGridHost", modid = "appliedenergistics2"),
@Interface(iface = "mekanism.api.gas.IGasHandler", modid = "MekanismAPI|gas"),
@Interface(iface = "mods.immibis.microblocks.api.IMicroblockSupporterTile", modid = "ImmibisMicroblocks"),
@Interface(iface = "li.cil.oc.api.network.Environment", modid = "OpenComputersAPI|Network"),
@Interface(iface = "li.cil.oc.api.network.SidedEnvironment", modid = "OpenComputersAPI|Network")
})
public interface IConduitBundle extends IInternalPowerHandler, IFluidHandler, IItemDuct, IGasHandler, IGridHost,
IMicroblockSupporterTile, Environment, SidedEnvironment {
IMicroblockSupporterTile, Environment, SidedEnvironment {
TileEntity getEntity();
TileEntity getEntity();
@Override
BlockCoord getLocation();
@Override
BlockCoord getLocation();
// conduits
// conduits
boolean hasType(Class<? extends IConduit> type);
boolean hasType(Class<? extends IConduit> type);
<T extends IConduit> T getConduit(Class<T> type);
<T extends IConduit> T getConduit(Class<T> type);
void addConduit(IConduit conduit);
void addConduit(IConduit conduit);
void replaceConduit(IConduit original, IConduit replacement);
void removeConduit(IConduit conduit);
void removeConduit(IConduit conduit);
Collection<IConduit> getConduits();
Collection<IConduit> getConduits();
Offset getOffset(Class<? extends IConduit> type, ForgeDirection dir);
Offset getOffset(Class<? extends IConduit> type, ForgeDirection dir);
// connections
// connections
Set<ForgeDirection> getConnections(Class<? extends IConduit> type);
Set<ForgeDirection> getConnections(Class<? extends IConduit> type);
boolean containsConnection(Class<? extends IConduit> type, ForgeDirection west);
boolean containsConnection(Class<? extends IConduit> type, ForgeDirection west);
Set<ForgeDirection> getAllConnections();
Set<ForgeDirection> getAllConnections();
boolean containsConnection(ForgeDirection dir);
boolean containsConnection(ForgeDirection dir);
//geometry
// geometry
List<CollidableComponent> getCollidableComponents();
List<CollidableComponent> getCollidableComponents();
List<CollidableComponent> getConnectors();
List<CollidableComponent> getConnectors();
// events
// events
void onNeighborBlockChange(Block blockId);
void onNeighborChange(IBlockAccess world, int x, int y, int z, int tileX, int tileY, int tileZ);
void onNeighborBlockChange(Block blockId);
void onBlockRemoved();
void onNeighborChange(IBlockAccess world, int x, int y, int z, int tileX, int tileY, int tileZ);
void dirty();
void onBlockRemoved();
// Facade
void dirty();
enum FacadeRenderState {
NONE,
FULL,
WIRE_FRAME
}
// Facade
@SideOnly(Side.CLIENT)
FacadeRenderState getFacadeRenderedAs();
enum FacadeRenderState {
NONE,
FULL,
WIRE_FRAME
}
@SideOnly(Side.CLIENT)
void setFacadeRenderAs(FacadeRenderState state);
@SideOnly(Side.CLIENT)
FacadeRenderState getFacadeRenderedAs();
int getLightOpacity();
@SideOnly(Side.CLIENT)
void setFacadeRenderAs(FacadeRenderState state);
void setLightOpacity(int opacity);
int getLightOpacity();
boolean hasFacade();
void setLightOpacity(int opacity);
void setFacadeId(Block block);
boolean hasFacade();
void setFacadeId(Block block, boolean triggerUpdate);
void setFacadeId(Block block);
void setFacadeMetadata(int meta);
void setFacadeId(Block block, boolean triggerUpdate);
void setFacadeType(FacadeType type);
void setFacadeMetadata(int meta);
Block getFacadeId();
void setFacadeType(FacadeType type);
int getFacadeMetadata();
Block getFacadeId();
FacadeType getFacadeType();
int getFacadeMetadata();
World getWorld();
FacadeType getFacadeType();
World getWorld();
void setGridNode(Object node);
void setGridNode(Object node);
}
@@ -2,12 +2,12 @@ package crazypants.enderio.conduit;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import crazypants.enderio.api.tool.IHideFacades;
public interface IConduitItem extends IHideFacades {
Class<? extends IConduit> getBaseConduitType();
Class<? extends IConduit> getBaseConduitType();
IConduit createConduit(ItemStack item, EntityPlayer player);
IConduit createConduit(ItemStack item, EntityPlayer player);
}
@@ -8,11 +8,12 @@ import crazypants.enderio.machine.RedstoneControlMode;
public interface IExtractor extends IConduit {
void setExtractionRedstoneMode(RedstoneControlMode mode, ForgeDirection dir);
void setExtractionRedstoneMode(RedstoneControlMode mode, ForgeDirection dir);
RedstoneControlMode getExtractionRedstoneMode(ForgeDirection dir);
RedstoneControlMode getExtractionRedstoneMode(ForgeDirection dir);
void setExtractionSignalColor(ForgeDirection dir, DyeColor col);
void setExtractionSignalColor(ForgeDirection dir, DyeColor col);
DyeColor getExtractionSignalColor(ForgeDirection dir);
DyeColor getExtractionSignalColor(ForgeDirection dir);
}
@@ -2,12 +2,13 @@ package crazypants.enderio.conduit;
public class ItemConduitSubtype {
public final String unlocalisedName;
public final String unlocalisedName;
public final String iconKey;
public final String iconKey;
public ItemConduitSubtype(String unlocalisedName, String iconKey) {
this.unlocalisedName = "enderio." + unlocalisedName;
this.iconKey = iconKey;
}
public ItemConduitSubtype(String unlocalisedName, String iconKey) {
this.unlocalisedName = "enderio." + unlocalisedName;
this.iconKey = iconKey;
}
}
@@ -1,41 +1,40 @@
package crazypants.enderio.conduit;
import mods.immibis.microblocks.api.EnumPosition;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Optional.Method;
import mods.immibis.microblocks.api.EnumPosition;
public class MicroblocksUtil {
private static boolean useCheckPerformed = false;
private static boolean supportMicroblocks = false;
private static boolean useCheckPerformed = false;
private static boolean supportMicroblocks = false;
public static boolean supportMicroblocks() {
if (!useCheckPerformed) {
supportMicroblocks = Loader.isModLoaded("ImmibisMicroblocks");
useCheckPerformed = true;
}
return supportMicroblocks;
public static boolean supportMicroblocks() {
if (!useCheckPerformed) {
supportMicroblocks = Loader.isModLoaded("ImmibisMicroblocks");
useCheckPerformed = true;
}
@Method(modid = "ImmibisMicroblocks")
public static ForgeDirection posToDir(EnumPosition pos) {
switch (pos) {
case FaceNX:
return ForgeDirection.WEST;
case FaceNY:
return ForgeDirection.DOWN;
case FaceNZ:
return ForgeDirection.NORTH;
case FacePX:
return ForgeDirection.EAST;
case FacePY:
return ForgeDirection.UP;
case FacePZ:
return ForgeDirection.SOUTH;
default:
return null;
}
return supportMicroblocks;
}
@Method(modid = "ImmibisMicroblocks")
public static ForgeDirection posToDir(EnumPosition pos) {
switch(pos) {
case FaceNX:
return ForgeDirection.WEST;
case FaceNY:
return ForgeDirection.DOWN;
case FaceNZ:
return ForgeDirection.NORTH;
case FacePX:
return ForgeDirection.EAST;
case FacePY:
return ForgeDirection.UP;
case FacePZ:
return ForgeDirection.SOUTH;
default:
return null;
}
}
}
@@ -7,53 +7,52 @@ import java.util.List;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import crazypants.enderio.conduit.geom.CollidableComponent;
public class RaytraceResult {
public static RaytraceResult getClosestHit(Vec3 origin, Collection<RaytraceResult> candidates) {
double minLengthSquared = Double.POSITIVE_INFINITY;
RaytraceResult closest = null;
public static RaytraceResult getClosestHit(Vec3 origin, Collection<RaytraceResult> candidates) {
double minLengthSquared = Double.POSITIVE_INFINITY;
RaytraceResult closest = null;
for (RaytraceResult candidate : candidates) {
MovingObjectPosition hit = candidate.movingObjectPosition;
if (hit != null) {
double lengthSquared = hit.hitVec.squareDistanceTo(origin);
if (lengthSquared < minLengthSquared) {
minLengthSquared = lengthSquared;
closest = candidate;
}
}
for (RaytraceResult candidate : candidates) {
MovingObjectPosition hit = candidate.movingObjectPosition;
if(hit != null) {
double lengthSquared = hit.hitVec.squareDistanceTo(origin);
if(lengthSquared < minLengthSquared) {
minLengthSquared = lengthSquared;
closest = candidate;
}
return closest;
}
}
return closest;
}
public static void sort(final Vec3 origin, List<RaytraceResult> toSort) {
if (origin == null || toSort == null) {
return;
}
Collections.sort(toSort, new Comparator<>() {
@Override
public int compare(RaytraceResult o1, RaytraceResult o2) {
return Double.compare(o1.getDistanceTo(origin), o2.getDistanceTo(origin));
}
});
public static void sort(final Vec3 origin, List<RaytraceResult> toSort) {
if(origin == null || toSort == null) {
return;
}
Collections.sort(toSort, new Comparator<RaytraceResult>() {
@Override
public int compare(RaytraceResult o1, RaytraceResult o2) {
return Double.compare(o1.getDistanceTo(origin), o2.getDistanceTo(origin));
}
});
}
public final CollidableComponent component;
public final MovingObjectPosition movingObjectPosition;
public final CollidableComponent component;
public final MovingObjectPosition movingObjectPosition;
public RaytraceResult(CollidableComponent component, MovingObjectPosition movingObjectPosition) {
this.component = component;
this.movingObjectPosition = movingObjectPosition;
public RaytraceResult(CollidableComponent component, MovingObjectPosition movingObjectPosition) {
this.component = component;
this.movingObjectPosition = movingObjectPosition;
}
public double getDistanceTo(Vec3 origin) {
if(movingObjectPosition == null || origin == null) {
return Double.MAX_VALUE;
}
return movingObjectPosition.hitVec.squareDistanceTo(origin);
}
public double getDistanceTo(Vec3 origin) {
if (movingObjectPosition == null || origin == null) {
return Double.MAX_VALUE;
}
return movingObjectPosition.hitVec.squareDistanceTo(origin);
}
}
File diff suppressed because it is too large. Load diff
@@ -8,7 +8,6 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.BlockEio;
@@ -16,138 +15,138 @@ import crazypants.enderio.ModObject;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.machine.painter.IPaintedBlock;
public class BlockConduitFacade extends BlockEio implements IPaintedBlock, Cloneable {
public class BlockConduitFacade extends BlockEio implements IPaintedBlock {
public static BlockConduitFacade create() {
BlockConduitFacade result = new BlockConduitFacade();
result.init();
return result;
public static BlockConduitFacade create() {
BlockConduitFacade result = new BlockConduitFacade();
result.init();
return result;
}
private Block blockOverride;
private BlockConduitFacade() {
super(ModObject.blockConduitFacade.unlocalisedName, null, new Material(MapColor.stoneColor));
setStepSound(Block.soundTypeStone);
setCreativeTab(null);
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister IIconRegister) {
blockIcon = IIconRegister.registerIcon("enderio:conduitFacade");
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(IBlockAccess ba, int x, int y, int z, int side) {
TileEntity te = ba.getTileEntity(x, y, z);
if(!(te instanceof IConduitBundle)) {
return blockIcon;
}
IConduitBundle cb = (IConduitBundle) te;
Block block = cb.getFacadeId();
if(block != null) {
int meta = cb.getFacadeMetadata();
return block.getIcon(side, meta);
}
return blockIcon;
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int par1, int par2) {
if(blockOverride != null) {
return blockOverride.getIcon(par1, par2);
}
return blockIcon;
}
@Override
@SideOnly(Side.CLIENT)
public int getBlockColor() {
if(blockOverride != null) {
return blockOverride.getBlockColor();
} else {
return super.getBlockColor();
}
}
@Override
@SideOnly(Side.CLIENT)
public int colorMultiplier(IBlockAccess par1IBlockAccess, int par2, int par3, int par4) {
if(blockOverride != null) {
try { //work around for Issue #589
return blockOverride.colorMultiplier(par1IBlockAccess, par2, par3, par4);
} catch (Exception e) {
}
}
return super.colorMultiplier(par1IBlockAccess, par2, par3, par4);
}
public Block getIconOverrideBlock() {
return blockOverride;
}
@Override
@SideOnly(Side.CLIENT)
public int getRenderColor(int par1) {
if(blockOverride != null) {
return blockOverride.getRenderColor(par1);
} else {
return super.getRenderColor(par1);
}
}
public void setBlockOverride(IConduitBundle cb) {
if(cb == null) {
blockOverride = null;
return;
}
public BlockConduitFacade clone() throws CloneNotSupportedException {
return (BlockConduitFacade) super.clone();
Block block = cb.getFacadeId();
int meta = cb.getFacadeMetadata();
if(block == null || block == this) {
return;
}
blockOverride = block;
}
@Override
public int getDamageValue(World par1World, int x, int y, int z) {
Mimic m = getMimic(par1World, x, y, z);
if(m != null) {
return m.meta;
}
return 0;
}
private Mimic getMimic(IBlockAccess ba, int x, int y, int z) {
TileEntity te = ba.getTileEntity(x, y, z);
if(!(te instanceof IConduitBundle)) {
return null;
}
IConduitBundle cb = (IConduitBundle) te;
Block id = cb.getFacadeId();
int meta = cb.getFacadeMetadata();
if(id == null) {
return null;
}
private Block blockOverride;
return new Mimic(id, meta);
}
private BlockConduitFacade() {
super(ModObject.blockConduitFacade.unlocalisedName, null, new Material(MapColor.stoneColor));
setStepSound(Block.soundTypeStone);
setCreativeTab(null);
class Mimic {
int meta;
Block block;
private Mimic(Block block, int meta) {
this.block = block;
this.meta = meta;
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister IIconRegister) {
blockIcon = IIconRegister.registerIcon("enderio:conduitFacade");
}
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(IBlockAccess ba, int x, int y, int z, int side) {
TileEntity te = ba.getTileEntity(x, y, z);
if (!(te instanceof IConduitBundle)) {
return blockIcon;
}
IConduitBundle cb = (IConduitBundle) te;
Block block = cb.getFacadeId();
if (block != null) {
int meta = cb.getFacadeMetadata();
return block.getIcon(side, meta);
}
return blockIcon;
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int par1, int par2) {
if (blockOverride != null) {
return blockOverride.getIcon(par1, par2);
}
return blockIcon;
}
@Override
@SideOnly(Side.CLIENT)
public int getBlockColor() {
if (blockOverride != null) {
return blockOverride.getBlockColor();
} else {
return super.getBlockColor();
}
}
@Override
@SideOnly(Side.CLIENT)
public int colorMultiplier(IBlockAccess par1IBlockAccess, int par2, int par3, int par4) {
if (blockOverride != null) {
try { // work around for Issue #589
return blockOverride.colorMultiplier(par1IBlockAccess, par2, par3, par4);
} catch (Exception e) {}
}
return super.colorMultiplier(par1IBlockAccess, par2, par3, par4);
}
public Block getIconOverrideBlock() {
return blockOverride;
}
@Override
@SideOnly(Side.CLIENT)
public int getRenderColor(int par1) {
if (blockOverride != null) {
return blockOverride.getRenderColor(par1);
} else {
return super.getRenderColor(par1);
}
}
public void setBlockOverride(IConduitBundle cb) {
if (cb == null) {
blockOverride = null;
return;
}
Block block = cb.getFacadeId();
if (block == null || block == this) {
return;
}
blockOverride = block;
}
@Override
public int getDamageValue(World par1World, int x, int y, int z) {
Mimic m = getMimic(par1World, x, y, z);
if (m != null) {
return m.meta;
}
return 0;
}
private Mimic getMimic(IBlockAccess ba, int x, int y, int z) {
TileEntity te = ba.getTileEntity(x, y, z);
if (!(te instanceof IConduitBundle)) {
return null;
}
IConduitBundle cb = (IConduitBundle) te;
Block id = cb.getFacadeId();
int meta = cb.getFacadeMetadata();
if (id == null) {
return null;
}
return new Mimic(id, meta);
}
static class Mimic {
int meta;
Block block;
private Mimic(Block block, int meta) {
this.block = block;
this.meta = meta;
}
}
}
@@ -15,89 +15,89 @@ import crazypants.enderio.machine.painter.PainterUtil;
public class FacadeRenderer implements IItemRenderer {
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED
|| type == ItemRenderType.INVENTORY
|| type == ItemRenderType.EQUIPPED_FIRST_PERSON;
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED_FIRST_PERSON;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
return true;
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
if(type == ItemRenderType.INVENTORY) {
RenderBlocks renderBlocks = (RenderBlocks) data[0];
renderToInventory(item, renderBlocks);
} else if(type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON) {
renderEquipped(item, (RenderBlocks) data[0]);
} else if(type == ItemRenderType.ENTITY) {
renderEntity(item, (RenderBlocks) data[0]);
} else {
System.out.println("FacadeRenderer.renderItem: Unsupported render type");
}
}
private void renderEntity(ItemStack item, RenderBlocks renderBlocks) {
GL11.glPushMatrix();
GL11.glScalef(0.5f, 0.5f, 0.5f);
renderToInventory(item, renderBlocks);
GL11.glPopMatrix();
}
private void renderEquipped(ItemStack item, RenderBlocks renderBlocks) {
renderToInventory(item, renderBlocks);
}
private void renderToInventory(ItemStack item, RenderBlocks renderBlocks) {
Block block = PainterUtil.getSourceBlock(item);
if(block != null) {
// Render the facade block
RenderUtil.bindBlockTexture();
if(!block.isOpaqueCube()) {
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
if("appeng.block.solids.BlockSkyStone".equals(block.getClass().getName())) {
//Yes, this is a horrible hack, but stumped as to why it is rendered invisible if this isn't done.
renderBlocks.setOverrideBlockTexture(block.getIcon(0, PainterUtil.getSourceBlockMetadata(item)));
renderBlocks.renderBlockAsItem(Blocks.stone, 0, 1.0F);
} else {
renderBlocks.renderBlockAsItem(block, PainterUtil.getSourceBlockMetadata(item), 1.0F);
}
// then the 'overlay' that marks it as a facade
GL11.glDepthFunc(GL11.GL_LEQUAL);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDepthMask(false);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GL11.glPolygonOffset(-1.0f, -1.0f);
RenderUtil.bindItemTexture();
renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getOverlayIcon());
renderBlocks.renderBlockAsItem(Blocks.stone, item.getItemDamage(), 1.0F);
GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
renderBlocks.clearOverrideBlockTexture();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDepthFunc(GL11.GL_LEQUAL);
} else {
renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getIconFromDamage(item.getItemDamage()));
renderBlocks.renderBlockAsItem(Blocks.stone, 0, 1.0F);
renderBlocks.clearOverrideBlockTexture();
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
return true;
}
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
if (type == ItemRenderType.INVENTORY) {
RenderBlocks renderBlocks = (RenderBlocks) data[0];
renderToInventory(item, renderBlocks);
} else if (type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON) {
renderEquipped(item, (RenderBlocks) data[0]);
} else if (type == ItemRenderType.ENTITY) {
renderEntity(item, (RenderBlocks) data[0]);
} else {
System.out.println("FacadeRenderer.renderItem: Unsupported render type");
}
}
private void renderEntity(ItemStack item, RenderBlocks renderBlocks) {
GL11.glPushMatrix();
GL11.glScalef(0.5f, 0.5f, 0.5f);
renderToInventory(item, renderBlocks);
GL11.glPopMatrix();
}
private void renderEquipped(ItemStack item, RenderBlocks renderBlocks) {
renderToInventory(item, renderBlocks);
}
private void renderToInventory(ItemStack item, RenderBlocks renderBlocks) {
Block block = PainterUtil.getSourceBlock(item);
if (block != null) {
// Render the facade block
RenderUtil.bindBlockTexture();
if (!block.isOpaqueCube()) {
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
if ("appeng.block.solids.BlockSkyStone".equals(block.getClass().getName())) {
// Yes, this is a horrible hack, but stumped as to why it is rendered invisible if this isn't done.
renderBlocks.setOverrideBlockTexture(block.getIcon(0, PainterUtil.getSourceBlockMetadata(item)));
renderBlocks.renderBlockAsItem(Blocks.stone, 0, 1.0F);
} else {
renderBlocks.renderBlockAsItem(block, PainterUtil.getSourceBlockMetadata(item), 1.0F);
}
// then the 'overlay' that marks it as a facade
GL11.glDepthFunc(GL11.GL_LEQUAL);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDepthMask(false);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GL11.glPolygonOffset(-1.0f, -1.0f);
RenderUtil.bindItemTexture();
renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getOverlayIcon());
renderBlocks.renderBlockAsItem(Blocks.stone, item.getItemDamage(), 1.0F);
GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
renderBlocks.clearOverrideBlockTexture();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDepthFunc(GL11.GL_LEQUAL);
} else {
renderBlocks.setOverrideBlockTexture(EnderIO.itemConduitFacade.getIconFromDamage(item.getItemDamage()));
renderBlocks.renderBlockAsItem(Blocks.stone, 0, 1.0F);
renderBlocks.clearOverrideBlockTexture();
}
}
}
@@ -32,220 +32,216 @@ import crazypants.enderio.machine.painter.BasicPainterTemplate;
import crazypants.enderio.machine.painter.IPaintedBlock;
import crazypants.enderio.machine.painter.PaintSourceValidator;
import crazypants.enderio.machine.painter.PainterUtil;
import crazypants.util.ForgeDirections;
public class ItemConduitFacade extends Item implements IAdvancedTooltipProvider, IResourceTooltipProvider {
public enum FacadeType {
public static enum FacadeType {
BASIC,
HARDENED;
BASIC,
HARDENED;
public String getUnlocName(Item me) {
return this == BASIC ? me.getUnlocalizedName() : me.getUnlocalizedName() + ".hardened";
}
}
public static final FacadeType[] VALUES = values();
private IIcon[] icons;
public String getUnlocName(Item me) {
return this == BASIC ? me.getUnlocalizedName() : me.getUnlocalizedName() + ".hardened";
public static ItemConduitFacade create() {
ItemConduitFacade result = new ItemConduitFacade();
result.init();
return result;
}
protected IIcon overlayIcon;
protected ItemConduitFacade() {
setCreativeTab(EnderIOTab.tabEnderIO);
setMaxStackSize(64);
setHasSubtypes(true);
}
protected void init() {
GameRegistry.registerItem(this, ModObject.itemConduitFacade.unlocalisedName);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs p_150895_2_, List list) {
for (FacadeType t : FacadeType.values()) {
list.add(new ItemStack(item, 1, t.ordinal()));
}
}
@Override
public String getUnlocalizedName(ItemStack stack) {
return FacadeType.values()[stack.getItemDamage()].getUnlocName(this);
}
@Override
public String getUnlocalizedName() {
return "item.enderio." + ModObject.itemConduitFacade.name();
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister IIconRegister) {
icons = new IIcon[FacadeType.values().length];
icons[0] = itemIcon = IIconRegister.registerIcon("enderio:conduitFacade");
icons[1] = IIconRegister.registerIcon("enderio:conduitFacadeHardened");
overlayIcon = IIconRegister.registerIcon("enderio:conduitFacadeOverlay");
}
public IIcon getOverlayIcon() {
return overlayIcon;
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int damage) {
return icons[damage % icons.length];
}
@Override
public IIcon getIcon(ItemStack stack, int renderPass, EntityPlayer player, ItemStack usingItem, int useRemaining) {
return getIconFromDamage(stack.getItemDamage());
}
@Override
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float par8,
float par9, float par10) {
if(world.isRemote) {
return true;
}
ForgeDirection dir = ForgeDirection.values()[side];
int placeX = x + dir.offsetX;
int placeY = y + dir.offsetY;
int placeZ = z + dir.offsetZ;
if (player.canPlayerEdit(placeX, placeY, placeZ, side, itemStack) && PainterUtil.getSourceBlock(itemStack) != null) {
if (world.isAirBlock(placeX, placeY, placeZ)) {
world.setBlock(placeX, placeY, placeZ, EnderIO.blockConduitBundle);
IConduitBundle bundle = (IConduitBundle) world.getTileEntity(placeX, placeY, placeZ);
Block facadeID = PainterUtil.getSourceBlock(itemStack);
int facadeMeta = PainterUtil.getSourceBlockMetadata(itemStack);
facadeMeta = PainterUtil.adjustFacadeMetadata(facadeID, facadeMeta, side);
bundle.setFacadeId(facadeID);
bundle.setFacadeMetadata(facadeMeta);
bundle.setFacadeType(FacadeType.values()[itemStack.getItemDamage()]);
ConduitUtil.playPlaceSound(facadeID.stepSound, world, x, y, z);
if (!player.capabilities.isCreativeMode) {
itemStack.stackSize--;
}
}
private IIcon[] icons;
public static ItemConduitFacade create() {
ItemConduitFacade result = new ItemConduitFacade();
result.init();
return result;
}
protected IIcon overlayIcon;
protected ItemConduitFacade() {
setCreativeTab(EnderIOTab.tabEnderIO);
setMaxStackSize(64);
setHasSubtypes(true);
}
protected void init() {
GameRegistry.registerItem(this, ModObject.itemConduitFacade.unlocalisedName);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs p_150895_2_, List<ItemStack> list) {
for (FacadeType t : FacadeType.VALUES) {
list.add(new ItemStack(item, 1, t.ordinal()));
}
}
@Override
public String getUnlocalizedName(ItemStack stack) {
return FacadeType.VALUES[stack.getItemDamage()].getUnlocName(this);
}
@Override
public String getUnlocalizedName() {
return "item.enderio." + ModObject.itemConduitFacade.name();
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister IIconRegister) {
icons = new IIcon[FacadeType.VALUES.length];
icons[0] = itemIcon = IIconRegister.registerIcon("enderio:conduitFacade");
icons[1] = IIconRegister.registerIcon("enderio:conduitFacadeHardened");
overlayIcon = IIconRegister.registerIcon("enderio:conduitFacadeOverlay");
}
public IIcon getOverlayIcon() {
return overlayIcon;
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIconFromDamage(int damage) {
return icons[damage % icons.length];
}
@Override
public IIcon getIcon(ItemStack stack, int renderPass, EntityPlayer player, ItemStack usingItem, int useRemaining) {
return getIconFromDamage(stack.getItemDamage());
}
@Override
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side,
float par8, float par9, float par10) {
if (world.isRemote) {
return true;
}
ForgeDirection dir = ForgeDirections.DIRECTIONS[side];
int placeX = x + dir.offsetX;
int placeY = y + dir.offsetY;
int placeZ = z + dir.offsetZ;
if (player.canPlayerEdit(placeX, placeY, placeZ, side, itemStack)
&& PainterUtil.getSourceBlock(itemStack) != null) {
if (world.isAirBlock(placeX, placeY, placeZ)) {
world.setBlock(placeX, placeY, placeZ, EnderIO.blockConduitBundle);
IConduitBundle bundle = (IConduitBundle) world.getTileEntity(placeX, placeY, placeZ);
Block facadeID = PainterUtil.getSourceBlock(itemStack);
int facadeMeta = PainterUtil.getSourceBlockMetadata(itemStack);
facadeMeta = PainterUtil.adjustFacadeMetadata(facadeID, facadeMeta, side);
bundle.setFacadeId(facadeID);
bundle.setFacadeMetadata(facadeMeta);
bundle.setFacadeType(FacadeType.VALUES[itemStack.getItemDamage()]);
ConduitUtil.playPlaceSound(facadeID.stepSound, world, x, y, z);
if (!player.capabilities.isCreativeMode) {
itemStack.stackSize--;
}
return true;
} else {
Block block = world.getBlock(placeX, placeY, placeZ);
if (block == EnderIO.blockConduitBundle) {
((BlockConduitBundle) block).handleFacadeClick(
world,
placeX,
placeY,
placeZ,
player,
dir.getOpposite().ordinal(),
(IConduitBundle) world.getTileEntity(placeX, placeY, placeZ),
itemStack);
}
}
}
return false;
}
@Override
@SideOnly(Side.CLIENT)
public boolean isFull3D() {
return true;
} else {
Block block = world.getBlock(placeX, placeY, placeZ);
if (block == EnderIO.blockConduitBundle) {
((BlockConduitBundle) block).handleFacadeClick(world, placeX, placeY, placeZ, player, dir.getOpposite().ordinal(),
(IConduitBundle) world.getTileEntity(placeX, placeY, placeZ), itemStack);
}
}
}
public ItemStack createItemStackForSourceBlock(Block id, int itemDamage) {
if (id == null) {
id = EnderIO.blockConduitFacade;
}
ItemStack result = new ItemStack(id, 1, 0);
PainterUtil.setSourceBlock(result, id, itemDamage);
return result;
return false;
}
@Override
@SideOnly(Side.CLIENT)
public boolean isFull3D() {
return true;
}
public ItemStack createItemStackForSourceBlock(Block id, int itemDamage) {
if(id == null) {
id = EnderIO.blockConduitFacade;
}
ItemStack result = new ItemStack(id, 1, 0);
PainterUtil.setSourceBlock(result, id, itemDamage);
return result;
}
@SuppressWarnings("rawtypes")
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack item, EntityPlayer par2EntityPlayer, List list, boolean par4) {
super.addInformation(item, par2EntityPlayer, list, par4);
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return getUnlocalizedName();
}
@SuppressWarnings("rawtypes")
@Override
@SideOnly(Side.CLIENT)
public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@SideOnly(Side.CLIENT)
public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
if(PainterUtil.getSourceBlock(itemstack) == null) {
list.add(EnderIO.lang.localize("item.itemConduitFacade.tooltip.notpainted"));
} else {
list.add(PainterUtil.getTooltTipText(itemstack));
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
@SideOnly(Side.CLIENT)
public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
SpecialTooltipHandler.addDetailedTooltipFromResources(list, itemstack);
if(itemstack.getItemDamage() == FacadeType.HARDENED.ordinal()) {
list.add("");
list.add(EnderIO.lang.localizeExact(getUnlocalizedName(itemstack) + ".tooltip"));
}
}
public final class FacadePainterRecipe extends BasicPainterTemplate {
@Override
public boolean isValidPaintSource(ItemStack paintSource) {
if(paintSource == null) {
return false;
}
if (paintSource.getItem() == ItemConduitFacade.this) {
return true;
}
Block block = Util.getBlockFromItemId(paintSource);
if(block == null || block instanceof IPaintedBlock) {
return false;
}
if(PaintSourceValidator.instance.isBlacklisted(paintSource)) {
return false;
}
if(PaintSourceValidator.instance.isWhitelisted(paintSource)) {
return true;
}
if (!Config.allowTileEntitiesAsPaintSource && block.hasTileEntity(paintSource.getItemDamage())) {
return false;
}
if(block == EnderIO.blockFusedQuartz && paintSource.getItemDamage() < 2) {
return true;
}
return block.getRenderType() == 0 || block.isOpaqueCube() || block.isNormalCube();
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack item, EntityPlayer par2EntityPlayer, List<String> list, boolean par4) {
super.addInformation(item, par2EntityPlayer, list, par4);
public boolean isValidTarget(ItemStack target) {
return target != null && target.getItem() == ItemConduitFacade.this;
}
@Override
public String getUnlocalizedNameForTooltip(ItemStack itemStack) {
return getUnlocalizedName();
public ResultStack[] getCompletedResult(float chance, MachineRecipeInput... inputs) {
ResultStack[] res = super.getCompletedResult(chance, inputs);
return res;
}
}
@Override
@SideOnly(Side.CLIENT)
public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {}
@Override
@SideOnly(Side.CLIENT)
public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {
if (PainterUtil.getSourceBlock(itemstack) == null) {
list.add(EnderIO.lang.localize("item.itemConduitFacade.tooltip.notpainted"));
} else {
list.add(PainterUtil.getTooltTipText(itemstack));
}
}
@Override
@SideOnly(Side.CLIENT)
public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {
SpecialTooltipHandler.addDetailedTooltipFromResources(list, itemstack);
if (itemstack.getItemDamage() == FacadeType.HARDENED.ordinal()) {
list.add("");
list.add(EnderIO.lang.localizeExact(getUnlocalizedName(itemstack) + ".tooltip"));
}
}
public final class FacadePainterRecipe extends BasicPainterTemplate {
@Override
public boolean isValidPaintSource(ItemStack paintSource) {
if (paintSource == null) {
return false;
}
if (paintSource.getItem() == ItemConduitFacade.this) {
return true;
}
Block block = Util.getBlockFromItemId(paintSource);
if (block == null || block instanceof IPaintedBlock) {
return false;
}
if (PaintSourceValidator.instance.isBlacklisted(paintSource)) {
return false;
}
if (PaintSourceValidator.instance.isWhitelisted(paintSource)) {
return true;
}
if (!Config.allowTileEntitiesAsPaintSource && block.hasTileEntity(paintSource.getItemDamage())) {
return false;
}
if (block == EnderIO.blockFusedQuartz && paintSource.getItemDamage() < 2) {
return true;
}
return block.getRenderType() == 0 || block.isOpaqueCube() || block.isNormalCube();
}
@Override
public boolean isValidTarget(ItemStack target) {
return target != null && target.getItem() == ItemConduitFacade.this;
}
@Override
public ResultStack[] getCompletedResult(float chance, MachineRecipeInput... inputs) {
ResultStack[] res = super.getCompletedResult(chance, inputs);
return res;
}
}
}
@@ -5,6 +5,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import mekanism.api.gas.IGasHandler;
import net.minecraft.block.Block;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
@@ -21,180 +22,181 @@ import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.machine.RedstoneControlMode;
import crazypants.enderio.machine.reservoir.TileReservoir;
import mekanism.api.gas.IGasHandler;
public abstract class AbstractGasConduit extends AbstractConduit implements IGasConduit {
protected final EnumMap<ForgeDirection, RedstoneControlMode> extractionModes = new EnumMap<>(ForgeDirection.class);
protected final EnumMap<ForgeDirection, DyeColor> extractionColors = new EnumMap<>(ForgeDirection.class);
protected final EnumMap<ForgeDirection, RedstoneControlMode> extractionModes = new EnumMap<ForgeDirection, RedstoneControlMode>(ForgeDirection.class);
protected final EnumMap<ForgeDirection, DyeColor> extractionColors = new EnumMap<ForgeDirection, DyeColor>(ForgeDirection.class);
protected final Map<ForgeDirection, Integer> externalRedstoneSignals = new HashMap<>();
protected boolean redstoneStateDirty = true;
protected final Map<ForgeDirection, Integer> externalRedstoneSignals = new HashMap<ForgeDirection, Integer>();
protected boolean redstoneStateDirty = true;
@Method(modid = GasUtil.API_NAME)
public IGasHandler getExternalHandler(ForgeDirection direction) {
IGasHandler con = GasUtil.getExternalGasHandler(getBundle().getWorld(), getLocation().getLocation(direction));
return (con != null && !(con instanceof IConduitBundle)) ? con : null;
@Method(modid = GasUtil.API_NAME)
public IGasHandler getExternalHandler(ForgeDirection direction) {
IGasHandler con = GasUtil.getExternalGasHandler(getBundle().getWorld(), getLocation().getLocation(direction));
return (con != null && !(con instanceof IConduitBundle)) ? con : null;
}
@Method(modid = GasUtil.API_NAME)
public IGasHandler getTankContainer(BlockCoord bc) {
return GasUtil.getGasHandler(getBundle().getWorld(), bc);
}
@Override
public boolean canConnectToExternal(ForgeDirection direction, boolean ignoreDisabled) {
IGasHandler h = getExternalHandler(direction);
if(h == null) {
return false;
}
return true;
}
@Override
public Class<? extends IConduit> getBaseConduitType() {
return IGasConduit.class;
}
@Override
public boolean onNeighborBlockChange(Block blockId) {
redstoneStateDirty = true;
return super.onNeighborBlockChange(blockId);
}
@Override
public void setExtractionRedstoneMode(RedstoneControlMode mode, ForgeDirection dir) {
extractionModes.put(dir, mode);
redstoneStateDirty = true;
}
@Override
public RedstoneControlMode getExtractionRedstoneMode(ForgeDirection dir) {
RedstoneControlMode res = extractionModes.get(dir);
if(res == null) {
res = RedstoneControlMode.ON;
}
return res;
}
@Override
public void setExtractionSignalColor(ForgeDirection dir, DyeColor col) {
extractionColors.put(dir, col);
}
@Override
public DyeColor getExtractionSignalColor(ForgeDirection dir) {
DyeColor result = extractionColors.get(dir);
if(result == null) {
return DyeColor.RED;
}
return result;
}
@Override
public boolean canOutputToDir(ForgeDirection dir) {
if(isExtractingFromDir(dir) || getConnectionMode(dir) == ConnectionMode.DISABLED) {
return false;
}
if(conduitConnections.contains(dir)) {
return true;
}
if(!externalConnections.contains(dir)) {
return false;
}
IGasHandler ext = getExternalHandler(dir);
if(ext instanceof TileReservoir) { // dont push to an auto ejecting
// resevoir or we loop
TileReservoir tr = (TileReservoir) ext;
return !tr.isMultiblock() || !tr.isAutoEject();
}
return true;
}
protected boolean autoExtractForDir(ForgeDirection dir) {
if(!isExtractingFromDir(dir)) {
return false;
}
RedstoneControlMode mode = getExtractionRedstoneMode(dir);
if(mode == RedstoneControlMode.IGNORE) {
return true;
}
if(mode == RedstoneControlMode.NEVER) {
return false;
}
if(redstoneStateDirty) {
externalRedstoneSignals.clear();
redstoneStateDirty = false;
}
@Method(modid = GasUtil.API_NAME)
public IGasHandler getTankContainer(BlockCoord bc) {
return GasUtil.getGasHandler(getBundle().getWorld(), bc);
DyeColor col = getExtractionSignalColor(dir);
int signal = ConduitUtil.getInternalSignalForColor(getBundle(), col);
if(RedstoneControlMode.isConditionMet(mode, signal) && mode != RedstoneControlMode.OFF) {
return true;
}
@Override
public boolean canConnectToExternal(ForgeDirection direction, boolean ignoreDisabled) {
IGasHandler h = getExternalHandler(direction);
if (h == null) {
return false;
}
return true;
return isConditionMetByExternalSignal(dir, mode, col);
}
private boolean isConditionMetByExternalSignal(ForgeDirection dir, RedstoneControlMode mode, DyeColor col) {
int externalSignal = 0;
if(col == DyeColor.RED) {
Integer val = externalRedstoneSignals.get(dir);
if(val == null) {
TileEntity te = getBundle().getEntity();
externalSignal = te.getWorldObj().getStrongestIndirectPower(te.xCoord, te.yCoord, te.zCoord);
externalRedstoneSignals.put(dir, externalSignal);
} else {
externalSignal = val;
}
}
@Override
public Class<? extends IConduit> getBaseConduitType() {
return IGasConduit.class;
return RedstoneControlMode.isConditionMet(mode, externalSignal);
}
@Override
public boolean isExtractingFromDir(ForgeDirection dir) {
return getConnectionMode(dir) == ConnectionMode.INPUT;
}
@Override
public void writeToNBT(NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
for (Entry<ForgeDirection, RedstoneControlMode> entry : extractionModes.entrySet()) {
if(entry.getValue() != null) {
short ord = (short) entry.getValue().ordinal();
nbtRoot.setShort("extRM." + entry.getKey().name(), ord);
}
}
@Override
public boolean onNeighborBlockChange(Block blockId) {
redstoneStateDirty = true;
return super.onNeighborBlockChange(blockId);
for (Entry<ForgeDirection, DyeColor> entry : extractionColors.entrySet()) {
if(entry.getValue() != null) {
short ord = (short) entry.getValue().ordinal();
nbtRoot.setShort("extSC." + entry.getKey().name(), ord);
}
}
@Override
public void setExtractionRedstoneMode(RedstoneControlMode mode, ForgeDirection dir) {
extractionModes.put(dir, mode);
redstoneStateDirty = true;
}
@Override
public void readFromNBT(NBTTagCompound nbtRoot, short nbtVersion) {
super.readFromNBT(nbtRoot, nbtVersion);
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
String key = "extRM." + dir.name();
if(nbtRoot.hasKey(key)) {
short ord = nbtRoot.getShort(key);
if(ord >= 0 && ord < RedstoneControlMode.values().length) {
extractionModes.put(dir, RedstoneControlMode.values()[ord]);
}
}
key = "extSC." + dir.name();
if(nbtRoot.hasKey(key)) {
short ord = nbtRoot.getShort(key);
if(ord >= 0 && ord < DyeColor.values().length) {
extractionColors.put(dir, DyeColor.values()[ord]);
}
}
}
}
@Override
public RedstoneControlMode getExtractionRedstoneMode(ForgeDirection dir) {
RedstoneControlMode res = extractionModes.get(dir);
if (res == null) {
res = RedstoneControlMode.ON;
}
return res;
}
@Override
public void setExtractionSignalColor(ForgeDirection dir, DyeColor col) {
extractionColors.put(dir, col);
}
@Override
public DyeColor getExtractionSignalColor(ForgeDirection dir) {
DyeColor result = extractionColors.get(dir);
if (result == null) {
return DyeColor.RED;
}
return result;
}
@Override
public boolean canOutputToDir(ForgeDirection dir) {
if (isExtractingFromDir(dir) || getConnectionMode(dir) == ConnectionMode.DISABLED) {
return false;
}
if (conduitConnections.contains(dir)) {
return true;
}
if (!externalConnections.contains(dir)) {
return false;
}
IGasHandler ext = getExternalHandler(dir);
if (ext instanceof TileReservoir) { // dont push to an auto ejecting
// resevoir or we loop
TileReservoir tr = (TileReservoir) ext;
return !tr.isMultiblock() || !tr.isAutoEject();
}
return true;
}
protected boolean autoExtractForDir(ForgeDirection dir) {
if (!isExtractingFromDir(dir)) {
return false;
}
RedstoneControlMode mode = getExtractionRedstoneMode(dir);
if (mode == RedstoneControlMode.IGNORE) {
return true;
}
if (mode == RedstoneControlMode.NEVER) {
return false;
}
if (redstoneStateDirty) {
externalRedstoneSignals.clear();
redstoneStateDirty = false;
}
DyeColor col = getExtractionSignalColor(dir);
int signal = ConduitUtil.getInternalSignalForColor(getBundle(), col);
if (RedstoneControlMode.isConditionMet(mode, signal) && mode != RedstoneControlMode.OFF) {
return true;
}
return isConditionMetByExternalSignal(dir, mode, col);
}
private boolean isConditionMetByExternalSignal(ForgeDirection dir, RedstoneControlMode mode, DyeColor col) {
int externalSignal = 0;
if (col == DyeColor.RED) {
Integer val = externalRedstoneSignals.get(dir);
if (val == null) {
TileEntity te = getBundle().getEntity();
externalSignal = te.getWorldObj().getStrongestIndirectPower(te.xCoord, te.yCoord, te.zCoord);
externalRedstoneSignals.put(dir, externalSignal);
} else {
externalSignal = val;
}
}
return RedstoneControlMode.isConditionMet(mode, externalSignal);
}
@Override
public boolean isExtractingFromDir(ForgeDirection dir) {
return getConnectionMode(dir) == ConnectionMode.INPUT;
}
@Override
public void writeToNBT(NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
for (Entry<ForgeDirection, RedstoneControlMode> entry : extractionModes.entrySet()) {
if (entry.getValue() != null) {
short ord = (short) entry.getValue().ordinal();
nbtRoot.setShort("extRM." + entry.getKey().name(), ord);
}
}
for (Entry<ForgeDirection, DyeColor> entry : extractionColors.entrySet()) {
if (entry.getValue() != null) {
short ord = (short) entry.getValue().ordinal();
nbtRoot.setShort("extSC." + entry.getKey().name(), ord);
}
}
}
@Override
public void readFromNBT(NBTTagCompound nbtRoot, short nbtVersion) {
super.readFromNBT(nbtRoot, nbtVersion);
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
String key = "extRM." + dir.name();
if (nbtRoot.hasKey(key)) {
short ord = nbtRoot.getShort(key);
if (ord >= 0 && ord < RedstoneControlMode.VALUES.length) {
extractionModes.put(dir, RedstoneControlMode.VALUES[ord]);
}
}
key = "extSC." + dir.name();
if (nbtRoot.hasKey(key)) {
short ord = nbtRoot.getShort(key);
if (ord >= 0 && ord < DyeColor.VALUES.length) {
extractionColors.put(dir, DyeColor.VALUES[ord]);
}
}
}
}
}
@@ -2,6 +2,8 @@ package crazypants.enderio.conduit.gas;
import java.util.List;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.ForgeDirection;
@@ -14,154 +16,151 @@ import crazypants.enderio.conduit.ConduitUtil;
import crazypants.enderio.conduit.ConnectionMode;
import crazypants.enderio.conduit.RaytraceResult;
import crazypants.enderio.tool.ToolUtil;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
public abstract class AbstractGasTankConduit extends AbstractGasConduit {
protected ConduitGasTank tank = new ConduitGasTank(0);
protected boolean stateDirty = false;
protected long lastEmptyTick = 0;
protected int numEmptyEvents = 0;
protected ConduitGasTank tank = new ConduitGasTank(0);
protected boolean stateDirty = false;
protected long lastEmptyTick = 0;
protected int numEmptyEvents = 0;
@Override
public boolean onBlockActivated(EntityPlayer player, RaytraceResult res, List<RaytraceResult> all) {
if (player.getCurrentEquippedItem() == null) {
return false;
}
if (ToolUtil.isToolEquipped(player)) {
@Override
public boolean onBlockActivated(EntityPlayer player, RaytraceResult res, List<RaytraceResult> all) {
if(player.getCurrentEquippedItem() == null) {
return false;
}
if(ToolUtil.isToolEquipped(player)) {
if (!getBundle().getEntity().getWorldObj().isRemote) {
if(!getBundle().getEntity().getWorldObj().isRemote) {
if (res != null && res.component != null) {
if(res != null && res.component != null) {
ForgeDirection connDir = res.component.dir;
ForgeDirection faceHit = ForgeDirection.getOrientation(res.movingObjectPosition.sideHit);
ForgeDirection connDir = res.component.dir;
ForgeDirection faceHit = ForgeDirection.getOrientation(res.movingObjectPosition.sideHit);
if (connDir == ForgeDirection.UNKNOWN || connDir == faceHit) {
if(connDir == ForgeDirection.UNKNOWN || connDir == faceHit) {
if (getConnectionMode(faceHit) == ConnectionMode.DISABLED) {
setConnectionMode(faceHit, getNextConnectionMode(faceHit));
return true;
}
BlockCoord loc = getLocation().getLocation(faceHit);
IGasConduit n = ConduitUtil.getConduit(
getBundle().getEntity().getWorldObj(),
loc.x,
loc.y,
loc.z,
IGasConduit.class);
if (n == null) {
return false;
}
if (!canJoinNeighbour(n)) {
return false;
}
if (!(n instanceof AbstractGasTankConduit)) {
return false;
}
AbstractGasTankConduit neighbour = (AbstractGasTankConduit) n;
if (neighbour.getGasType() == null || getGasType() == null) {
GasStack type = getGasType();
type = type != null ? type : neighbour.getGasType();
neighbour.setGasTypeOnNetwork(neighbour, type);
setGasTypeOnNetwork(this, type);
}
return ConduitUtil.joinConduits(this, faceHit);
} else if (containsExternalConnection(connDir)) {
// Toggle extraction mode
setConnectionMode(connDir, getNextConnectionMode(connDir));
} else if (containsConduitConnection(connDir)) {
GasStack curGasType = null;
if (getTankNetwork() != null) {
curGasType = getTankNetwork().getGasType();
}
ConduitUtil.disconectConduits(this, connDir);
setGasType(curGasType);
}
}
if(getConnectionMode(faceHit) == ConnectionMode.DISABLED) {
setConnectionMode(faceHit, getNextConnectionMode(faceHit));
return true;
}
return true;
}
return false;
BlockCoord loc = getLocation().getLocation(faceHit);
IGasConduit n = ConduitUtil.getConduit(getBundle().getEntity().getWorldObj(), loc.x, loc.y, loc.z, IGasConduit.class);
if(n == null) {
return false;
}
if(!canJoinNeighbour(n)) {
return false;
}
if(!(n instanceof AbstractGasTankConduit)) {
return false;
}
AbstractGasTankConduit neighbour = (AbstractGasTankConduit) n;
if(neighbour.getGasType() == null || getGasType() == null) {
GasStack type = getGasType();
type = type != null ? type : neighbour.getGasType();
neighbour.setGasTypeOnNetwork(neighbour, type);
setGasTypeOnNetwork(this, type);
}
return ConduitUtil.joinConduits(this, faceHit);
} else if(containsExternalConnection(connDir)) {
// Toggle extraction mode
setConnectionMode(connDir, getNextConnectionMode(connDir));
} else if(containsConduitConnection(connDir)) {
GasStack curGasType = null;
if(getTankNetwork() != null) {
curGasType = getTankNetwork().getGasType();
}
ConduitUtil.disconectConduits(this, connDir);
setGasType(curGasType);
}
}
}
return true;
}
private void setGasTypeOnNetwork(AbstractGasTankConduit con, GasStack type) {
AbstractConduitNetwork<?, ?> n = con.getNetwork();
if (n != null) {
AbstractGasTankConduitNetwork<?> network = (AbstractGasTankConduitNetwork<?>) n;
network.setGasType(type);
}
return false;
}
private void setGasTypeOnNetwork(AbstractGasTankConduit con, GasStack type) {
AbstractConduitNetwork<?, ?> n = con.getNetwork();
if(n != null) {
AbstractGasTankConduitNetwork<?> network = (AbstractGasTankConduitNetwork<?>) n;
network.setGasType(type);
}
protected abstract boolean canJoinNeighbour(IGasConduit n);
}
public abstract AbstractGasTankConduitNetwork<? extends AbstractGasTankConduit> getTankNetwork();
protected abstract boolean canJoinNeighbour(IGasConduit n);
@Method(modid = GasUtil.API_NAME)
public void setGasType(GasStack gasType) {
if (tank.getGas() != null && tank.getGas().isGasEqual(gasType)) {
return;
}
if (gasType != null) {
gasType = gasType.copy();
} else if (tank.getGas() == null) {
return;
}
tank.setGas(gasType);
stateDirty = true;
public abstract AbstractGasTankConduitNetwork<? extends AbstractGasTankConduit> getTankNetwork();
@Method(modid = GasUtil.API_NAME)
public void setGasType(GasStack gasType) {
if(tank.getGas() != null && tank.getGas().isGasEqual(gasType)) {
return;
}
public ConduitGasTank getTank() {
return tank;
if(gasType != null) {
gasType = gasType.copy();
} else if(tank.getGas() == null) {
return;
}
tank.setGas(gasType);
stateDirty = true;
}
@Method(modid = GasUtil.API_NAME)
public GasStack getGasType() {
GasStack result = null;
if (getTankNetwork() != null) {
result = getTankNetwork().getGasType();
}
if (result == null) {
result = tank.getGas();
}
return result;
public ConduitGasTank getTank() {
return tank;
}
@Method(modid = GasUtil.API_NAME)
public GasStack getGasType() {
GasStack result = null;
if(getTankNetwork() != null) {
result = getTankNetwork().getGasType();
}
@Override
public boolean canOutputToDir(ForgeDirection dir) {
if (super.canOutputToDir(dir)) {
IGasHandler ext = getExternalHandler(dir);
return ext != null && ext.canReceiveGas(dir.getOpposite(), tank.getGasType());
}
return false;
if(result == null) {
result = tank.getGas();
}
protected abstract void updateTank();
@Override
public void readFromNBT(NBTTagCompound nbtRoot, short nbtVersion) {
super.readFromNBT(nbtRoot, nbtVersion);
updateTank();
if (nbtRoot.hasKey("tank")) {
GasStack gas = GasStack.readFromNBT(nbtRoot.getCompoundTag("tank"));
tank.setGas(gas);
} else {
tank.setGas(null);
}
return result;
}
@Override
public boolean canOutputToDir(ForgeDirection dir) {
if (super.canOutputToDir(dir)) {
IGasHandler ext = getExternalHandler(dir);
return ext != null && ext.canReceiveGas(dir.getOpposite(), tank.getGasType());
}
return false;
}
@Override
public void writeToNBT(NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
GasStack gt = getGasType();
if (GasUtil.isGasValid(gt)) {
updateTank();
gt = gt.copy();
gt.amount = tank.getStored();
nbtRoot.setTag("tank", gt.write(new NBTTagCompound()));
}
protected abstract void updateTank();
@Override
public void readFromNBT(NBTTagCompound nbtRoot, short nbtVersion) {
super.readFromNBT(nbtRoot, nbtVersion);
updateTank();
if(nbtRoot.hasKey("tank")) {
GasStack gas = GasStack.readFromNBT(nbtRoot.getCompoundTag("tank"));
tank.setGas(gas);
} else {
tank.setGas(null);
}
}
@Override
public void writeToNBT(NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
GasStack gt = getGasType();
if(GasUtil.isGasValid(gt)) {
updateTank();
gt = gt.copy();
gt.amount = tank.getStored();
nbtRoot.setTag("tank", gt.write(new NBTTagCompound()));
}
}
}
@@ -1,59 +1,59 @@
package crazypants.enderio.conduit.gas;
import crazypants.enderio.conduit.AbstractConduitNetwork;
import mekanism.api.gas.GasStack;
import crazypants.enderio.conduit.AbstractConduitNetwork;
public class AbstractGasTankConduitNetwork<T extends AbstractGasTankConduit>
extends AbstractConduitNetwork<IGasConduit, T> {
public class AbstractGasTankConduitNetwork<T extends AbstractGasTankConduit> extends AbstractConduitNetwork<IGasConduit, T> {
protected GasStack gasType;
protected GasStack gasType;
protected AbstractGasTankConduitNetwork(Class<T> cl) {
super(cl, IGasConduit.class);
protected AbstractGasTankConduitNetwork(Class<T> cl) {
super(cl, IGasConduit.class);
}
public GasStack getGasType() {
return gasType;
}
@Override
public void addConduit(T con) {
super.addConduit(con);
con.setGasType(gasType);
}
public boolean setGasType(GasStack newType) {
if(gasType != null && gasType.isGasEqual(newType)) {
return false;
}
public GasStack getGasType() {
return gasType;
if(newType != null) {
gasType = newType.copy();
gasType.amount = 0;
} else {
gasType = null;
}
@Override
public void addConduit(T con) {
super.addConduit(con);
con.setGasType(gasType);
for (AbstractGasTankConduit conduit : conduits) {
conduit.setGasType(gasType);
}
return true;
}
public boolean setGasType(GasStack newType) {
if (gasType != null && gasType.isGasEqual(newType)) {
return false;
}
if (newType != null) {
gasType = newType.copy();
gasType.amount = 0;
} else {
gasType = null;
}
for (AbstractGasTankConduit conduit : conduits) {
conduit.setGasType(gasType);
}
return true;
}
public boolean canAcceptGas(GasStack acceptable) {
return areGassCompatable(gasType, acceptable);
}
public boolean canAcceptGas(GasStack acceptable) {
return areGassCompatable(gasType, acceptable);
public static boolean areGassCompatable(GasStack a, GasStack b) {
if(a == null || b == null) {
return true;
}
return a.isGasEqual(b);
}
public static boolean areGassCompatable(GasStack a, GasStack b) {
if (a == null || b == null) {
return true;
}
return a.isGasEqual(b);
public int getTotalVolume() {
int totalVolume = 0;
for (T con : conduits) {
totalVolume += con.getTank().getStored();
}
return totalVolume;
}
public int getTotalVolume() {
int totalVolume = 0;
for (T con : conduits) {
totalVolume += con.getTank().getStored();
}
return totalVolume;
}
}
@@ -1,155 +1,156 @@
package crazypants.enderio.conduit.gas;
import net.minecraft.nbt.NBTTagCompound;
import cpw.mods.fml.common.Optional.Method;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.GasTank;
import net.minecraft.nbt.NBTTagCompound;
import cpw.mods.fml.common.Optional.Method;
public class ConduitGasTank extends GasTank {
private int capacity;
private int capacity;
ConduitGasTank(int capacity) {
super(capacity);
this.capacity = capacity;
ConduitGasTank(int capacity) {
super(capacity);
this.capacity = capacity;
}
public float getFilledRatio() {
if(getStored() <= 0) {
return 0;
}
if(getMaxGas() <= 0) {
return -1;
}
float res = (float) getStored() / getMaxGas();
return res;
}
public boolean isFull() {
return getStored() >= getMaxGas();
}
public void setAmount(int amount) {
if(stored != null) {
stored.amount = amount;
}
}
public int getAvailableSpace() {
return getMaxGas() - getStored();
}
public void addAmount(int amount) {
setAmount(getStored() + amount);
}
@Override
public int getMaxGas() {
return this.capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
if(getStored() > capacity) {
setAmount(capacity);
}
}
@Override
@Method(modid = GasUtil.API_NAME)
public int receive(GasStack resource, boolean doReceive) {
if(resource == null || resource.getGas().getID() < 0) {
return 0;
}
public float getFilledRatio() {
if (getStored() <= 0) {
return 0;
if(stored == null || stored.getGas().getID() < 0) {
if(resource.amount <= capacity) {
if(doReceive) {
setGas(resource.copy());
}
if (getMaxGas() <= 0) {
return -1;
return resource.amount;
} else {
if(doReceive) {
stored = resource.copy();
stored.amount = capacity;
}
float res = (float) getStored() / getMaxGas();
return res;
return capacity;
}
}
public boolean isFull() {
return getStored() >= getMaxGas();
if(!stored.isGasEqual(resource)) {
return 0;
}
public void setAmount(int amount) {
if (stored != null) {
stored.amount = amount;
}
int space = capacity - stored.amount;
if(resource.amount <= space) {
if(doReceive) {
addAmount(resource.amount);
}
return resource.amount;
} else {
if(doReceive) {
stored.amount = capacity;
}
return space;
}
public int getAvailableSpace() {
return getMaxGas() - getStored();
}
@Override
@Method(modid = GasUtil.API_NAME)
public GasStack draw(int maxDrain, boolean doDraw) {
if(stored == null || stored.getGas().getID() < 0) {
return null;
}
if(stored.amount <= 0) {
return null;
}
public void addAmount(int amount) {
setAmount(getStored() + amount);
int used = maxDrain;
if(stored.amount < used) {
used = stored.amount;
}
@Override
public int getMaxGas() {
return this.capacity;
if(doDraw) {
addAmount(-used);
}
public void setCapacity(int capacity) {
this.capacity = capacity;
if (getStored() > capacity) {
setAmount(capacity);
}
GasStack drained = new GasStack(stored.getGas().getID(), used);
if(stored.amount < 0) {
stored.amount = 0;
}
return drained;
}
@Override
@Method(modid = GasUtil.API_NAME)
public int receive(GasStack resource, boolean doReceive) {
if (resource == null || resource.getGas().getID() < 0) {
return 0;
}
public String getGasName() {
return stored != null ? stored.getGas().getLocalizedName() : null;
}
if (stored == null || stored.getGas().getID() < 0) {
if (resource.amount <= capacity) {
if (doReceive) {
setGas(resource.copy());
}
return resource.amount;
} else {
if (doReceive) {
stored = resource.copy();
stored.amount = capacity;
}
return capacity;
}
}
public boolean containsValidGas() {
return GasUtil.isGasValid(stored);
}
if (!stored.isGasEqual(resource)) {
return 0;
}
int space = capacity - stored.amount;
if (resource.amount <= space) {
if (doReceive) {
addAmount(resource.amount);
}
return resource.amount;
} else {
if (doReceive) {
stored.amount = capacity;
}
return space;
}
public NBTTagCompound write(NBTTagCompound nbt) {
if(containsValidGas()) {
stored.write(nbt);
} else {
nbt.setBoolean("emptyGasTank", true);
}
return nbt;
}
@Override
@Method(modid = GasUtil.API_NAME)
public GasStack draw(int maxDrain, boolean doDraw) {
if (stored == null || stored.getGas().getID() < 0) {
return null;
}
if (stored.amount <= 0) {
return null;
}
int used = maxDrain;
if (stored.amount < used) {
used = stored.amount;
}
if (doDraw) {
addAmount(-used);
}
GasStack drained = new GasStack(stored.getGas().getID(), used);
if (stored.amount < 0) {
stored.amount = 0;
}
return drained;
public void read(NBTTagCompound nbt) {
if(!nbt.hasKey("emptyGasTank")) {
GasStack gas = GasStack.readFromNBT(nbt);
if(gas != null) {
setGas(gas);
}
}
}
public String getGasName() {
return stored != null ? stored.getGas().getLocalizedName() : null;
}
public boolean isEmpty() {
return stored == null || stored.amount == 0;
}
public boolean containsValidGas() {
return GasUtil.isGasValid(stored);
}
public NBTTagCompound write(NBTTagCompound nbt) {
if (containsValidGas()) {
stored.write(nbt);
} else {
nbt.setBoolean("emptyGasTank", true);
}
return nbt;
}
public void read(NBTTagCompound nbt) {
if (!nbt.hasKey("emptyGasTank")) {
GasStack gas = GasStack.readFromNBT(nbt);
if (gas != null) {
setGas(gas);
}
}
}
public boolean isEmpty() {
return stored == null || stored.amount == 0;
}
}
@@ -3,6 +3,8 @@ package crazypants.enderio.conduit.gas;
import java.util.HashMap;
import java.util.Map;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
@@ -10,6 +12,7 @@ import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import com.enderio.core.client.render.IconUtil;
import com.enderio.core.common.util.BlockCoord;
import cpw.mods.fml.common.Optional.Method;
import cpw.mods.fml.relauncher.Side;
@@ -19,269 +22,264 @@ import crazypants.enderio.conduit.AbstractConduitNetwork;
import crazypants.enderio.conduit.ConnectionMode;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.geom.CollidableComponent;
import crazypants.enderio.conduit.render.ConduitRenderer;
import crazypants.enderio.config.Config;
import mekanism.api.gas.Gas;
import mekanism.api.gas.GasStack;
public class GasConduit extends AbstractGasTankConduit {
public static final int CONDUIT_VOLUME = 1000;
public static final int CONDUIT_VOLUME = 1000;
public static final String ICON_KEY = "enderio:gasConduit";
public static final String ICON_CORE_KEY = "enderio:gasConduitCore";
public static final String ICON_EXTRACT_KEY = "enderio:gasConduitInput";
public static final String ICON_INSERT_KEY = "enderio:gasConduitOutput";
public static final String ICON_EMPTY_EDGE = "enderio:gasConduitEdge";
public static final String ICON_KEY = "enderio:gasConduit";
public static final String ICON_CORE_KEY = "enderio:gasConduitCore";
public static final String ICON_EXTRACT_KEY = "enderio:gasConduitInput";
public static final String ICON_INSERT_KEY = "enderio:gasConduitOutput";
public static final String ICON_EMPTY_EDGE = "enderio:gasConduitEdge";
static final Map<String, IIcon> ICONS = new HashMap<>();
static final Map<String, IIcon> ICONS = new HashMap<String, IIcon>();
@Override
public ConduitRenderer getRenderer() {
return GasConduitRenderer.instance.get();
@SideOnly(Side.CLIENT)
public static void initIcons() {
IconUtil.addIconProvider(new IconUtil.IIconProvider() {
@Override
public void registerIcons(IIconRegister register) {
ICONS.put(ICON_KEY, register.registerIcon(ICON_KEY));
ICONS.put(ICON_CORE_KEY, register.registerIcon(ICON_CORE_KEY));
ICONS.put(ICON_EXTRACT_KEY, register.registerIcon(ICON_EXTRACT_KEY));
ICONS.put(ICON_INSERT_KEY, register.registerIcon(ICON_INSERT_KEY));
ICONS.put(ICON_EMPTY_EDGE, register.registerIcon(ICON_EMPTY_EDGE));
}
@Override
public int getTextureType() {
return 0;
}
});
}
private GasConduitNetwork network;
private long ticksSinceFailedExtract = 0;
public static final int MAX_EXTRACT_PER_TICK = Config.gasConduitExtractRate;
public static final int MAX_IO_PER_TICK = Config.gasConduitMaxIoRate;
public GasConduit() {
updateTank();
}
@Override
public void updateEntity(World world) {
super.updateEntity(world);
if(world.isRemote) {
return;
}
doExtract();
if(stateDirty) {
getBundle().dirty();
stateDirty = false;
}
}
private void doExtract() {
BlockCoord loc = getLocation();
if(!hasConnectionMode(ConnectionMode.INPUT)) {
return;
}
if(network == null) {
return;
}
@SideOnly(Side.CLIENT)
public static void initIcons() {
IconUtil.addIconProvider(new IconUtil.IIconProvider() {
@Override
public void registerIcons(IIconRegister register) {
ICONS.put(ICON_KEY, register.registerIcon(ICON_KEY));
ICONS.put(ICON_CORE_KEY, register.registerIcon(ICON_CORE_KEY));
ICONS.put(ICON_EXTRACT_KEY, register.registerIcon(ICON_EXTRACT_KEY));
ICONS.put(ICON_INSERT_KEY, register.registerIcon(ICON_INSERT_KEY));
ICONS.put(ICON_EMPTY_EDGE, register.registerIcon(ICON_EMPTY_EDGE));
}
@Override
public int getTextureType() {
return 0;
}
});
// assume failure, reset to 0 if we do extract
ticksSinceFailedExtract++;
if(ticksSinceFailedExtract > 25 && ticksSinceFailedExtract % 10 != 0) {
// after 25 ticks of failing, only check every 10 ticks
return;
}
private GasConduitNetwork network;
private long ticksSinceFailedExtract = 0;
public static final int MAX_EXTRACT_PER_TICK = Config.gasConduitExtractRate;
public static final int MAX_IO_PER_TICK = Config.gasConduitMaxIoRate;
public GasConduit() {
updateTank();
}
@Override
public void updateEntity(World world) {
super.updateEntity(world);
if (world.isRemote) {
return;
}
doExtract();
if (stateDirty) {
getBundle().dirty();
stateDirty = false;
Gas f = tank.getGas() == null ? null : tank.getGas().getGas();
for (ForgeDirection dir : externalConnections) {
if(autoExtractForDir(dir)) {
if(network.extractFrom(this, dir, MAX_EXTRACT_PER_TICK)) {
ticksSinceFailedExtract = 0;
}
}
}
private void doExtract() {
if (!hasConnectionMode(ConnectionMode.INPUT)) {
return;
}
if (network == null) {
return;
}
}
// assume failure, reset to 0 if we do extract
ticksSinceFailedExtract++;
if (ticksSinceFailedExtract > 25 && ticksSinceFailedExtract % 10 != 0) {
// after 25 ticks of failing, only check every 10 ticks
return;
}
@Override
protected void updateTank() {
tank.setCapacity(CONDUIT_VOLUME);
if(network != null) {
network.updateConduitVolumes();
}
}
for (ForgeDirection dir : externalConnections) {
if (autoExtractForDir(dir)) {
if (network.extractFrom(this, dir, MAX_EXTRACT_PER_TICK)) {
ticksSinceFailedExtract = 0;
}
}
}
@Override
public ItemStack createItem() {
return new ItemStack(EnderIO.itemGasConduit);
}
@Override
public AbstractConduitNetwork<?, ?> getNetwork() {
return network;
}
@Override
public boolean setNetwork(AbstractConduitNetwork<?, ?> network) {
if(network == null) {
this.network = null;
return true;
}
if(!(network instanceof GasConduitNetwork)) {
return false;
}
@Override
protected void updateTank() {
tank.setCapacity(CONDUIT_VOLUME);
if (network != null) {
network.updateConduitVolumes();
}
GasConduitNetwork n = (GasConduitNetwork) network;
if(tank.getGas() == null) {
tank.setGas(n.getGasType() == null ? null : n.getGasType().copy());
} else if(n.getGasType() == null) {
n.setGasType(tank.getGas());
} else if(!tank.getGas().isGasEqual(n.getGasType())) {
return false;
}
this.network = n;
return true;
@Override
public ItemStack createItem() {
return new ItemStack(EnderIO.itemGasConduit);
}
@Override
public boolean canConnectToConduit(ForgeDirection direction, IConduit con) {
if(!super.canConnectToConduit(direction, con)) {
return false;
}
@Override
public AbstractConduitNetwork<?, ?> getNetwork() {
return network;
if(!(con instanceof GasConduit)) {
return false;
}
@Override
public boolean setNetwork(AbstractConduitNetwork<?, ?> network) {
if (network == null) {
this.network = null;
return true;
}
if (!(network instanceof GasConduitNetwork)) {
return false;
}
GasConduitNetwork n = (GasConduitNetwork) network;
if (tank.getGas() == null) {
tank.setGas(n.getGasType() == null ? null : n.getGasType().copy());
} else if (n.getGasType() == null) {
n.setGasType(tank.getGas());
} else if (!tank.getGas().isGasEqual(n.getGasType())) {
return false;
}
this.network = n;
return true;
if(getGasType() != null && ((GasConduit) con).getGasType() == null) {
return false;
}
return GasConduitNetwork.areGassCompatable(getGasType(), ((GasConduit) con).getGasType());
}
@Override
public boolean canConnectToConduit(ForgeDirection direction, IConduit con) {
if (!super.canConnectToConduit(direction, con)) {
return false;
}
if (!(con instanceof GasConduit)) {
return false;
}
if (getGasType() != null && ((GasConduit) con).getGasType() == null) {
return false;
}
return GasConduitNetwork.areGassCompatable(getGasType(), ((GasConduit) con).getGasType());
@Override
public void setConnectionMode(ForgeDirection dir, ConnectionMode mode) {
super.setConnectionMode(dir, mode);
refreshInputs(dir);
}
private void refreshInputs(ForgeDirection dir) {
if(network == null) {
return;
}
@Override
public void setConnectionMode(ForgeDirection dir, ConnectionMode mode) {
super.setConnectionMode(dir, mode);
refreshInputs(dir);
GasOutput lo = new GasOutput(getLocation().getLocation(dir), dir.getOpposite());
network.removeInput(lo);
if(getConnectionMode(dir).acceptsOutput() && containsExternalConnection(dir)) {
network.addInput(lo);
}
}
private void refreshInputs(ForgeDirection dir) {
if (network == null) {
return;
}
GasOutput lo = new GasOutput(getLocation().getLocation(dir), dir.getOpposite());
network.removeInput(lo);
if (getConnectionMode(dir).acceptsOutput() && containsExternalConnection(dir)) {
network.addInput(lo);
}
@Override
public void externalConnectionAdded(ForgeDirection fromDirection) {
super.externalConnectionAdded(fromDirection);
refreshInputs(fromDirection);
}
@Override
public void externalConnectionRemoved(ForgeDirection fromDirection) {
super.externalConnectionRemoved(fromDirection);
refreshInputs(fromDirection);
}
@Override
public IIcon getTextureForState(CollidableComponent component) {
if(component.dir == ForgeDirection.UNKNOWN) {
return ICONS.get(ICON_CORE_KEY);
}
return ICONS.get(ICON_KEY);
}
@Override
public void externalConnectionAdded(ForgeDirection fromDirection) {
super.externalConnectionAdded(fromDirection);
refreshInputs(fromDirection);
public IIcon getTextureForInputMode() {
return ICONS.get(ICON_EXTRACT_KEY);
}
public IIcon getTextureForOutputMode() {
return ICONS.get(ICON_INSERT_KEY);
}
public IIcon getNotSetEdgeTexture() {
return ICONS.get(ICON_EMPTY_EDGE);
}
@Override
public IIcon getTransmitionTextureForState(CollidableComponent component) {
if(isActive() && tank.containsValidGas()) {
return tank.getGas().getGas().getIcon();
}
return null;
}
@Override
public void externalConnectionRemoved(ForgeDirection fromDirection) {
super.externalConnectionRemoved(fromDirection);
refreshInputs(fromDirection);
// ------------------------------------------- Gas API
@Override
@Deprecated
@Method(modid = GasUtil.API_NAME)
public int receiveGas(ForgeDirection side, GasStack stack) {
return receiveGas(side, stack, true);
}
@Override
@Method(modid = GasUtil.API_NAME)
public int receiveGas(ForgeDirection side, GasStack stack, boolean doTransfer) {
if(network == null || !getConnectionMode(side).acceptsInput()) {
return 0;
}
return network.fill(side, stack, doTransfer);
}
@Override
public IIcon getTextureForState(CollidableComponent component) {
if (component.dir == ForgeDirection.UNKNOWN) {
return ICONS.get(ICON_CORE_KEY);
}
return ICONS.get(ICON_KEY);
@Override
@Deprecated
@Method(modid = GasUtil.API_NAME)
public GasStack drawGas(ForgeDirection side, int amount) {
return drawGas(side, amount, true);
}
@Override
@Method(modid = GasUtil.API_NAME)
public GasStack drawGas(ForgeDirection side, int amount, boolean doTransfer) {
if(network == null || !getConnectionMode(side).acceptsOutput()) {
return null;
}
return network.drain(side, amount, doTransfer);
}
public IIcon getTextureForInputMode() {
return ICONS.get(ICON_EXTRACT_KEY);
@Override
@Method(modid = GasUtil.API_NAME)
public boolean canReceiveGas(ForgeDirection from, Gas gas) {
if(network == null) {
return false;
}
return getConnectionMode(from).acceptsInput() && GasConduitNetwork.areGassCompatable(getGasType(), new GasStack(gas, 0));
}
public IIcon getTextureForOutputMode() {
return ICONS.get(ICON_INSERT_KEY);
@Override
@Method(modid = GasUtil.API_NAME)
public boolean canDrawGas(ForgeDirection from, Gas gas) {
if(network == null) {
return false;
}
return getConnectionMode(from).acceptsOutput() && GasConduitNetwork.areGassCompatable(getGasType(), new GasStack(gas, 0));
}
public IIcon getNotSetEdgeTexture() {
return ICONS.get(ICON_EMPTY_EDGE);
}
@Override
protected boolean canJoinNeighbour(IGasConduit n) {
return n instanceof GasConduit;
}
@Override
public IIcon getTransmitionTextureForState(CollidableComponent component) {
if (isActive() && tank.containsValidGas()) {
return tank.getGas().getGas().getIcon();
}
return null;
}
// ------------------------------------------- Gas API
@Override
@Deprecated
@Method(modid = GasUtil.API_NAME)
public int receiveGas(ForgeDirection side, GasStack stack) {
return receiveGas(side, stack, true);
}
@Override
@Method(modid = GasUtil.API_NAME)
public int receiveGas(ForgeDirection side, GasStack stack, boolean doTransfer) {
if (network == null || !getConnectionMode(side).acceptsInput()) {
return 0;
}
return network.fill(side, stack, doTransfer);
}
@Override
@Deprecated
@Method(modid = GasUtil.API_NAME)
public GasStack drawGas(ForgeDirection side, int amount) {
return drawGas(side, amount, true);
}
@Override
@Method(modid = GasUtil.API_NAME)
public GasStack drawGas(ForgeDirection side, int amount, boolean doTransfer) {
if (network == null || !getConnectionMode(side).acceptsOutput()) {
return null;
}
return network.drain(side, amount, doTransfer);
}
@Override
@Method(modid = GasUtil.API_NAME)
public boolean canReceiveGas(ForgeDirection from, Gas gas) {
if (network == null) {
return false;
}
return getConnectionMode(from).acceptsInput()
&& GasConduitNetwork.areGassCompatable(getGasType(), new GasStack(gas, 0));
}
@Override
@Method(modid = GasUtil.API_NAME)
public boolean canDrawGas(ForgeDirection from, Gas gas) {
if (network == null) {
return false;
}
return getConnectionMode(from).acceptsOutput()
&& GasConduitNetwork.areGassCompatable(getGasType(), new GasStack(gas, 0));
}
@Override
protected boolean canJoinNeighbour(IGasConduit n) {
return n instanceof GasConduit;
}
@Override
public AbstractGasTankConduitNetwork<? extends AbstractGasTankConduit> getTankNetwork() {
return network;
}
@Override
public AbstractGasTankConduitNetwork<? extends AbstractGasTankConduit> getTankNetwork() {
return network;
}
}
@@ -4,6 +4,8 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
@@ -11,259 +13,258 @@ import net.minecraftforge.common.util.ForgeDirection;
import com.enderio.core.common.util.BlockCoord;
import crazypants.enderio.conduit.IConduit;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
public class GasConduitNetwork extends AbstractGasTankConduitNetwork<GasConduit> {
private final ConduitGasTank tank = new ConduitGasTank(0);
private final ConduitGasTank tank = new ConduitGasTank(0);
private final Set<GasOutput> outputs = new HashSet<>();
private final Set<GasOutput> outputs = new HashSet<GasOutput>();
private Iterator<GasOutput> outputIterator;
private Iterator<GasOutput> outputIterator;
private int ticksActiveUnsynced;
private int ticksActiveUnsynced;
private boolean lastSyncedActive = false;
private boolean lastSyncedActive = false;
private int lastSyncedVolume = -1;
private int lastSyncedVolume = -1;
public GasConduitNetwork() {
super(GasConduit.class);
public GasConduitNetwork() {
super(GasConduit.class);
}
@Override
public void addConduit(GasConduit con) {
tank.setCapacity(tank.getMaxGas() + GasConduit.CONDUIT_VOLUME);
if(con.getTank().containsValidGas()) {
tank.addAmount(con.getTank().getStored());
}
for (ForgeDirection dir : con.getExternalConnections()) {
if(con.getConnectionMode(dir).acceptsOutput()) {
outputs.add(new GasOutput(con.getLocation().getLocation(dir), dir.getOpposite()));
}
}
outputIterator = null;
super.addConduit(con);
}
@Override
public boolean setGasType(GasStack newType) {
if(super.setGasType(newType)) {
GasStack ft = getGasType();
tank.setGas(ft == null ? null : ft.copy());
return true;
}
return false;
}
@Override
public void destroyNetwork() {
setConduitVolumes();
outputs.clear();
super.destroyNetwork();
}
private void setConduitVolumes() {
if(tank.containsValidGas() && !conduits.isEmpty()) {
GasStack gasPerConduit = tank.getGas().copy();
int numCons = conduits.size();
int leftOvers = gasPerConduit.amount % numCons;
gasPerConduit.amount = gasPerConduit.amount / numCons;
for (GasConduit con : conduits) {
GasStack f = gasPerConduit.copy();
if(leftOvers > 0) {
f.amount += 1;
leftOvers--;
}
con.getTank().setGas(f);
BlockCoord bc = con.getLocation();
con.getBundle().getEntity().getWorldObj().markTileEntityChunkModified(bc.x, bc.y, bc.z, con.getBundle().getEntity());
}
}
}
@Override
public void doNetworkTick() {
if(gasType == null || outputs.isEmpty() || !tank.containsValidGas() || tank.isEmpty()) {
updateActiveState();
return;
}
@Override
public void addConduit(GasConduit con) {
tank.setCapacity(tank.getMaxGas() + GasConduit.CONDUIT_VOLUME);
if (con.getTank().containsValidGas()) {
tank.addAmount(con.getTank().getStored());
}
for (ForgeDirection dir : con.getExternalConnections()) {
if (con.getConnectionMode(dir).acceptsOutput()) {
outputs.add(new GasOutput(con.getLocation().getLocation(dir), dir.getOpposite()));
}
}
outputIterator = null;
super.addConduit(con);
if(outputIterator == null || !outputIterator.hasNext()) {
outputIterator = outputs.iterator();
}
@Override
public boolean setGasType(GasStack newType) {
if (super.setGasType(newType)) {
updateActiveState();
GasStack ft = getGasType();
tank.setGas(ft == null ? null : ft.copy());
return true;
int numVisited = 0;
while (!tank.isEmpty() && numVisited < outputs.size()) {
if(!outputIterator.hasNext()) {
outputIterator = outputs.iterator();
}
GasOutput output = outputIterator.next();
if(output != null) {
IGasHandler cont = getTankContainer(output.location);
if(cont != null) {
GasStack offer = tank.getGas().copy();
int filled = cont.receiveGas(output.dir, offer);
if(filled > 0) {
tank.addAmount(-filled);
}
}
}
numVisited++;
}
}
private void updateActiveState() {
boolean isActive = tank.containsValidGas() && !tank.isEmpty();
if(lastSyncedActive != isActive) {
ticksActiveUnsynced++;
} else {
ticksActiveUnsynced = 0;
}
if(ticksActiveUnsynced >= 10 || ticksActiveUnsynced > 0 && isActive) {
if(!isActive) {
setGasType(null);
}
for (IConduit con : conduits) {
con.setActive(isActive);
}
lastSyncedActive = isActive;
ticksActiveUnsynced = 0;
}
}
public int fill(ForgeDirection from, GasStack resource, boolean doFill) {
if(resource == null) {
return 0;
}
resource.amount = Math.min(resource.amount, GasConduit.MAX_IO_PER_TICK);
boolean gasWasValid = tank.containsValidGas();
int res = tank.receive(resource, doFill);
if(doFill && res > 0 && gasWasValid) {
int vol = tank.getStored();
setGasType(resource);
tank.setAmount(vol);
}
return res;
}
public GasStack drain(ForgeDirection from, GasStack resource, boolean doDrain) {
if(resource == null || tank.isEmpty() || !tank.containsValidGas() || !GasConduitNetwork.areGassCompatable(getGasType(), resource)) {
return null;
}
int amount = Math.min(resource.amount, tank.getStored());
amount = Math.min(amount, GasConduit.MAX_IO_PER_TICK);
GasStack result = resource.copy();
result.amount = amount;
if(doDrain) {
tank.addAmount(-amount);
}
return result;
}
public GasStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
if(tank.isEmpty() || !tank.containsValidGas()) {
return null;
}
int amount = Math.min(maxDrain, tank.getStored());
GasStack result = tank.getGas().copy();
result.amount = amount;
if(doDrain) {
tank.addAmount(-amount);
}
return result;
}
public boolean extractFrom(GasConduit advancedGasConduit, ForgeDirection dir, int maxExtractPerTick) {
if(tank.isFull()) {
return false;
}
IGasHandler extTank = getTankContainer(advancedGasConduit, dir);
if(extTank != null) {
int maxExtract = Math.min(maxExtractPerTick, tank.getAvailableSpace());
if(gasType == null || !tank.containsValidGas()) {
GasStack drained = extTank.drawGas(dir.getOpposite(), maxExtract);
if(drained == null || drained.amount <= 0) {
return false;
}
setGasType(drained);
tank.setGas(drained.copy());
return true;
}
GasStack couldDrain = gasType.copy();
couldDrain.amount = maxExtract;
// GasStack drained = extTank.drain(dir.getOpposite(), couldDrain, true);
// if(drained == null || drained.amount <= 0) {
// return false;
// }
// tank.addAmount(drained.amount);
//Have to use this 'double handle' approach to work around an issue with TiC
GasStack drained = extTank.drawGas(dir.getOpposite(), maxExtract);
if(drained == null || drained.amount == 0) {
return false;
} else {
if(drained.isGasEqual(getGasType())) {
tank.addAmount(drained.amount);
}
}
return true;
}
return false;
}
@Override
public void destroyNetwork() {
setConduitVolumes();
outputs.clear();
super.destroyNetwork();
public IGasHandler getTankContainer(BlockCoord bc) {
World w = getWorld();
if(w == null) {
return null;
}
private void setConduitVolumes() {
if (tank.containsValidGas() && !conduits.isEmpty()) {
GasStack gasPerConduit = tank.getGas().copy();
int numCons = conduits.size();
int leftOvers = gasPerConduit.amount % numCons;
gasPerConduit.amount = gasPerConduit.amount / numCons;
for (GasConduit con : conduits) {
GasStack f = gasPerConduit.copy();
if (leftOvers > 0) {
f.amount += 1;
leftOvers--;
}
con.getTank().setGas(f);
BlockCoord bc = con.getLocation();
con.getBundle().getEntity().getWorldObj()
.markTileEntityChunkModified(bc.x, bc.y, bc.z, con.getBundle().getEntity());
}
}
TileEntity te = w.getTileEntity(bc.x, bc.y, bc.z);
if(te instanceof IGasHandler) {
return (IGasHandler) te;
}
return null;
}
@Override
public void doNetworkTick() {
if (gasType == null || outputs.isEmpty() || !tank.containsValidGas() || tank.isEmpty()) {
updateActiveState();
return;
}
public IGasHandler getTankContainer(GasConduit con, ForgeDirection dir) {
BlockCoord bc = con.getLocation().getLocation(dir);
return getTankContainer(bc);
}
if (outputIterator == null || !outputIterator.hasNext()) {
outputIterator = outputs.iterator();
}
updateActiveState();
int numVisited = 0;
while (!tank.isEmpty() && numVisited < outputs.size()) {
if (!outputIterator.hasNext()) {
outputIterator = outputs.iterator();
}
GasOutput output = outputIterator.next();
if (output != null) {
IGasHandler cont = getTankContainer(output.location);
if (cont != null) {
GasStack offer = tank.getGas().copy();
int filled = cont.receiveGas(output.dir, offer);
if (filled > 0) {
tank.addAmount(-filled);
}
}
}
numVisited++;
}
World getWorld() {
if(conduits.isEmpty()) {
return null;
}
return conduits.get(0).getBundle().getWorld();
}
private void updateActiveState() {
boolean isActive = tank.containsValidGas() && !tank.isEmpty();
if (lastSyncedActive != isActive) {
ticksActiveUnsynced++;
} else {
ticksActiveUnsynced = 0;
}
if (ticksActiveUnsynced >= 10 || ticksActiveUnsynced > 0 && isActive) {
if (!isActive) {
setGasType(null);
}
for (IConduit con : conduits) {
con.setActive(isActive);
}
lastSyncedActive = isActive;
ticksActiveUnsynced = 0;
}
public void removeInput(GasOutput lo) {
outputs.remove(lo);
outputIterator = null;
}
public void addInput(GasOutput lo) {
outputs.add(lo);
outputIterator = null;
}
public void updateConduitVolumes() {
if(tank.getStored() == lastSyncedVolume) {
return;
}
setConduitVolumes();
lastSyncedVolume = tank.getStored();
}
public int fill(ForgeDirection from, GasStack resource, boolean doFill) {
if (resource == null) {
return 0;
}
resource.amount = Math.min(resource.amount, GasConduit.MAX_IO_PER_TICK);
boolean gasWasValid = tank.containsValidGas();
int res = tank.receive(resource, doFill);
if (doFill && res > 0 && gasWasValid) {
int vol = tank.getStored();
setGasType(resource);
tank.setAmount(vol);
}
return res;
}
public GasStack drain(ForgeDirection from, GasStack resource, boolean doDrain) {
if (resource == null || tank.isEmpty()
|| !tank.containsValidGas()
|| !GasConduitNetwork.areGassCompatable(getGasType(), resource)) {
return null;
}
int amount = Math.min(resource.amount, tank.getStored());
amount = Math.min(amount, GasConduit.MAX_IO_PER_TICK);
GasStack result = resource.copy();
result.amount = amount;
if (doDrain) {
tank.addAmount(-amount);
}
return result;
}
public GasStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
if (tank.isEmpty() || !tank.containsValidGas()) {
return null;
}
int amount = Math.min(maxDrain, tank.getStored());
GasStack result = tank.getGas().copy();
result.amount = amount;
if (doDrain) {
tank.addAmount(-amount);
}
return result;
}
public boolean extractFrom(GasConduit advancedGasConduit, ForgeDirection dir, int maxExtractPerTick) {
if (tank.isFull()) {
return false;
}
IGasHandler extTank = getTankContainer(advancedGasConduit, dir);
if (extTank != null) {
int maxExtract = Math.min(maxExtractPerTick, tank.getAvailableSpace());
if (gasType == null || !tank.containsValidGas()) {
GasStack drained = extTank.drawGas(dir.getOpposite(), maxExtract);
if (drained == null || drained.amount <= 0) {
return false;
}
setGasType(drained);
tank.setGas(drained.copy());
return true;
}
GasStack couldDrain = gasType.copy();
couldDrain.amount = maxExtract;
// GasStack drained = extTank.drain(dir.getOpposite(), couldDrain, true);
// if(drained == null || drained.amount <= 0) {
// return false;
// }
// tank.addAmount(drained.amount);
// Have to use this 'double handle' approach to work around an issue with TiC
GasStack drained = extTank.drawGas(dir.getOpposite(), maxExtract);
if (drained == null || drained.amount == 0) {
return false;
} else {
if (drained.isGasEqual(getGasType())) {
tank.addAmount(drained.amount);
}
}
return true;
}
return false;
}
public IGasHandler getTankContainer(BlockCoord bc) {
World w = getWorld();
if (w == null) {
return null;
}
TileEntity te = w.getTileEntity(bc.x, bc.y, bc.z);
if (te instanceof IGasHandler) {
return (IGasHandler) te;
}
return null;
}
public IGasHandler getTankContainer(GasConduit con, ForgeDirection dir) {
BlockCoord bc = con.getLocation().getLocation(dir);
return getTankContainer(bc);
}
World getWorld() {
if (conduits.isEmpty()) {
return null;
}
return conduits.get(0).getBundle().getWorld();
}
public void removeInput(GasOutput lo) {
outputs.remove(lo);
outputIterator = null;
}
public void addInput(GasOutput lo) {
outputs.add(lo);
outputIterator = null;
}
public void updateConduitVolumes() {
if (tank.getStored() == lastSyncedVolume) {
return;
}
setConduitVolumes();
lastSyncedVolume = tank.getStored();
}
}
@@ -1,13 +1,13 @@
package crazypants.enderio.conduit.gas;
import java.util.List;
import mekanism.api.gas.GasStack;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraftforge.common.util.ForgeDirection;
import com.enderio.core.client.render.BoundingBox;
import com.enderio.core.client.render.CubeRenderer;
import com.enderio.core.client.render.RenderUtil;
import com.enderio.core.common.vecmath.Vector3d;
import com.enderio.core.common.vecmath.Vertex;
@@ -20,166 +20,162 @@ import crazypants.enderio.conduit.geom.CollidableComponent;
import crazypants.enderio.conduit.geom.ConnectionModeGeometry;
import crazypants.enderio.conduit.geom.Offset;
import crazypants.enderio.conduit.render.ConduitBundleRenderer;
import crazypants.enderio.conduit.render.ConduitRenderer;
import crazypants.enderio.conduit.render.DefaultConduitRenderer;
import mekanism.api.gas.GasStack;
import static com.enderio.core.client.render.CubeRenderer.addVecWithUV;
public class GasConduitRenderer extends DefaultConduitRenderer {
public static final ThreadLocal<ConduitRenderer> instance = ThreadLocal.withInitial(GasConduitRenderer::new);
@Override
public boolean isRendererForConduit(IConduit conduit) {
return conduit instanceof GasConduit;
}
@Override
public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x,
double y, double z, float partialTick, float worldLight, RenderBlocks rb) {
super.renderEntity(conduitBundleRenderer, te, conduit, x, y, z, partialTick, worldLight, rb);
@Override
public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick,
float worldLight, RenderBlocks rb) {
super.renderEntity(conduitBundleRenderer, te, conduit, x, y, z, partialTick, worldLight, rb);
if(!conduit.hasConnectionMode(ConnectionMode.INPUT) && !conduit.hasConnectionMode(ConnectionMode.OUTPUT)) {
return;
}
GasConduit pc = (GasConduit) conduit;
for (ForgeDirection dir : conduit.getExternalConnections()) {
IIcon tex = null;
if(conduit.getConnectionMode(dir) == ConnectionMode.INPUT) {
tex = pc.getTextureForInputMode();
} else if(conduit.getConnectionMode(dir) == ConnectionMode.OUTPUT) {
tex = pc.getTextureForOutputMode();
}
if(tex != null) {
Offset offset = te.getOffset(IGasConduit.class, dir);
ConnectionModeGeometry.renderModeConnector(dir, offset, tex, true);
}
}
}
@Override
protected void renderConduit(IIcon tex, IConduit conduit, CollidableComponent component, float brightness) {
super.renderConduit(tex, conduit, component, brightness);
if(isNSEWUD(component.dir)) {
GasConduit lc = (GasConduit) conduit;
GasStack gas = lc.getGasType();
IIcon texture = null;
if(gas != null) {
texture = gas.getGas().getIcon();
}
if(texture == null) {
texture = lc.getNotSetEdgeTexture();
}
float scaleFactor = 0.75f;
float xLen = Math.abs(component.dir.offsetX) == 1 ? 1 : scaleFactor;
float yLen = Math.abs(component.dir.offsetY) == 1 ? 1 : scaleFactor;
float zLen = Math.abs(component.dir.offsetZ) == 1 ? 1 : scaleFactor;
BoundingBox cube = component.bound;
BoundingBox bb = cube.scale(xLen, yLen, zLen);
for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) {
if(d != component.dir && d != component.dir.getOpposite()) {
ForgeDirection vDir = RenderUtil.getVDirForFace(d);
if(component.dir == ForgeDirection.UP || component.dir == ForgeDirection.DOWN) {
vDir = RenderUtil.getUDirForFace(d);
} else if((component.dir == ForgeDirection.NORTH || component.dir == ForgeDirection.SOUTH) && d.offsetY != 0) {
vDir = RenderUtil.getUDirForFace(d);
}
float minU = texture.getMinU();
float maxU = texture.getMaxU();
float minV = texture.getMinV();
float maxV = texture.getMaxV();
float sideScale = Math.max(bb.sizeX(), bb.sizeY()) * 2 / 16f;
sideScale = Math.max(sideScale, bb.sizeZ() * 2 / 16f);
float width = Math.min(bb.sizeX(), bb.sizeY()) * 15f / 16f;
List<Vertex> corners = bb.getCornersWithUvForFace(d, minU, maxU, minV, maxV);
moveEdgeCorners(corners, vDir, width);
moveEdgeCorners(corners, component.dir.getOpposite(), sideScale);
for (Vertex c : corners) {
addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
corners = bb.getCornersWithUvForFace(d, minU, maxU, minV, maxV);
moveEdgeCorners(corners, vDir.getOpposite(), width);
moveEdgeCorners(corners, component.dir.getOpposite(), sideScale);
for (Vertex c : corners) {
addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
if (!conduit.hasConnectionMode(ConnectionMode.INPUT) && !conduit.hasConnectionMode(ConnectionMode.OUTPUT)) {
return;
}
GasConduit pc = (GasConduit) conduit;
for (ForgeDirection dir : conduit.getExternalConnections()) {
IIcon tex = null;
if (conduit.getConnectionMode(dir) == ConnectionMode.INPUT) {
tex = pc.getTextureForInputMode();
} else if (conduit.getConnectionMode(dir) == ConnectionMode.OUTPUT) {
tex = pc.getTextureForOutputMode();
}
if (tex != null) {
Offset offset = te.getOffset(IGasConduit.class, dir);
ConnectionModeGeometry.renderModeConnector(dir, offset, tex, true);
}
}
if(conduit.getConnectionMode(component.dir) == ConnectionMode.DISABLED) {
tex = EnderIO.blockConduitBundle.getConnectorIcon(component.data);
List<Vertex> corners = component.bound.getCornersWithUvForFace(component.dir, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV());
Tessellator tessellator = Tessellator.instance;
for (Vertex c : corners) {
addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
//back face
for (int i = corners.size() - 1; i >= 0; i--) {
Vertex c = corners.get(i);
addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
}
}
@Override
protected void renderConduit(IIcon tex, IConduit conduit, CollidableComponent component, float brightness) {
super.renderConduit(tex, conduit, component, brightness);
final CubeRenderer cr = CubeRenderer.get();
int i;
}
if (isNSEWUD(component.dir)) {
GasConduit lc = (GasConduit) conduit;
@Override
protected void renderTransmission(IConduit conduit, IIcon tex, CollidableComponent component, float selfIllum) {
super.renderTransmission(conduit, tex, component, selfIllum);
}
GasStack gas = lc.getGasType();
IIcon texture = null;
if (gas != null) {
texture = gas.getGas().getIcon();
}
private void moveEdgeCorners(List<Vertex> vertices, ForgeDirection edge, float scaleFactor) {
int[] indices = getClosest(edge, vertices);
vertices.get(indices[0]).xyz.x -= scaleFactor * edge.offsetX;
vertices.get(indices[1]).xyz.x -= scaleFactor * edge.offsetX;
vertices.get(indices[0]).xyz.y -= scaleFactor * edge.offsetY;
vertices.get(indices[1]).xyz.y -= scaleFactor * edge.offsetY;
vertices.get(indices[0]).xyz.z -= scaleFactor * edge.offsetZ;
vertices.get(indices[1]).xyz.z -= scaleFactor * edge.offsetZ;
}
if (texture == null) {
texture = lc.getNotSetEdgeTexture();
}
float scaleFactor = 0.75f;
float xLen = Math.abs(component.dir.offsetX) == 1 ? 1 : scaleFactor;
float yLen = Math.abs(component.dir.offsetY) == 1 ? 1 : scaleFactor;
float zLen = Math.abs(component.dir.offsetZ) == 1 ? 1 : scaleFactor;
BoundingBox cube = component.bound;
BoundingBox bb = cube.scale(xLen, yLen, zLen);
for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) {
if (d != component.dir && d != component.dir.getOpposite()) {
ForgeDirection vDir = RenderUtil.getVDirForFace(d);
if (component.dir == ForgeDirection.UP || component.dir == ForgeDirection.DOWN) {
vDir = RenderUtil.getUDirForFace(d);
} else if ((component.dir == ForgeDirection.NORTH || component.dir == ForgeDirection.SOUTH)
&& d.offsetY != 0) {
vDir = RenderUtil.getUDirForFace(d);
}
float minU = texture.getMinU();
float maxU = texture.getMaxU();
float minV = texture.getMinV();
float maxV = texture.getMaxV();
float sideScale = Math.max(bb.sizeX(), bb.sizeY()) * 2 / 16f;
sideScale = Math.max(sideScale, bb.sizeZ() * 2 / 16f);
float width = Math.min(bb.sizeX(), bb.sizeY()) * 15f / 16f;
List<Vertex> corners = bb.getCornersWithUvForFace(d, minU, maxU, minV, maxV);
moveEdgeCorners(corners, vDir, width);
moveEdgeCorners(corners, component.dir.getOpposite(), sideScale);
for (i = 0; i < corners.size(); i++) {
final Vertex c = corners.get(i);
cr.addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
corners = bb.getCornersWithUvForFace(d, minU, maxU, minV, maxV);
moveEdgeCorners(corners, vDir.getOpposite(), width);
moveEdgeCorners(corners, component.dir.getOpposite(), sideScale);
for (i = 0; i < corners.size(); i++) {
final Vertex c = corners.get(i);
cr.addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
}
}
if (conduit.getConnectionMode(component.dir) == ConnectionMode.DISABLED) {
tex = EnderIO.blockConduitBundle.getConnectorIcon(component.data);
List<Vertex> corners = component.bound.getCornersWithUvForFace(
component.dir,
tex.getMinU(),
tex.getMaxU(),
tex.getMinV(),
tex.getMaxV());
for (i = 0; i < corners.size(); i++) {
final Vertex c = corners.get(i);
cr.addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
// back face
for (i = corners.size() - 1; i >= 0; i--) {
final Vertex c = corners.get(i);
cr.addVecWithUV(c.xyz, c.uv.x, c.uv.y);
}
}
private int[] getClosest(ForgeDirection edge, List<Vertex> vertices) {
int[] res = new int[] { -1, -1 };
boolean highest = edge.offsetX > 0 || edge.offsetY > 0 || edge.offsetZ > 0;
double minMax = highest ? -Double.MAX_VALUE : Double.MAX_VALUE;
int index = 0;
for (Vertex v : vertices) {
double val = get(v.xyz, edge);
if(highest ? val >= minMax : val <= minMax) {
if(val != minMax) {
res[0] = index;
} else {
res[1] = index;
}
minMax = val;
}
index++;
}
return res;
}
@Override
protected void renderTransmission(IConduit conduit, IIcon tex, CollidableComponent component, float selfIllum) {
super.renderTransmission(conduit, tex, component, selfIllum);
private double get(Vector3d xyz, ForgeDirection edge) {
if(edge == ForgeDirection.EAST || edge == ForgeDirection.WEST) {
return xyz.x;
}
if(edge == ForgeDirection.UP || edge == ForgeDirection.DOWN) {
return xyz.y;
}
return xyz.z;
}
private void moveEdgeCorners(List<Vertex> vertices, ForgeDirection edge, float scaleFactor) {
int[] indices = getClosest(edge, vertices);
vertices.get(indices[0]).xyz.x -= scaleFactor * edge.offsetX;
vertices.get(indices[1]).xyz.x -= scaleFactor * edge.offsetX;
vertices.get(indices[0]).xyz.y -= scaleFactor * edge.offsetY;
vertices.get(indices[1]).xyz.y -= scaleFactor * edge.offsetY;
vertices.get(indices[0]).xyz.z -= scaleFactor * edge.offsetZ;
vertices.get(indices[1]).xyz.z -= scaleFactor * edge.offsetZ;
}
private int[] getClosest(ForgeDirection edge, List<Vertex> vertices) {
int[] res = new int[] { -1, -1 };
boolean highest = edge.offsetX > 0 || edge.offsetY > 0 || edge.offsetZ > 0;
double minMax = highest ? -Double.MAX_VALUE : Double.MAX_VALUE;
int index = 0;
for (Vertex v : vertices) {
double val = get(v.xyz, edge);
if (highest ? val >= minMax : val <= minMax) {
if (val != minMax) {
res[0] = index;
} else {
res[1] = index;
}
minMax = val;
}
index++;
}
return res;
}
private double get(Vector3d xyz, ForgeDirection edge) {
if (edge == ForgeDirection.EAST || edge == ForgeDirection.WEST) {
return xyz.x;
}
if (edge == ForgeDirection.UP || edge == ForgeDirection.DOWN) {
return xyz.y;
}
return xyz.z;
}
}
@@ -6,38 +6,45 @@ import com.enderio.core.common.util.BlockCoord;
public class GasOutput {
final ForgeDirection dir;
final BlockCoord location;
final ForgeDirection dir;
final BlockCoord location;
public GasOutput(BlockCoord bc, ForgeDirection dir) {
this.dir = dir;
this.location = bc;
}
public GasOutput(BlockCoord bc, ForgeDirection dir) {
this.dir = dir;
this.location = bc;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((location == null) ? 0 : location.hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((location == null) ? 0 : location.hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
GasOutput other = (GasOutput) obj;
if (location == null) {
if (other.location != null) return false;
} else if (!location.equals(other.location)) return false;
if (dir != other.dir) return false;
return true;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
GasOutput other = (GasOutput) obj;
if(location == null) {
if(other.location != null)
return false;
} else if(!location.equals(other.location))
return false;
if(dir != other.dir)
return false;
return true;
}
@Override
public String toString() {
return "GasOutput [dir=" + dir + ", location=" + location + "]";
}
}
@Override
public String toString() {
return "GasOutput [dir=" + dir + ", location=" + location + "]";
}
}
@@ -1,5 +1,7 @@
package crazypants.enderio.conduit.gas;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
@@ -9,63 +11,62 @@ import cpw.mods.fml.common.ModAPIManager;
import cpw.mods.fml.common.Optional.Method;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.config.Config;
import mekanism.api.gas.GasStack;
import mekanism.api.gas.IGasHandler;
public final class GasUtil {
private static boolean useCheckPerformed = false;
private static boolean isGasConduitEnabled = false;
private static boolean useCheckPerformed = false;
private static boolean isGasConduitEnabled = false;
public static final String API_NAME = "MekanismAPI|gas";
public static final String API_NAME = "MekanismAPI|gas";
public static boolean isGasConduitEnabled() {
if (!useCheckPerformed) {
if (Config.isGasConduitEnabled) {
isGasConduitEnabled = ModAPIManager.INSTANCE.hasAPI(API_NAME);
} else {
isGasConduitEnabled = false;
}
useCheckPerformed = true;
}
return isGasConduitEnabled;
public static boolean isGasConduitEnabled() {
if(!useCheckPerformed) {
if(Config.isGasConduitEnabled) {
isGasConduitEnabled = ModAPIManager.INSTANCE.hasAPI(API_NAME);
} else {
isGasConduitEnabled = false;
}
useCheckPerformed = true;
}
return isGasConduitEnabled;
}
@Method(modid = API_NAME)
public static IGasHandler getExternalGasHandler(IBlockAccess world, BlockCoord bc) {
IGasHandler con = getGasHandler(world, bc);
return (con != null && !(con instanceof IConduitBundle)) ? con : null;
@Method(modid = API_NAME)
public static IGasHandler getExternalGasHandler(IBlockAccess world, BlockCoord bc) {
IGasHandler con = getGasHandler(world, bc);
return (con != null && !(con instanceof IConduitBundle)) ? con : null;
}
@Method(modid = API_NAME)
public static IGasHandler getGasHandler(IBlockAccess world, BlockCoord bc) {
return getGasHandler(world, bc.x, bc.y, bc.z);
}
@Method(modid = API_NAME)
public static IGasHandler getGasHandler(IBlockAccess world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
return getGasHandler(te);
}
@Method(modid = API_NAME)
public static IGasHandler getGasHandler(TileEntity te) {
if(te instanceof IGasHandler) {
return (IGasHandler) te;
}
return null;
}
@Method(modid = API_NAME)
public static IGasHandler getGasHandler(IBlockAccess world, BlockCoord bc) {
return getGasHandler(world, bc.x, bc.y, bc.z);
@Method(modid = API_NAME)
public static boolean isGasValid(GasStack gas) {
if(gas != null) {
String name = gas.getGas().getLocalizedName();
if(name != null && !name.trim().isEmpty()) {
return true;
}
}
return false;
}
@Method(modid = API_NAME)
public static IGasHandler getGasHandler(IBlockAccess world, int x, int y, int z) {
TileEntity te = world.getTileEntity(x, y, z);
return getGasHandler(te);
}
@Method(modid = API_NAME)
public static IGasHandler getGasHandler(TileEntity te) {
if (te instanceof IGasHandler) {
return (IGasHandler) te;
}
return null;
}
@Method(modid = API_NAME)
public static boolean isGasValid(GasStack gas) {
if (gas != null) {
String name = gas.getGas().getLocalizedName();
if (name != null && !name.trim().isEmpty()) {
return true;
}
}
return false;
}
private GasUtil() {}
private GasUtil() {
}
}
@@ -1,16 +1,16 @@
package crazypants.enderio.conduit.gas;
import mekanism.api.gas.IGasHandler;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.common.Optional.Interface;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.IExtractor;
import mekanism.api.gas.IGasHandler;
@Interface(iface = "mekanism.api.gas.IGasHandler", modid = GasUtil.API_NAME)
public interface IGasConduit extends IConduit, IGasHandler, IExtractor {
boolean canOutputToDir(ForgeDirection dir);
boolean canOutputToDir(ForgeDirection dir);
boolean isExtractingFromDir(ForgeDirection dir);
boolean isExtractingFromDir(ForgeDirection dir);
}
@@ -21,60 +21,61 @@ import crazypants.enderio.gui.IconEIO;
public class ItemGasConduit extends AbstractItemConduit implements IAdvancedTooltipProvider {
private static final ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] {
new ItemConduitSubtype(ModObject.itemGasConduit.name(), "enderio:itemGasConduit"), };
private static ItemConduitSubtype[] subtypes = new ItemConduitSubtype[] {
new ItemConduitSubtype(ModObject.itemGasConduit.name(), "enderio:itemGasConduit"),
};
public static ItemGasConduit create() {
ItemGasConduit result = new ItemGasConduit();
if (GasUtil.isGasConduitEnabled()) {
result.init();
ConduitDisplayMode.registerDisplayMode(
new ConduitDisplayMode(
IGasConduit.class,
IconEIO.WRENCH_OVERLAY_GAS,
IconEIO.WRENCH_OVERLAY_GAS_OFF));
}
return result;
public static ItemGasConduit create() {
ItemGasConduit result = new ItemGasConduit();
if (GasUtil.isGasConduitEnabled()) {
result.init();
ConduitDisplayMode.registerDisplayMode(new ConduitDisplayMode(IGasConduit.class, IconEIO.WRENCH_OVERLAY_GAS, IconEIO.WRENCH_OVERLAY_GAS_OFF));
}
return result;
}
protected ItemGasConduit() {
super(ModObject.itemGasConduit, subtypes);
if (!GasUtil.isGasConduitEnabled()) {
setCreativeTab(null);
}
protected ItemGasConduit() {
super(ModObject.itemGasConduit, subtypes);
if(!GasUtil.isGasConduitEnabled()) {
setCreativeTab(null);
}
}
@Override
public Class<? extends IConduit> getBaseConduitType() {
return IGasConduit.class;
}
@Override
public Class<? extends IConduit> getBaseConduitType() {
return IGasConduit.class;
}
@Override
public IConduit createConduit(ItemStack stack, EntityPlayer player) {
return new GasConduit();
}
@Override
public IConduit createConduit(ItemStack stack, EntityPlayer player) {
return new GasConduit();
}
@Override
@SideOnly(Side.CLIENT)
public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {}
@Override
@SideOnly(Side.CLIENT)
public void addCommonEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
}
@Override
@SideOnly(Side.CLIENT)
public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {}
@Override
@SideOnly(Side.CLIENT)
public void addBasicEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
@Override
@SideOnly(Side.CLIENT)
public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List<String> list, boolean flag) {
String gpt = " " + EnderIO.lang.localize("gas.gasTick");
int extractRate = Config.gasConduitExtractRate;
int maxIo = Config.gasConduitMaxIoRate;
list.add(EnderIO.lang.localize("itemGasConduit.tooltip.maxExtract") + " " + extractRate + gpt);
list.add(EnderIO.lang.localize("itemGasConduit.tooltip.maxIo") + " " + maxIo + gpt);
SpecialTooltipHandler.addDetailedTooltipFromResources(list, "enderio.itemGasConduit");
}
}
@Override
@SideOnly(Side.CLIENT)
public void addDetailedEntries(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) {
String gpt = " " + EnderIO.lang.localize("gas.gasTick");
int extractRate = Config.gasConduitExtractRate;
int maxIo = Config.gasConduitMaxIoRate;
list.add(EnderIO.lang.localize("itemGasConduit.tooltip.maxExtract") + " " + extractRate + gpt);
list.add(EnderIO.lang.localize("itemGasConduit.tooltip.maxIo") + " " + maxIo + gpt);
SpecialTooltipHandler.addDetailedTooltipFromResources(list, "enderio.itemGasConduit");
}
@Override
public boolean shouldHideFacades(ItemStack stack, EntityPlayer player) {
return true;
}
@Override
public boolean shouldHideFacades(ItemStack stack, EntityPlayer player) {
return true;
}
}
@@ -1,5 +1,6 @@
package crazypants.enderio.conduit.gas;
import io.netty.buffer.ByteBuf;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
@@ -10,35 +11,35 @@ 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 crazypants.util.ClientUtil;
import io.netty.buffer.ByteBuf;
public class PacketGasLevel extends MessageTileEntity<TileEntity> implements IMessageHandler<PacketGasLevel, IMessage> {
public NBTTagCompound tc;
public NBTTagCompound tc;
public PacketGasLevel() {}
public PacketGasLevel() {
}
public PacketGasLevel(IGasConduit conduit) {
super(conduit.getBundle().getEntity());
tc = new NBTTagCompound();
conduit.writeToNBT(tc);
}
public PacketGasLevel(IGasConduit conduit) {
super(conduit.getBundle().getEntity());
tc = new NBTTagCompound();
conduit.writeToNBT(tc);
}
@Override
public void toBytes(ByteBuf buf) {
super.toBytes(buf);
ByteBufUtils.writeTag(buf, tc);
}
@Override
public void toBytes(ByteBuf buf) {
super.toBytes(buf);
ByteBufUtils.writeTag(buf, tc);
}
@Override
public void fromBytes(ByteBuf buf) {
super.fromBytes(buf);
tc = ByteBufUtils.readTag(buf);
}
@Override
public void fromBytes(ByteBuf buf) {
super.fromBytes(buf);
tc = ByteBufUtils.readTag(buf);
}
@Override
public IMessage onMessage(PacketGasLevel message, MessageContext ctx) {
ClientUtil.doGasLevelUpdate(message.x, message.y, message.z, message);
return null;
}
@Override
public IMessage onMessage(PacketGasLevel message, MessageContext ctx) {
ClientUtil.doGasLevelUpdate(message.x, message.y, message.z, message);
return null;
}
}
@@ -5,85 +5,86 @@ import java.util.HashMap;
import java.util.Map;
import net.minecraftforge.common.util.ForgeDirection;
import crazypants.enderio.conduit.IConduit;
public class CollidableCache {
public static final CollidableCache instance = new CollidableCache();
public static final CollidableCache instance = new CollidableCache();
private final Map<CacheKey, Collection<CollidableComponent>> cache = new HashMap<>();
private final Map<CacheKey, Collection<CollidableComponent>> cache = new HashMap<CollidableCache.CacheKey, Collection<CollidableComponent>>();
public CacheKey createKey(Class<? extends IConduit> baseType, Offset offset, ForgeDirection dir, boolean isStub) {
return new CacheKey(baseType, offset, dir, isStub);
public CacheKey createKey(Class<? extends IConduit> baseType, Offset offset, ForgeDirection dir, boolean isStub) {
return new CacheKey(baseType, offset, dir, isStub);
}
public Collection<CollidableComponent> getCollidables(CacheKey key, IConduit conduit) {
Collection<CollidableComponent> result = cache.get(key);
if(result == null) {
result = conduit.createCollidables(key);
cache.put(key, result);
}
return result;
}
public static class CacheKey {
public final Class<? extends IConduit> baseType;
public final String className; // used to generate reliable equals /
// hashcode
public final Offset offset;
public final ForgeDirection dir;
public final boolean isStub;
public CacheKey(Class<? extends IConduit> baseType, Offset offset, ForgeDirection dir, boolean isStub) {
this.baseType = baseType;
className = baseType.getCanonicalName();
this.offset = offset;
this.dir = dir;
this.isStub = isStub;
}
public Collection<CollidableComponent> getCollidables(CacheKey key, IConduit conduit) {
Collection<CollidableComponent> result = cache.get(key);
if (result == null) {
result = conduit.createCollidables(key);
cache.put(key, result);
}
return result;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((className == null) ? 0 : className.hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
result = prime * result + (isStub ? 1231 : 1237);
result = prime * result + ((offset == null) ? 0 : offset.hashCode());
return result;
}
public static class CacheKey {
public final Class<? extends IConduit> baseType;
public final String className; // used to generate reliable equals /
// hashcode
public final Offset offset;
public final ForgeDirection dir;
public final boolean isStub;
public CacheKey(Class<? extends IConduit> baseType, Offset offset, ForgeDirection dir, boolean isStub) {
this.baseType = baseType;
className = baseType.getCanonicalName();
this.offset = offset;
this.dir = dir;
this.isStub = isStub;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((className == null) ? 0 : className.hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
result = prime * result + (isStub ? 1231 : 1237);
result = prime * result + ((offset == null) ? 0 : offset.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CacheKey other = (CacheKey) obj;
if (className == null) {
if (other.className != null) {
return false;
}
} else if (!className.equals(other.className)) {
return false;
}
if (dir != other.dir) {
return false;
}
if (isStub != other.isStub) {
return false;
}
if (offset != other.offset) {
return false;
}
return true;
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
CacheKey other = (CacheKey) obj;
if(className == null) {
if(other.className != null) {
return false;
}
} else if(!className.equals(other.className)) {
return false;
}
if(dir != other.dir) {
return false;
}
if(isStub != other.isStub) {
return false;
}
if(offset != other.offset) {
return false;
}
return true;
}
}
}
@@ -8,41 +8,39 @@ import crazypants.enderio.conduit.IConduit;
public class CollidableComponent {
public final Class<? extends IConduit> conduitType;
public final BoundingBox bound;
public final ForgeDirection dir;
public final Object data;
public final Class<? extends IConduit> conduitType;
public final BoundingBox bound;
public final ForgeDirection dir;
public final Object data;
public CollidableComponent(Class<? extends IConduit> conduitType, BoundingBox bound, ForgeDirection id,
Object data) {
this.conduitType = conduitType;
this.bound = bound;
this.dir = id;
this.data = data;
}
public CollidableComponent(Class<? extends IConduit> conduitType, BoundingBox bound, ForgeDirection id, Object data) {
this.conduitType = conduitType;
this.bound = bound;
this.dir = id;
this.data = data;
}
@Override
public String toString() {
return "CollidableComponent [conduitType=" + conduitType + ", bound=" + bound + ", id=" + dir + "]";
}
@Override
public String toString() {
return "CollidableComponent [conduitType=" + conduitType + ", bound=" + bound + ", id=" + dir + "]";
}
@Override
public boolean equals(Object obj) {
if (obj instanceof CollidableComponent) {
CollidableComponent other = (CollidableComponent) obj;
return conduitType == other.conduitType && bound.equals(((CollidableComponent) obj).bound)
&& dir == other.dir;
}
return false;
@Override
public boolean equals(Object obj) {
if(obj instanceof CollidableComponent) {
CollidableComponent other = (CollidableComponent) obj;
return conduitType == other.conduitType && bound.equals(((CollidableComponent) obj).bound) && dir == other.dir;
}
return false;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bound == null) ? 0 : bound.hashCode());
result = prime * result + ((conduitType == null) ? 0 : conduitType.getName().hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bound == null) ? 0 : bound.hashCode());
result = prime * result + ((conduitType == null) ? 0 : conduitType.getName().hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
return result;
}
}
@@ -1,6 +1,8 @@
package crazypants.enderio.conduit.geom;
public enum ConduitConnectorType {
INTERNAL,
EXTERNAL
INTERNAL,
EXTERNAL
}
@@ -15,197 +15,194 @@ import crazypants.enderio.conduit.IConduit;
public class ConduitGeometryUtil {
public static final ConduitGeometryUtil instance = new ConduitGeometryUtil();
public static final ConduitGeometryUtil instance = new ConduitGeometryUtil();
public static float STUB_WIDTH = 0.2f;
public static float STUB_HEIGHT = 0.2f;
public static float STUB_WIDTH = 0.2f;
public static float STUB_HEIGHT = 0.2f;
public static float WIDTH;
public static float HEIGHT;
public static float WIDTH;
public static float HEIGHT;
public static float HWIDTH;
public static float HHEIGHT;
public static float HWIDTH;
public static float HHEIGHT;
// All values are for a single conduit core
public static Vector3d CORE_MIN;
public static Vector3d CORE_MAX;
public static BoundingBox CORE_BOUNDS;
// All values are for a single conduit core
public static Vector3d CORE_MIN;
public static Vector3d CORE_MAX;
public static BoundingBox CORE_BOUNDS;
public static final float CONNECTOR_DEPTH = 0.05f;
public static final float CONNECTOR_DEPTH = 0.05f;
private static final Map<ForgeDirection, BoundingBox[]> EXTERNAL_CONNECTOR_BOUNDS = new HashMap<>();
private static Map<ForgeDirection, BoundingBox[]> EXTERNAL_CONNECTOR_BOUNDS = new HashMap<ForgeDirection, BoundingBox[]>();
static {
setupBounds(0.5f);
static {
setupBounds(0.5f);
}
public static void setupBounds(float scale) {
float size = 0.075f + (0.175f * scale);
WIDTH = size;
HEIGHT = size;
HWIDTH = WIDTH / 2;
HHEIGHT = HEIGHT / 2;
CORE_MIN = new Vector3d(0.5f - HWIDTH, 0.5 - HHEIGHT, 0.5 - HWIDTH);
CORE_MAX = new Vector3d(CORE_MIN.x + WIDTH, CORE_MIN.y + HEIGHT, CORE_MIN.z + WIDTH);
CORE_BOUNDS = new BoundingBox(CORE_MIN, CORE_MAX);
float connectorWidth = 0.25f + (scale * 0.5f);
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
EXTERNAL_CONNECTOR_BOUNDS.put(dir, createExternalConnector(dir, CONNECTOR_DEPTH, connectorWidth));
}
}
private static BoundingBox[] createExternalConnector(ForgeDirection dir, float connectorDepth, float connectorWidth) {
BoundingBox[] res = new BoundingBox[2];
float cMin = 0.5f - connectorWidth / 2;
float cMax = 0.5f + connectorWidth / 2;
float dMin = 1 - connectorDepth / 2;
float dMax = 1;
res[0] = createConnectorComponent(dir, cMin, cMax, dMin, dMax);
cMin = 0.5f - connectorWidth / 3;
cMax = 0.5f + connectorWidth / 3;
dMin = 1 - connectorDepth;
dMax = 1 - connectorDepth / 2;
res[1] = createConnectorComponent(dir, cMin, cMax, dMin, dMax);
return res;
}
private static BoundingBox createConnectorComponent(ForgeDirection dir, float cornerMin, float cornerMax, float depthMin, float depthMax) {
float minX = (1 - Math.abs(dir.offsetX)) * cornerMin + dir.offsetX * depthMin;
float minY = (1 - Math.abs(dir.offsetY)) * cornerMin + dir.offsetY * depthMin;
float minZ = (1 - Math.abs(dir.offsetZ)) * cornerMin + dir.offsetZ * depthMin;
float maxX = (1 - Math.abs(dir.offsetX)) * cornerMax + (dir.offsetX * depthMax);
float maxY = (1 - Math.abs(dir.offsetY)) * cornerMax + (dir.offsetY * depthMax);
float maxZ = (1 - Math.abs(dir.offsetZ)) * cornerMax + (dir.offsetZ * depthMax);
minX = fix(minX);
minY = fix(minY);
minZ = fix(minZ);
maxX = fix(maxX);
maxY = fix(maxY);
maxZ = fix(maxZ);
BoundingBox bb = new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
bb = bb.fixMinMax();
return bb;
}
private static float fix(float val) {
return val < 0 ? 1 + val : val;
}
private Map<GeometryKey, BoundingBox> boundsCache = new HashMap<GeometryKey, BoundingBox>();
private EnumMap<ConduitConnectorType, BoundingBox> connectorBounds = new EnumMap<ConduitConnectorType, BoundingBox>(ConduitConnectorType.class);
private ConduitGeometryUtil() {
}
public BoundingBox getExternalConnectorBoundingBox(ForgeDirection dir) {
return getExternalConnectorBoundingBoxes(dir)[0];
}
public BoundingBox[] getExternalConnectorBoundingBoxes(ForgeDirection dir) {
return EXTERNAL_CONNECTOR_BOUNDS.get(dir);
}
public BoundingBox getBoundingBox(Class<? extends IConduit> type, ForgeDirection dir, boolean isStub, Offset offset) {
GeometryKey key = new GeometryKey(dir, isStub, offset, type);
BoundingBox result = boundsCache.get(key);
if(result == null) {
result = createConduitBounds(type, key);
boundsCache.put(key, result);
}
return result;
}
public Vector3d getTranslation(ForgeDirection dir, Offset offset) {
Vector3d result = new Vector3d(offset.xOffset, offset.yOffset, offset.zOffset);
result.scale(WIDTH);
return result;
}
public BoundingBox createBoundsForConnectionController(ForgeDirection dir, Offset offset) {
Vector3d nonUniformScale = ForgeDirectionOffsets.forDirCopy(dir);
nonUniformScale.scale(0.5);
nonUniformScale.x = 0.8 * (1 - Math.abs(nonUniformScale.x));
nonUniformScale.y = 0.8 * (1 - Math.abs(nonUniformScale.y));
nonUniformScale.z = 0.8 * (1 - Math.abs(nonUniformScale.z));
BoundingBox bb = CORE_BOUNDS;
bb = bb.scale(nonUniformScale.x, nonUniformScale.y, nonUniformScale.z);
double offsetFromEnd = Math.min(bb.sizeX(), bb.sizeY());
offsetFromEnd = Math.min(offsetFromEnd, bb.sizeZ());
offsetFromEnd = Math.max(offsetFromEnd, 0.075);
double transMag = 0.5 - (offsetFromEnd * 1.2);
Vector3d trans = ForgeDirectionOffsets.forDirCopy(dir);
trans.scale(transMag);
bb = bb.translate(trans);
bb = bb.translate(getTranslation(dir, offset));
return bb;
}
private BoundingBox createConduitBounds(Class<? extends IConduit> type, GeometryKey key) {
return createConduitBounds(type, key.dir, key.isStub, key.offset);
}
private BoundingBox createConduitBounds(Class<? extends IConduit> type, ForgeDirection dir, boolean isStub, Offset offset) {
BoundingBox bb = CORE_BOUNDS;
Vector3d min = bb.getMin();
Vector3d max = bb.getMax();
switch (dir) {
case WEST:
min.x = isStub ? Math.max(0, bb.minX - STUB_WIDTH) : 0;
max.x = bb.minX;
break;
case EAST:
min.x = bb.maxX;
max.x = isStub ? Math.min(1, bb.maxX + STUB_WIDTH) : 1;
break;
case DOWN:
min.y = isStub ? Math.max(0, bb.minY - STUB_HEIGHT) : 0;
max.y = bb.minY;
break;
case UP:
max.y = isStub ? Math.min(1, bb.maxY + STUB_HEIGHT) : 1;
min.y = bb.maxY;
break;
case NORTH:
min.z = isStub ? Math.max(0.0F, bb.minZ - STUB_WIDTH) : 0;
max.z = bb.minZ;
break;
case SOUTH:
max.z = isStub ? Math.min(1F, bb.maxZ + STUB_WIDTH) : 1;
min.z = bb.maxZ;
break;
default:
break;
}
public static void setupBounds(float scale) {
float size = 0.075f + (0.175f * scale);
Vector3d trans = getTranslation(dir, offset);
min.add(trans);
max.add(trans);
bb = new BoundingBox(VecmathUtil.clamp(min, 0, 1), VecmathUtil.clamp(max, 0, 1));
return bb;
}
WIDTH = size;
HEIGHT = size;
HWIDTH = WIDTH / 2;
HHEIGHT = HEIGHT / 2;
CORE_MIN = new Vector3d(0.5f - HWIDTH, 0.5 - HHEIGHT, 0.5 - HWIDTH);
CORE_MAX = new Vector3d(CORE_MIN.x + WIDTH, CORE_MIN.y + HEIGHT, CORE_MIN.z + WIDTH);
CORE_BOUNDS = new BoundingBox(CORE_MIN, CORE_MAX);
float connectorWidth = 0.25f + (scale * 0.5f);
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
EXTERNAL_CONNECTOR_BOUNDS.put(dir, createExternalConnector(dir, CONNECTOR_DEPTH, connectorWidth));
}
}
private static BoundingBox[] createExternalConnector(ForgeDirection dir, float connectorDepth,
float connectorWidth) {
BoundingBox[] res = new BoundingBox[2];
float cMin = 0.5f - connectorWidth / 2;
float cMax = 0.5f + connectorWidth / 2;
float dMin = 1 - connectorDepth / 2;
float dMax = 1;
res[0] = createConnectorComponent(dir, cMin, cMax, dMin, dMax);
cMin = 0.5f - connectorWidth / 3;
cMax = 0.5f + connectorWidth / 3;
dMin = 1 - connectorDepth;
dMax = 1 - connectorDepth / 2;
res[1] = createConnectorComponent(dir, cMin, cMax, dMin, dMax);
return res;
}
private static BoundingBox createConnectorComponent(ForgeDirection dir, float cornerMin, float cornerMax,
float depthMin, float depthMax) {
float minX = (1 - Math.abs(dir.offsetX)) * cornerMin + dir.offsetX * depthMin;
float minY = (1 - Math.abs(dir.offsetY)) * cornerMin + dir.offsetY * depthMin;
float minZ = (1 - Math.abs(dir.offsetZ)) * cornerMin + dir.offsetZ * depthMin;
float maxX = (1 - Math.abs(dir.offsetX)) * cornerMax + (dir.offsetX * depthMax);
float maxY = (1 - Math.abs(dir.offsetY)) * cornerMax + (dir.offsetY * depthMax);
float maxZ = (1 - Math.abs(dir.offsetZ)) * cornerMax + (dir.offsetZ * depthMax);
minX = fix(minX);
minY = fix(minY);
minZ = fix(minZ);
maxX = fix(maxX);
maxY = fix(maxY);
maxZ = fix(maxZ);
BoundingBox bb = new BoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
bb = bb.fixMinMax();
return bb;
}
private static float fix(float val) {
return val < 0 ? 1 + val : val;
}
private final Map<GeometryKey, BoundingBox> boundsCache = new HashMap<>();
private final EnumMap<ConduitConnectorType, BoundingBox> connectorBounds = new EnumMap<>(
ConduitConnectorType.class);
private ConduitGeometryUtil() {}
public BoundingBox getExternalConnectorBoundingBox(ForgeDirection dir) {
return getExternalConnectorBoundingBoxes(dir)[0];
}
public BoundingBox[] getExternalConnectorBoundingBoxes(ForgeDirection dir) {
return EXTERNAL_CONNECTOR_BOUNDS.get(dir);
}
public BoundingBox getBoundingBox(Class<? extends IConduit> type, ForgeDirection dir, boolean isStub,
Offset offset) {
GeometryKey key = new GeometryKey(dir, isStub, offset, type);
BoundingBox result = boundsCache.get(key);
if (result == null) {
result = createConduitBounds(type, key);
boundsCache.put(key, result);
}
return result;
}
public Vector3d getTranslation(ForgeDirection dir, Offset offset) {
Vector3d result = new Vector3d(offset.xOffset, offset.yOffset, offset.zOffset);
result.scale(WIDTH);
return result;
}
public BoundingBox createBoundsForConnectionController(ForgeDirection dir, Offset offset) {
Vector3d nonUniformScale = ForgeDirectionOffsets.forDirCopy(dir);
nonUniformScale.scale(0.5);
nonUniformScale.x = 0.8 * (1 - Math.abs(nonUniformScale.x));
nonUniformScale.y = 0.8 * (1 - Math.abs(nonUniformScale.y));
nonUniformScale.z = 0.8 * (1 - Math.abs(nonUniformScale.z));
BoundingBox bb = CORE_BOUNDS;
bb = bb.scale(nonUniformScale.x, nonUniformScale.y, nonUniformScale.z);
double offsetFromEnd = Math.min(bb.sizeX(), bb.sizeY());
offsetFromEnd = Math.min(offsetFromEnd, bb.sizeZ());
offsetFromEnd = Math.max(offsetFromEnd, 0.075);
double transMag = 0.5 - (offsetFromEnd * 1.2);
Vector3d trans = ForgeDirectionOffsets.forDirCopy(dir);
trans.scale(transMag);
bb = bb.translate(trans);
bb = bb.translate(getTranslation(dir, offset));
return bb;
}
private BoundingBox createConduitBounds(Class<? extends IConduit> type, GeometryKey key) {
return createConduitBounds(type, key.dir, key.isStub, key.offset);
}
private BoundingBox createConduitBounds(Class<? extends IConduit> type, ForgeDirection dir, boolean isStub,
Offset offset) {
BoundingBox bb = CORE_BOUNDS;
Vector3d min = bb.getMin();
Vector3d max = bb.getMax();
switch (dir) {
case WEST:
min.x = isStub ? Math.max(0, bb.minX - STUB_WIDTH) : 0;
max.x = bb.minX;
break;
case EAST:
min.x = bb.maxX;
max.x = isStub ? Math.min(1, bb.maxX + STUB_WIDTH) : 1;
break;
case DOWN:
min.y = isStub ? Math.max(0, bb.minY - STUB_HEIGHT) : 0;
max.y = bb.minY;
break;
case UP:
max.y = isStub ? Math.min(1, bb.maxY + STUB_HEIGHT) : 1;
min.y = bb.maxY;
break;
case NORTH:
min.z = isStub ? Math.max(0.0F, bb.minZ - STUB_WIDTH) : 0;
max.z = bb.minZ;
break;
case SOUTH:
max.z = isStub ? Math.min(1F, bb.maxZ + STUB_WIDTH) : 1;
min.z = bb.maxZ;
break;
default:
break;
}
Vector3d trans = getTranslation(dir, offset);
min.add(trans);
max.add(trans);
bb = new BoundingBox(VecmathUtil.clamp(min, 0, 1), VecmathUtil.clamp(max, 0, 1));
return bb;
}
}
@@ -1,7 +1,5 @@
package crazypants.enderio.conduit.geom;
import static com.enderio.core.common.util.ForgeDirectionOffsets.offsetScaled;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
@@ -19,121 +17,123 @@ import com.enderio.core.client.render.VertexTranslation;
import com.enderio.core.common.vecmath.Vector3d;
import com.enderio.core.common.vecmath.Vertex;
import static com.enderio.core.common.util.ForgeDirectionOffsets.offsetScaled;
public class ConnectionModeGeometry {
private static final EnumMap<ForgeDirection, List<Vertex>> VERTS = new EnumMap<>(ForgeDirection.class);
private static final EnumMap<ForgeDirection, List<Vertex>> VERTS = new EnumMap<ForgeDirection, List<Vertex>>(ForgeDirection.class);
static {
float scale = 0.9f;
BoundingBox refBB = ConduitGeometryUtil.CORE_BOUNDS;
refBB = refBB.scale(scale, scale, scale);
refBB = refBB.scale(scale, 1, 1);
static {
double offset = (ConduitGeometryUtil.HWIDTH * scale * scale) + ConduitGeometryUtil.CONNECTOR_DEPTH;
float scale = 0.9f;
BoundingBox refBB = ConduitGeometryUtil.CORE_BOUNDS;
refBB = refBB.scale(scale, scale, scale);
refBB = refBB.scale(scale, 1, 1);
ForgeDirection dir;
Vector3d trans;
double offset = (ConduitGeometryUtil.HWIDTH * scale * scale) + ConduitGeometryUtil.CONNECTOR_DEPTH;
VertexRotation vrot = new VertexRotation(Math.PI / 2, new Vector3d(0, 1, 0), new Vector3d(0.5, 0.5, 0.5));
VertexTranslation vtrans = new VertexTranslation(0, 0, 0);
VertexTransformComposite xform = new VertexTransformComposite(vrot, vtrans);
ForgeDirection dir;
Vector3d trans;
dir = ForgeDirection.SOUTH;
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
VertexRotation vrot = new VertexRotation(Math.PI / 2, new Vector3d(0, 1, 0), new Vector3d(0.5, 0.5, 0.5));
VertexTranslation vtrans = new VertexTranslation(0, 0, 0);
VertexTransformComposite xform = new VertexTransformComposite(vrot, vtrans);
dir = ForgeDirection.NORTH;
vrot.setAngle(Math.PI + Math.PI / 2);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.SOUTH;
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.EAST;
vrot.setAngle(Math.PI);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.NORTH;
vrot.setAngle(Math.PI + Math.PI / 2);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.WEST;
vrot.setAngle(0);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.EAST;
vrot.setAngle(Math.PI);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
vrot.setAxis(new Vector3d(0, 0, 1));
dir = ForgeDirection.WEST;
vrot.setAngle(0);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.UP;
vrot.setAngle(-Math.PI / 2);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
vrot.setAxis(new Vector3d(0, 0, 1));
dir = ForgeDirection.DOWN;
vrot.setAngle(Math.PI / 2);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.UP;
vrot.setAngle(-Math.PI / 2);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
dir = ForgeDirection.DOWN;
vrot.setAngle(Math.PI / 2);
trans = offsetScaled(dir, 0.5);
trans.sub(offsetScaled(dir, offset));
vtrans.set(trans);
VERTS.put(dir, createVerticesForDir(refBB, xform));
}
private static List<Vertex> createVerticesForDir(BoundingBox refBB, VertexTransform xform) {
List<Vertex> result = new ArrayList<Vertex>(24);
for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) {
result.addAll(refBB.getCornersWithUvForFace(face));
}
for (Vertex v : result) {
xform.apply(v.xyz);
xform.applyToNormal(v.normal);
}
return result;
}
public static void renderModeConnector(ForgeDirection dir, Offset offset, IIcon tex, boolean tintSides) {
List<Vertex> verts = VERTS.get(dir);
if (verts == null) {
return;
}
private static List<Vertex> createVerticesForDir(BoundingBox refBB, VertexTransform xform) {
List<Vertex> result = new ArrayList<>(24);
for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) {
result.addAll(refBB.getCornersWithUvForFace(face));
Vector3d trans = ConduitGeometryUtil.instance.getTranslation(dir, offset);
float uWidth = tex.getMaxU() - tex.getMinU();
float uScale = uWidth * 0.64f;
float minU = tex.getMinU() + (uWidth - uScale);
float vScale = tex.getMaxV() - tex.getMinV();
Tessellator tes = Tessellator.instance;
for (Vertex v : verts) {
if (tintSides) {
float cm = 1;
if (v.ny() > 0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.UP);
} else if (v.ny() < -0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.DOWN);
} else if (v.nx() > 0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.EAST);
} else if (v.nx() < -0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.WEST);
} else if (v.nz() > 0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.SOUTH);
} else if (v.nz() < -0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.NORTH);
}
for (Vertex v : result) {
xform.apply(v.xyz);
xform.applyToNormal(v.normal);
}
return result;
tes.setColorOpaque_F(cm, cm, cm);
}
tes.setNormal(v.nx(), v.ny(), v.nz());
tes.addVertexWithUV(v.x() + trans.x, v.y() + trans.y, v.z() + trans.z, minU + (v.u() * uScale), tex.getMinV() + (v.v() * vScale));
}
public static void renderModeConnector(ForgeDirection dir, Offset offset, IIcon tex, boolean tintSides) {
List<Vertex> verts = VERTS.get(dir);
if (verts == null) {
return;
}
}
Vector3d trans = ConduitGeometryUtil.instance.getTranslation(dir, offset);
float uWidth = tex.getMaxU() - tex.getMinU();
float uScale = uWidth * 0.64f;
float minU = tex.getMinU() + (uWidth - uScale);
float vScale = tex.getMaxV() - tex.getMinV();
Tessellator tes = Tessellator.instance;
for (Vertex v : verts) {
if (tintSides) {
float cm = 1;
if (v.ny() > 0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.UP);
} else if (v.ny() < -0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.DOWN);
} else if (v.nx() > 0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.EAST);
} else if (v.nx() < -0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.WEST);
} else if (v.nz() > 0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.SOUTH);
} else if (v.nz() < -0.1) {
cm = RenderUtil.getColorMultiplierForFace(ForgeDirection.NORTH);
}
tes.setColorOpaque_F(cm, cm, cm);
}
tes.setNormal(v.nx(), v.ny(), v.nz());
tes.addVertexWithUV(
v.x() + trans.x,
v.y() + trans.y,
v.z() + trans.z,
minU + (v.u() * uScale),
tex.getMinV() + (v.v() * vScale));
}
}
}
@@ -1,46 +1,54 @@
package crazypants.enderio.conduit.geom;
import net.minecraftforge.common.util.ForgeDirection;
import crazypants.enderio.conduit.IConduit;
public final class GeometryKey {
public final ForgeDirection dir;
public final boolean isStub;
public final Offset offset;
public final String className;
public final ForgeDirection dir;
public final boolean isStub;
public final Offset offset;
public final String className;
public GeometryKey(ForgeDirection dir, boolean isStub, Offset offset, Class<? extends IConduit> type) {
this.dir = dir;
this.isStub = isStub;
this.offset = offset;
className = type != null ? type.getName() : null;
}
public GeometryKey(ForgeDirection dir, boolean isStub, Offset offset, Class<? extends IConduit> type) {
this.dir = dir;
this.isStub = isStub;
this.offset = offset;
className = type != null ? type.getName() : null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((className == null) ? 0 : className.hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
result = prime * result + (isStub ? 1231 : 1237);
result = prime * result + ((offset == null) ? 0 : offset.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((className == null) ? 0 : className.hashCode());
result = prime * result + ((dir == null) ? 0 : dir.hashCode());
result = prime * result + (isStub ? 1231 : 1237);
result = prime * result + ((offset == null) ? 0 : offset.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
GeometryKey other = (GeometryKey) obj;
if(className == null) {
if(other.className != null)
return false;
} else if(!className.equals(other.className))
return false;
if(dir != other.dir)
return false;
if(isStub != other.isStub)
return false;
if(offset != other.offset)
return false;
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
GeometryKey other = (GeometryKey) obj;
if (className == null) {
if (other.className != null) return false;
} else if (!className.equals(other.className)) return false;
if (dir != other.dir) return false;
if (isStub != other.isStub) return false;
if (offset != other.offset) return false;
return true;
}
}
@@ -4,50 +4,51 @@ import net.minecraftforge.common.util.ForgeDirection;
/**
* Offset vectors are based on Y up.
*
*
* @author brad
*/
public enum Offset {
NONE(0, 0, 0),
UP(ForgeDirection.UP),
DOWN(ForgeDirection.DOWN),
EAST(ForgeDirection.EAST),
WEST(ForgeDirection.WEST),
SOUTH(ForgeDirection.SOUTH),
NORTH(ForgeDirection.NORTH),
EAST_UP(ForgeDirection.EAST, ForgeDirection.UP),
WEST_UP(ForgeDirection.WEST, ForgeDirection.UP),
SOUTH_UP(ForgeDirection.SOUTH, ForgeDirection.UP),
NORTH_UP(ForgeDirection.NORTH, ForgeDirection.UP),
EAST_DOWN(ForgeDirection.EAST, ForgeDirection.DOWN),
WEST_DOWN(ForgeDirection.WEST, ForgeDirection.DOWN),
SOUTH_DOWN(ForgeDirection.SOUTH, ForgeDirection.DOWN),
NORTH_DOWN(ForgeDirection.NORTH, ForgeDirection.DOWN),
NORTH_EAST(ForgeDirection.NORTH, ForgeDirection.EAST),
NORTH_WEST(ForgeDirection.NORTH, ForgeDirection.WEST),
SOUTH_EAST(ForgeDirection.SOUTH, ForgeDirection.EAST),
SOUTH_WEST(ForgeDirection.SOUTH, ForgeDirection.WEST);
NONE(0, 0, 0),
UP(ForgeDirection.UP),
DOWN(ForgeDirection.DOWN),
EAST(ForgeDirection.EAST),
WEST(ForgeDirection.WEST),
SOUTH(ForgeDirection.SOUTH),
NORTH(ForgeDirection.NORTH),
EAST_UP(ForgeDirection.EAST, ForgeDirection.UP),
WEST_UP(ForgeDirection.WEST, ForgeDirection.UP),
SOUTH_UP(ForgeDirection.SOUTH, ForgeDirection.UP),
NORTH_UP(ForgeDirection.NORTH, ForgeDirection.UP),
EAST_DOWN(ForgeDirection.EAST, ForgeDirection.DOWN),
WEST_DOWN(ForgeDirection.WEST, ForgeDirection.DOWN),
SOUTH_DOWN(ForgeDirection.SOUTH, ForgeDirection.DOWN),
NORTH_DOWN(ForgeDirection.NORTH, ForgeDirection.DOWN),
NORTH_EAST(ForgeDirection.NORTH, ForgeDirection.EAST),
NORTH_WEST(ForgeDirection.NORTH, ForgeDirection.WEST),
SOUTH_EAST(ForgeDirection.SOUTH, ForgeDirection.EAST),
SOUTH_WEST(ForgeDirection.SOUTH, ForgeDirection.WEST);
public final int xOffset;
public final int yOffset;
public final int zOffset;
public final int xOffset;
public final int yOffset;
public final int zOffset;
private Offset(ForgeDirection dir) {
xOffset = dir.offsetX;
yOffset = dir.offsetY;
zOffset = dir.offsetZ;
}
private Offset(ForgeDirection dir) {
xOffset = dir.offsetX;
yOffset = dir.offsetY;
zOffset = dir.offsetZ;
}
private Offset(ForgeDirection dir, ForgeDirection yDir) {
xOffset = dir.offsetX + yDir.offsetX;
yOffset = dir.offsetY + yDir.offsetY;
zOffset = dir.offsetZ + yDir.offsetZ;
}
private Offset(ForgeDirection dir, ForgeDirection yDir) {
xOffset = dir.offsetX + yDir.offsetX;
yOffset = dir.offsetY + yDir.offsetY;
zOffset = dir.offsetZ + yDir.offsetZ;
}
private Offset(int xOffset, int yOffset, int zOffset) {
this.xOffset = xOffset;
this.yOffset = yOffset;
this.zOffset = zOffset;
}
private Offset(int xOffset, int yOffset, int zOffset) {
this.xOffset = xOffset;
this.yOffset = yOffset;
this.zOffset = zOffset;
}
}
@@ -4,7 +4,6 @@ import java.util.HashMap;
import java.util.Map;
import net.minecraftforge.common.util.ForgeDirection;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.gas.IGasConduit;
import crazypants.enderio.conduit.item.IItemConduit;
@@ -16,133 +15,135 @@ import crazypants.enderio.conduit.redstone.IRedstoneConduit;
public class Offsets {
private static final Map<OffsetKey, Offset> OFFSETS = new HashMap<>();
private static Map<OffsetKey, Offset> OFFSETS = new HashMap<OffsetKey, Offset>();
static {
OFFSETS.put(key(IRedstoneConduit.class, Axis.NONE), Offset.UP);
OFFSETS.put(key(IRedstoneConduit.class, Axis.X), Offset.UP);
OFFSETS.put(key(IRedstoneConduit.class, Axis.Y), Offset.NORTH);
OFFSETS.put(key(IRedstoneConduit.class, Axis.Z), Offset.UP);
static {
OFFSETS.put(key(IRedstoneConduit.class, Axis.NONE), Offset.UP);
OFFSETS.put(key(IRedstoneConduit.class, Axis.X), Offset.UP);
OFFSETS.put(key(IRedstoneConduit.class, Axis.Y), Offset.NORTH);
OFFSETS.put(key(IRedstoneConduit.class, Axis.Z), Offset.UP);
OFFSETS.put(key(IPowerConduit.class, Axis.NONE), Offset.DOWN);
OFFSETS.put(key(IPowerConduit.class, Axis.X), Offset.DOWN);
OFFSETS.put(key(IPowerConduit.class, Axis.Y), Offset.SOUTH);
OFFSETS.put(key(IPowerConduit.class, Axis.Z), Offset.DOWN);
OFFSETS.put(key(IPowerConduit.class, Axis.NONE), Offset.DOWN);
OFFSETS.put(key(IPowerConduit.class, Axis.X), Offset.DOWN);
OFFSETS.put(key(IPowerConduit.class, Axis.Y), Offset.SOUTH);
OFFSETS.put(key(IPowerConduit.class, Axis.Z), Offset.DOWN);
OFFSETS.put(key(ILiquidConduit.class, Axis.NONE), Offset.WEST);
OFFSETS.put(key(ILiquidConduit.class, Axis.X), Offset.NORTH);
OFFSETS.put(key(ILiquidConduit.class, Axis.Y), Offset.WEST);
OFFSETS.put(key(ILiquidConduit.class, Axis.Z), Offset.WEST);
OFFSETS.put(key(ILiquidConduit.class, Axis.NONE), Offset.WEST);
OFFSETS.put(key(ILiquidConduit.class, Axis.X), Offset.NORTH);
OFFSETS.put(key(ILiquidConduit.class, Axis.Y), Offset.WEST);
OFFSETS.put(key(ILiquidConduit.class, Axis.Z), Offset.WEST);
OFFSETS.put(key(IItemConduit.class, Axis.NONE), Offset.EAST);
OFFSETS.put(key(IItemConduit.class, Axis.X), Offset.SOUTH);
OFFSETS.put(key(IItemConduit.class, Axis.Y), Offset.EAST);
OFFSETS.put(key(IItemConduit.class, Axis.Z), Offset.EAST);
OFFSETS.put(key(IItemConduit.class, Axis.NONE), Offset.EAST);
OFFSETS.put(key(IItemConduit.class, Axis.X), Offset.SOUTH);
OFFSETS.put(key(IItemConduit.class, Axis.Y), Offset.EAST);
OFFSETS.put(key(IItemConduit.class, Axis.Z), Offset.EAST);
OFFSETS.put(key(IGasConduit.class, Axis.NONE), Offset.NORTH_UP);
OFFSETS.put(key(IGasConduit.class, Axis.X), Offset.NORTH_UP);
OFFSETS.put(key(IGasConduit.class, Axis.Y), Offset.NORTH_WEST);
OFFSETS.put(key(IGasConduit.class, Axis.Z), Offset.WEST_UP);
OFFSETS.put(key(IGasConduit.class, Axis.NONE), Offset.NORTH_UP);
OFFSETS.put(key(IGasConduit.class, Axis.X), Offset.NORTH_UP);
OFFSETS.put(key(IGasConduit.class, Axis.Y), Offset.NORTH_WEST);
OFFSETS.put(key(IGasConduit.class, Axis.Z), Offset.WEST_UP);
OFFSETS.put(key(IMEConduit.class, Axis.NONE), Offset.SOUTH_UP);
OFFSETS.put(key(IMEConduit.class, Axis.X), Offset.SOUTH_UP);
OFFSETS.put(key(IMEConduit.class, Axis.Y), Offset.NORTH_EAST);
OFFSETS.put(key(IMEConduit.class, Axis.Z), Offset.EAST_UP);
OFFSETS.put(key(IMEConduit.class, Axis.NONE), Offset.SOUTH_UP);
OFFSETS.put(key(IMEConduit.class, Axis.X), Offset.SOUTH_UP);
OFFSETS.put(key(IMEConduit.class, Axis.Y), Offset.NORTH_EAST);
OFFSETS.put(key(IMEConduit.class, Axis.Z), Offset.EAST_UP);
OFFSETS.put(key(IOCConduit.class, Axis.NONE), Offset.NORTH_DOWN);
OFFSETS.put(key(IOCConduit.class, Axis.X), Offset.NORTH_DOWN);
OFFSETS.put(key(IOCConduit.class, Axis.Y), Offset.SOUTH_WEST);
OFFSETS.put(key(IOCConduit.class, Axis.Z), Offset.WEST_DOWN);
OFFSETS.put(key(IOCConduit.class, Axis.NONE), Offset.NORTH_DOWN);
OFFSETS.put(key(IOCConduit.class, Axis.X), Offset.NORTH_DOWN);
OFFSETS.put(key(IOCConduit.class, Axis.Y), Offset.SOUTH_WEST);
OFFSETS.put(key(IOCConduit.class, Axis.Z), Offset.WEST_DOWN);
// OFFSETS.put(key(IxConduit.class, Axis.NONE), Offset.SOUTH_DOWN);
// OFFSETS.put(key(IxConduit.class, Axis.X), Offset.SOUTH_DOWN);
// OFFSETS.put(key(IxConduit.class, Axis.Y), Offset.SOUTH_EAST);
// OFFSETS.put(key(IxConduit.class, Axis.Z), Offset.EAST_DOWN);
// OFFSETS.put(key(IxConduit.class, Axis.NONE), Offset.SOUTH_DOWN);
// OFFSETS.put(key(IxConduit.class, Axis.X), Offset.SOUTH_DOWN);
// OFFSETS.put(key(IxConduit.class, Axis.Y), Offset.SOUTH_EAST);
// OFFSETS.put(key(IxConduit.class, Axis.Z), Offset.EAST_DOWN);
}
public static Offset get(Class<? extends IConduit> type, ForgeDirection dir) {
Offset res = OFFSETS.get(key(type, getAxisForDir(dir)));
if(res == null) {
res = Offset.NONE;
}
return res;
}
public static OffsetKey key(Class<? extends IConduit> type, Axis axis) {
return new OffsetKey(type, axis);
}
public static Axis getAxisForDir(ForgeDirection dir) {
if(dir == ForgeDirection.UNKNOWN) {
return Axis.NONE;
}
if(dir == ForgeDirection.EAST || dir == ForgeDirection.WEST) {
return Axis.X;
}
if(dir == ForgeDirection.UP || dir == ForgeDirection.DOWN) {
return Axis.Y;
}
if(dir == ForgeDirection.NORTH || dir == ForgeDirection.SOUTH) {
return Axis.Z;
}
return Axis.NONE;
}
public static enum Axis {
NONE,
X,
Y,
Z
}
public static class OffsetKey {
String typeName;
Axis axis;
private OffsetKey(Class<? extends IConduit> type, Axis axis) {
this.typeName = type.getCanonicalName();
this.axis = axis;
}
public static Offset get(Class<? extends IConduit> type, ForgeDirection dir) {
Offset res = OFFSETS.get(key(type, getAxisForDir(dir)));
if (res == null) {
res = Offset.NONE;
}
return res;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((axis == null) ? 0 : axis.hashCode());
result = prime * result + ((typeName == null) ? 0 : typeName.hashCode());
return result;
}
public static OffsetKey key(Class<? extends IConduit> type, Axis axis) {
return new OffsetKey(type, axis);
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
OffsetKey other = (OffsetKey) obj;
if(axis != other.axis) {
return false;
}
if(typeName == null) {
if(other.typeName != null) {
return false;
}
} else if(!typeName.equals(other.typeName)) {
return false;
}
return true;
}
public static Axis getAxisForDir(ForgeDirection dir) {
if (dir == ForgeDirection.UNKNOWN) {
return Axis.NONE;
}
if (dir == ForgeDirection.EAST || dir == ForgeDirection.WEST) {
return Axis.X;
}
if (dir == ForgeDirection.UP || dir == ForgeDirection.DOWN) {
return Axis.Y;
}
if (dir == ForgeDirection.NORTH || dir == ForgeDirection.SOUTH) {
return Axis.Z;
}
return Axis.NONE;
@Override
public String toString() {
return "OffsetKey [typeName=" + typeName + ", axis=" + axis + "]";
}
public static enum Axis {
NONE,
X,
Y,
Z
}
}
public static class OffsetKey {
String typeName;
Axis axis;
private OffsetKey(Class<? extends IConduit> type, Axis axis) {
this.typeName = type.getCanonicalName();
this.axis = axis;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((axis == null) ? 0 : axis.hashCode());
result = prime * result + ((typeName == null) ? 0 : typeName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OffsetKey other = (OffsetKey) obj;
if (axis != other.axis) {
return false;
}
if (typeName == null) {
if (other.typeName != null) {
return false;
}
} else if (!typeName.equals(other.typeName)) {
return false;
}
return true;
}
@Override
public String toString() {
return "OffsetKey [typeName=" + typeName + ", axis=" + axis + "]";
}
}
}
@@ -1,342 +1,175 @@
package crazypants.enderio.conduit.gui;
import java.awt.Color;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.annotation.Nonnull;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import com.enderio.core.api.client.gui.ITabPanel;
import com.enderio.core.api.client.render.IWidgetIcon;
import com.enderio.core.client.gui.button.CheckBox;
import com.enderio.core.client.gui.widget.GuiToolTip;
import com.enderio.core.client.handlers.SpecialTooltipHandler;
import com.enderio.core.client.gui.button.MultiIconButton;
import com.enderio.core.client.render.ColorUtil;
import crazypants.enderio.EnderIO;
import crazypants.enderio.conduit.ConnectionMode;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.item.FunctionUpgrade;
import crazypants.enderio.conduit.packet.PacketConnectionMode;
import crazypants.enderio.gui.IconEIO;
import crazypants.enderio.network.PacketHandler;
public class BaseSettingsPanel implements ITabPanel {
static final int ID_INSERT_ENABLED = 327;
static final int ID_EXTRACT_ENABLED = 328;
protected static final int ID_INSERT_FILTER_OPTIONS = 329;
protected static final int ID_EXTRACT_FILTER_OPTIONS = 330;
protected static final int ID_ENABLED = 331;
static final int PREV_MODE_B = 327;
static final int NEXT_MODE_B = 328;
protected final @Nonnull IWidgetIcon icon;
protected final @Nonnull GuiExternalConnection gui;
protected @Nonnull IConduit con;
protected final @Nonnull String typeName;
protected final @Nonnull ResourceLocation texture;
protected final IconEIO icon;
protected final GuiExternalConnection gui;
protected final IConduit con;
protected final String typeName;
protected ConnectionMode oldConnectionMode;
protected MultiIconButton leftArrow;
protected MultiIconButton rightArrow;
protected String modeLabel;
private final @Nonnull String inputHeading;
private final @Nonnull String outputHeading;
protected int left = 0;
protected int top = 0;
protected int width = 0;
protected int height = 0;
private boolean insertEnabled = false;
private boolean extractEnabled = false;
protected int gap = 5;
private boolean enabled = false;
protected int customTop = 0;
private final @Nonnull CheckBox extractEnabledB;
private final @Nonnull CheckBox insertEnabledB;
protected BaseSettingsPanel(IconEIO icon, String typeName, GuiExternalConnection gui, IConduit con) {
this.icon = icon;
this.typeName = typeName;
this.gui = gui;
this.con = con;
private final @Nonnull CheckBox enabledB;
modeLabel = EnderIO.lang.localize("gui.conduit.ioMode");
protected int left = 0;
protected int top = 0;
protected int width = 0;
protected int height = 0;
protected int rightColumn = 112;
protected int leftColumn = 22;
FontRenderer fr = Minecraft.getMinecraft().fontRenderer;
int x = gap * 3 + fr.getStringWidth(modeLabel);
int y = 8;// + fr.FONT_HEIGHT;
protected int gap = 5;
leftArrow = MultiIconButton.createLeftArrowButton(gui, PREV_MODE_B, x, y);
protected int customTop = 0;
x += leftArrow.getWidth() + gap + getLongestModeStringWidth() + gap;
rightArrow = MultiIconButton.createRightArrowButton(gui, NEXT_MODE_B, x, y);
protected int textureHeight = 166 + 29;
customTop = top + gap * 5 + fr.FONT_HEIGHT * 2;
customTop -= 16;
//customTop = top;
private final @Nonnull GuiToolTip speedUpgradeTooltip;
private final @Nonnull GuiToolTip functionUpgradeTooltip;
protected @Nonnull GuiToolTip filterExtractUpgradeTooltip;
protected @Nonnull GuiToolTip filterInsertUpgradeTooltip;
}
protected BaseSettingsPanel(@Nonnull IWidgetIcon icon, @Nonnull String typeName, @Nonnull GuiExternalConnection gui,
@Nonnull IConduit con) {
this(icon, typeName, gui, con, "externalConduitConnection");
@Override
public void onGuiInit(int left, int top, int width, int height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
leftArrow.onGuiInit();
rightArrow.onGuiInit();
connectionModeChanged(con.getConnectionMode(gui.getDir()));
initCustomOptions();
}
protected void initCustomOptions() {
}
@Override
public void deactivate() {
}
@Override
public void mouseClicked(int x, int y, int par3) {
}
@Override
public void keyTyped(char par1, int par2) {
}
@Override
public void updateScreen() {
}
@Override
public IWidgetIcon getIcon() {
return icon;
}
@Override
public void actionPerformed(GuiButton guiButton) {
if(guiButton.id == PREV_MODE_B) {
con.setConnectionMode(gui.getDir(), con.getPreviousConnectionMode(gui.getDir()));
PacketHandler.INSTANCE.sendToServer(new PacketConnectionMode(con, gui.getDir()));
connectionModeChanged(con.getConnectionMode(gui.getDir()));
} else if(guiButton.id == NEXT_MODE_B) {
con.setConnectionMode(gui.getDir(), con.getNextConnectionMode(gui.getDir()));
PacketHandler.INSTANCE.sendToServer(new PacketConnectionMode(con, gui.getDir()));
connectionModeChanged(con.getConnectionMode(gui.getDir()));
}
}
protected BaseSettingsPanel(@Nonnull IWidgetIcon icon, @Nonnull String typeName, @Nonnull GuiExternalConnection gui,
@Nonnull IConduit con, @Nonnull String texture) {
this.icon = icon;
this.typeName = typeName;
this.gui = gui;
this.con = con;
this.texture = EnderIO.proxy.getGuiTexture(texture);
protected void connectionModeChanged(ConnectionMode conectionMode) {
}
inputHeading = getInputHeading();
outputHeading = getOutputHeading();
@Override
public void render(float par1, int par2, int par3) {
FontRenderer fr = gui.getFontRenderer();
FontRenderer fr = Minecraft.getMinecraft().fontRenderer;
int rgb = ColorUtil.getRGB(Color.darkGray);
int x = left + (width - fr.getStringWidth(getTypeName())) / 2;
customTop = top + gap * 5 + fr.FONT_HEIGHT * 2;
customTop -= 16;
//fr.drawString(getTypeName(), x, top, rgb);
int x = leftColumn;
int y = 6;
x = left;
int y = gui.getGuiTop() + 13;//customTop + 8;//gap + fr.FONT_HEIGHT + gap;
gui.getFontRenderer().drawString(modeLabel, x, y, rgb);
insertEnabledB = new CheckBox(gui, ID_INSERT_ENABLED, x, y);
String modeString = con.getConnectionMode(gui.getDir()).getLocalisedName();
x += gap + leftArrow.getWidth() + fr.getStringWidth(modeLabel) + gap;
enabledB = new CheckBox(gui, ID_ENABLED, x, y);
GL11.glColor3f(1, 1, 1);
// TODO figure out what this should be
// IconEIO icon = new IconEIO(10, 48, 64, 16);
// icon.getMap().render(icon, x - gap, y - (fr.FONT_HEIGHT / 2) - 1, getLongestModeStringWidth() + gap * 2, leftArrow.getHeight(), 0, true);
x = rightColumn;
int move = (getLongestModeStringWidth() - fr.getStringWidth(modeString)) / 2;
x += move;
rgb = ColorUtil.getRGB(Color.white);
gui.getFontRenderer().drawString(modeString, x, y, rgb);
extractEnabledB = new CheckBox(gui, ID_EXTRACT_ENABLED, x, y);
renderCustomOptions(y + gap + fr.FONT_HEIGHT + gap, par1, par2, par3);
//renderCustomOptions(y + gap, par1, par2, par3);
}
x = leftColumn;
y = 92;
protected void renderCustomOptions(int top, float par1, int par2, int par3) {
x = rightColumn;
}
x = rightColumn + 18 + 1;
filterExtractUpgradeTooltip = new GuiToolTip(
new Rectangle(rightColumn, 70, 18, 18),
EnderIO.lang.localize("gui.conduit.item.filterupgrade")) {
@Override
public boolean shouldDraw() {
return !gui.getContainer().hasFilterUpgrades(true) && super.shouldDraw();
}
};
filterInsertUpgradeTooltip = new GuiToolTip(
new Rectangle(leftColumn, 70, 18, 18),
EnderIO.lang.localize("gui.conduit.item.filterupgrade")) {
@Override
public boolean shouldDraw() {
return !gui.getContainer().hasFilterUpgrades(false) && super.shouldDraw();
}
};
speedUpgradeTooltip = new GuiToolTip(
new Rectangle(rightColumn + 18, customTop + 43, 18, 18),
EnderIO.lang.localize("gui.conduit.item.speedupgrade"),
EnderIO.lang.localize("gui.conduit.item.speedupgrade2")) {
@Override
public boolean shouldDraw() {
return !gui.getContainer().hasSpeedUpgrades() && super.shouldDraw();
}
};
ArrayList<String> funcUpgradeTips = new ArrayList<>();
SpecialTooltipHandler.addTooltipFromResources(funcUpgradeTips, "enderio.gui.conduit.item.functionupgrade.line");
for (FunctionUpgrade upgrade : FunctionUpgrade.values()) {
funcUpgradeTips.add(EnderIO.lang.localizeExact(upgrade.unlocName.concat(".name")));
}
functionUpgradeTooltip = new GuiToolTip(
new Rectangle(rightColumn + 36, customTop + 43, 18, 18),
funcUpgradeTips.toArray(new String[0])) {
@Override
public boolean shouldDraw() {
return !gui.getContainer().hasFunctionUpgrades() && super.shouldDraw();
}
};
gui.getContainer().setInoutSlotsVisible(false, false);
private int getLongestModeStringWidth() {
int maxWidth = 0;
for (ConnectionMode mode : ConnectionMode.values()) {
int width = gui.getFontRenderer().getStringWidth(mode.getLocalisedName());
if(width > maxWidth) {
maxWidth = width;
}
}
return maxWidth;
}
@Override
public ResourceLocation getTexture() {
return texture;
}
protected String getTypeName() {
return typeName;
}
public int getTextureHeight() {
return textureHeight;
}
protected void updateFilterButtons() {}
protected boolean hasFilterGui(boolean input) {
return true;
}
public boolean updateConduit(@Nonnull IConduit conduit) {
this.con = conduit;
if (oldConnectionMode != con.getConnectionMode(gui.getDir())) {
connectionModeChanged(con.getConnectionMode(gui.getDir()));
}
return true;
}
@Override
public void onGuiInit(int leftIn, int topIn, int widthIn, int heightIn) {
this.left = leftIn;
this.top = topIn;
this.width = widthIn;
this.height = heightIn;
updateConduit(con);
if (hasInOutModes()) {
insertEnabledB.onGuiInit();
extractEnabledB.onGuiInit();
insertEnabledB.setSelected(insertEnabled);
extractEnabledB.setSelected(extractEnabled);
} else {
enabledB.onGuiInit();
enabledB.setSelected(enabled);
}
if (hasFilters()) {
gui.addToolTip(filterExtractUpgradeTooltip);
gui.addToolTip(filterInsertUpgradeTooltip);
}
if (hasUpgrades()) {
gui.addToolTip(speedUpgradeTooltip);
gui.addToolTip(functionUpgradeTooltip);
}
initCustomOptions();
}
protected boolean hasUpgrades() {
return false;
}
protected void initCustomOptions() {}
@Override
public void deactivate() {
insertEnabledB.detach();
extractEnabledB.detach();
gui.removeToolTip(speedUpgradeTooltip);
gui.removeToolTip(functionUpgradeTooltip);
gui.removeToolTip(filterExtractUpgradeTooltip);
gui.removeToolTip(filterInsertUpgradeTooltip);
}
@Override
public void mouseClicked(int x, int y, int par3) {}
@Override
public void keyTyped(char par1, int par2) {}
@Override
public void updateScreen() {}
@Override
@Nonnull
public IWidgetIcon getIcon() {
return icon;
}
private void updateConnectionMode() {
ConnectionMode mode = ConnectionMode.DISABLED;
if (insertEnabled && extractEnabled || enabled) {
mode = ConnectionMode.IN_OUT;
} else if (insertEnabled) {
mode = ConnectionMode.OUTPUT;
} else if (extractEnabled) {
mode = ConnectionMode.INPUT;
}
con.setConnectionMode(gui.getDir(), mode);
PacketHandler.INSTANCE.sendToServer(new PacketConnectionMode(con, gui.getDir()));
}
@Override
public void actionPerformed(@Nonnull GuiButton guiButton) {
if (guiButton.id == ID_INSERT_ENABLED) {
insertEnabled = !insertEnabled;
updateConnectionMode();
} else if (guiButton.id == ID_EXTRACT_ENABLED) {
extractEnabled = !extractEnabled;
updateConnectionMode();
} else if (guiButton.id == ID_ENABLED) {
enabled = !enabled;
updateConnectionMode();
}
}
protected void connectionModeChanged(@Nonnull ConnectionMode mode) {
oldConnectionMode = mode;
if (hasInOutModes()) {
insertEnabled = mode.acceptsOutput();
extractEnabled = mode.acceptsInput();
} else {
enabled = mode == ConnectionMode.IN_OUT;
}
}
@Override
public void render(float par1, int par2, int par3) {
updateFilterButtons();
FontRenderer fr = gui.getFontRenderer();
int rgb = ColorUtil.getRGB(Color.darkGray);
int x = left + 32;
int y = gui.getGuiTop() + 10;
if (hasInOutModes()) {
fr.drawString(inputHeading, x, y, rgb);
x += 92;
fr.drawString(outputHeading, x, y, rgb);
} else {
String heading = enabled ? getEnabledHeading() : getDisabledHeading();
fr.drawString(heading, x, y, rgb);
}
renderCustomOptions(y + gap + fr.FONT_HEIGHT + gap, par1, par2, par3);
}
protected void renderCustomOptions(int topIn, float par1, int par2, int par3) {}
protected @Nonnull String getTypeName() {
return typeName;
}
protected boolean hasFilters() {
return false;
}
@Nonnull
protected String getInputHeading() {
// lang strings are nonintuitive for some reason
return EnderIO.lang.localize("gui.conduit.ioMode.output");
}
@Nonnull
protected String getOutputHeading() {
return EnderIO.lang.localize("gui.conduit.ioMode.input");
}
@Nonnull
protected String getEnabledHeading() {
return EnderIO.lang.localize("gui.enabled");
}
@Nonnull
protected String getDisabledHeading() {
return EnderIO.lang.localize("gui.disabled");
}
protected boolean hasInOutModes() {
return true;
}
}
@@ -2,7 +2,6 @@ package crazypants.enderio.conduit.gui;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
@@ -10,7 +9,6 @@ import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
@@ -24,294 +22,264 @@ import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.conduit.gui.item.InventoryUpgrades;
import crazypants.enderio.conduit.item.IItemConduit;
import crazypants.enderio.conduit.item.SpeedUpgrade;
import crazypants.enderio.conduit.item.filter.IItemFilter;
import crazypants.enderio.machine.gui.IContainerWithTileEntity;
import crazypants.enderio.network.PacketHandler;
public class ExternalConnectionContainer extends ContainerEnder<InventoryUpgrades> implements IContainerWithTileEntity {
public class ExternalConnectionContainer extends ContainerEnder<InventoryUpgrades> {
private final IItemConduit itemConduit;
private final ForgeDirection direction;
private final TileEntity te;
private final IItemConduit itemConduit;
private int speedUpgradeSlotLimit = 15;
private int speedUpgradeSlotLimit = 15;
private static final int outputFilterUpgradeSlot = 36;
private static final int inputFilterUpgradeSlot = 37;
private static final int speedUpgradeSlot = 38;
private static final int functionUpgradeSlot = 39;
private static final int outputFilterUpgradeSlot = 36;
private static final int inputFilterUpgradeSlot = 37;
private static final int speedUpgradeSlot = 38;
private static final int functionUpgradeSlot = 39;
private Slot slotSpeedUpgrades;
private Slot slotFunctionUpgrades;
private Slot slotInputFilterUpgrades;
private Slot slotOutputFilterUpgrades;
private Slot slotSpeedUpgrades;
private Slot slotFunctionUpgrades;
private Slot slotInputFilterUpgrades;
private Slot slotOutputFilterUpgrades;
private final List<Point> slotLocations = new ArrayList<>();
private final List<Point> slotLocations = new ArrayList<Point>();
final List<FilterChangeListener> filterListeners = new ArrayList<>();
final List<GhostBackgroundItemSlot> bgSlots = new ArrayList<>();
final List<FilterChangeListener> filterListeners = new ArrayList<FilterChangeListener>();
final List<GhostBackgroundItemSlot> bgSlots = new ArrayList<GhostBackgroundItemSlot>();
public ExternalConnectionContainer(InventoryPlayer playerInv, IConduitBundle bundle, ForgeDirection dir) {
super(playerInv, new InventoryUpgrades(bundle.getConduit(IItemConduit.class), dir));
this.direction = dir;
this.itemConduit = bundle.getConduit(IItemConduit.class);
this.te = (TileEntity) bundle;
slotLocations.addAll(playerSlotLocations.values());
public ExternalConnectionContainer(InventoryPlayer playerInv, IConduitBundle bundle, ForgeDirection dir) {
super(playerInv, new InventoryUpgrades(bundle.getConduit(IItemConduit.class), dir));
this.itemConduit = bundle.getConduit(IItemConduit.class);
slotLocations.addAll(playerSlotLocations.values());
int x;
int y;
int x;
int y;
if (itemConduit != null) {
x = 23;
y = 71;
slotOutputFilterUpgrades = addSlotToContainer(new FilterSlot(getInv(), 3, x, y));
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemBasicFilterUpgrade, slotOutputFilterUpgrades));
if (itemConduit != null) {
x = 10;
y = 47;
slotOutputFilterUpgrades = addSlotToContainer(new FilterSlot(getInv(), 3, x, y));
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemBasicFilterUpgrade, slotOutputFilterUpgrades));
x = 113;
y = 71;
slotInputFilterUpgrades = addSlotToContainer(new FilterSlot(getInv(), 2, x, y));
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemBasicFilterUpgrade, slotInputFilterUpgrades));
x = 10;
y = 47;
slotInputFilterUpgrades = addSlotToContainer(new FilterSlot(getInv(), 2, x, y));
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemBasicFilterUpgrade, slotInputFilterUpgrades));
x = 131;
y = 71;
slotSpeedUpgrades = addSlotToContainer(new Slot(getInv(), 0, x, y) {
@Override
public boolean isItemValid(ItemStack par1ItemStack) {
return getInv().isItemValidForSlot(0, par1ItemStack);
}
@Override
public int getSlotStackLimit() {
return speedUpgradeSlotLimit;
}
});
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemExtractSpeedUpgrade, slotSpeedUpgrades));
x = 149;
y = 71;
slotFunctionUpgrades = addSlotToContainer(new Slot(getInv(), 1, x, y) {
@Override
public boolean isItemValid(ItemStack par1ItemStack) {
return getInv().isItemValidForSlot(1, par1ItemStack);
}
@Override
public int getSlotStackLimit() {
return 1;
}
});
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemFunctionUpgrade, slotFunctionUpgrades));
}
setInventorySlotsVisible(false);
}
public void createGhostSlots(List<GhostSlot> slots) {
slots.addAll(bgSlots);
}
@Override
public Point getPlayerInventoryOffset() {
return new Point(23, 161);
}
public void addFilterListener(FilterChangeListener list) {
filterListeners.add(list);
}
protected void filterChanged() {
for (FilterChangeListener list : filterListeners) {
list.onFilterChanged();
}
}
public boolean hasSpeedUpgrades() {
return slotSpeedUpgrades != null && slotSpeedUpgrades.getHasStack();
}
public boolean hasFunctionUpgrades() {
return slotFunctionUpgrades != null && slotFunctionUpgrades.getHasStack();
}
public boolean hasFilterUpgrades(boolean input) {
Slot slot = input ? slotInputFilterUpgrades : slotOutputFilterUpgrades;
return slot != null && slot.getHasStack();
}
public ForgeDirection getDirection() {
return direction;
}
public IItemFilter getFilter(boolean input) {
if (itemConduit == null) {
return null;
}
return input ? itemConduit.getInputFilter(direction) : itemConduit.getOutputFilter(direction);
}
public void setInoutSlotsVisible(boolean inputVisible, boolean outputVisible) {
if (itemConduit == null) {
return;
}
setSlotsVisible(inputVisible, inputFilterUpgradeSlot, inputFilterUpgradeSlot + 1);
setSlotsVisible(inputVisible, speedUpgradeSlot, speedUpgradeSlot + 1);
setSlotsVisible(outputVisible, outputFilterUpgradeSlot, outputFilterUpgradeSlot + 1);
setSlotsVisible(inputVisible || outputVisible, functionUpgradeSlot, functionUpgradeSlot + 1);
World world = itemConduit.getBundle().getWorld();
if (world.isRemote) {
PacketHandler.INSTANCE.sendToServer(new PacketSlotVisibility(inputVisible, outputVisible));
}
}
public void setInventorySlotsVisible(boolean visible) {
setSlotsVisible(visible, 0, 36);
}
private void setSlotsVisible(boolean visible, int startIndex, int endIndex) {
for (int i = startIndex; i < endIndex; i++) {
Slot s = (Slot) inventorySlots.get(i);
if (visible) {
s.xDisplayPosition = slotLocations.get(i).x;
s.yDisplayPosition = slotLocations.get(i).y;
} else {
s.xDisplayPosition = -3000;
s.yDisplayPosition = -3000;
}
}
}
@Override
public ItemStack slotClick(int par1, int par2, int par3, EntityPlayer par4EntityPlayer) {
ItemStack st = par4EntityPlayer.inventory.getItemStack();
setSpeedUpgradeSlotLimit(st);
try {
return super.slotClick(par1, par2, par3, par4EntityPlayer);
} catch (Exception e) {
// Horrible work around for a bug when double clicking on a stack in inventory which matches a filter item
// This does does double clicking to fill a stack from working with this GUI open.
return null;
}
}
private void setSpeedUpgradeSlotLimit(ItemStack st) {
if (st != null && st.getItem() == EnderIO.itemExtractSpeedUpgrade) {
SpeedUpgrade speedUpgrade = EnderIO.itemExtractSpeedUpgrade.getSpeedUpgrade(st);
speedUpgradeSlotLimit = speedUpgrade.maxStackSize;
}
}
private boolean mergeItemStackSpecial(ItemStack origStack, Slot targetSlot) {
if (!targetSlot.isItemValid(origStack)) {
return false;
}
setSpeedUpgradeSlotLimit(origStack);
ItemStack curStack = targetSlot.getStack();
int maxStackSize = Math.min(origStack.getMaxStackSize(), targetSlot.getSlotStackLimit());
if (curStack == null) {
curStack = origStack.copy();
curStack.stackSize = Math.min(origStack.stackSize, maxStackSize);
origStack.stackSize -= curStack.stackSize;
targetSlot.putStack(curStack);
targetSlot.onSlotChanged();
return true;
} else if (ItemUtil.areStackMergable(curStack, origStack)) {
int mergedSize = curStack.stackSize + origStack.stackSize;
if (mergedSize <= maxStackSize) {
origStack.stackSize = 0;
curStack.stackSize = mergedSize;
targetSlot.onSlotChanged();
return true;
} else if (curStack.stackSize < maxStackSize) {
origStack.stackSize -= maxStackSize - curStack.stackSize;
curStack.stackSize = maxStackSize;
targetSlot.onSlotChanged();
return true;
}
}
return false;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int slotIndex) {
ItemStack copystack = null;
Slot slot = (Slot) inventorySlots.get(slotIndex);
if (slot != null && slot.getHasStack()) {
ItemStack origStack = slot.getStack();
copystack = origStack.copy();
boolean merged = false;
if (slotIndex < outputFilterUpgradeSlot) {
for (int targetSlotIdx = outputFilterUpgradeSlot; targetSlotIdx
<= functionUpgradeSlot; targetSlotIdx++) {
Slot targetSlot = (Slot) inventorySlots.get(targetSlotIdx);
if (targetSlot.xDisplayPosition >= 0 && mergeItemStackSpecial(origStack, targetSlot)) {
merged = true;
break;
}
}
} else {
merged = mergeItemStack(origStack, 0, outputFilterUpgradeSlot, false);
}
if (!merged) {
return null;
}
slot.onSlotChange(origStack, copystack);
if (origStack.stackSize == 0) {
slot.putStack((ItemStack) null);
} else {
slot.onSlotChanged();
}
if (origStack.stackSize == copystack.stackSize) {
return null;
}
slot.onPickupFromSlot(entityPlayer, origStack);
}
return copystack;
}
@Override
public TileEntity getTileEntity() {
return te;
}
private class FilterSlot extends Slot {
public FilterSlot(IInventory par1iInventory, int par2, int par3, int par4) {
super(par1iInventory, par2, par3, par4);
x = 10;
y = 83;
slotSpeedUpgrades = addSlotToContainer(new Slot(getInv(), 0, x, y) {
@Override
public boolean isItemValid(ItemStack par1ItemStack) {
return getInv().isItemValidForSlot(0, par1ItemStack);
}
@Override
public int getSlotStackLimit() {
return 1;
}
@Override
public void onSlotChanged() {
filterChanged();
return speedUpgradeSlotLimit;
}
});
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemExtractSpeedUpgrade, slotSpeedUpgrades));
x = 10;
y = 65;
slotFunctionUpgrades = addSlotToContainer(new Slot(getInv(), 1, x, y) {
@Override
public boolean isItemValid(ItemStack par1ItemStack) {
return inventory.isItemValidForSlot(getSlotIndex(), par1ItemStack);
return getInv().isItemValidForSlot(1, par1ItemStack);
}
@Override
public int getSlotStackLimit() {
return 1;
}
});
slotLocations.add(new Point(x, y));
bgSlots.add(new GhostBackgroundItemSlot(EnderIO.itemFunctionUpgrade, slotFunctionUpgrades));
}
}
public void createGhostSlots(List<GhostSlot> slots) {
slots.addAll(bgSlots);
}
@Override
public Point getPlayerInventoryOffset() {
return new Point(23, 113);
}
public void addFilterListener(FilterChangeListener list) {
filterListeners.add(list);
}
protected void filterChanged() {
for (FilterChangeListener list : filterListeners) {
list.onFilterChanged();
}
}
public boolean hasSpeedUpgrades() {
return slotSpeedUpgrades != null && slotSpeedUpgrades.getHasStack();
}
public boolean hasFunctionUpgrades() {
return slotFunctionUpgrades != null && slotFunctionUpgrades.getHasStack();
}
public boolean hasFilterUpgrades(boolean input) {
Slot slot = input ? slotInputFilterUpgrades : slotOutputFilterUpgrades;
return slot != null && slot.getHasStack();
}
public void setInoutSlotsVisible(boolean inputVisible, boolean outputVisible) {
if(itemConduit == null) {
return;
}
setSlotsVisible(inputVisible, inputFilterUpgradeSlot, inputFilterUpgradeSlot + 1);
setSlotsVisible(inputVisible, speedUpgradeSlot, speedUpgradeSlot + 1);
setSlotsVisible(outputVisible, outputFilterUpgradeSlot, outputFilterUpgradeSlot + 1);
setSlotsVisible(inputVisible || outputVisible, functionUpgradeSlot, functionUpgradeSlot + 1);
World world = itemConduit.getBundle().getWorld();
if(world.isRemote) {
PacketHandler.INSTANCE.sendToServer(new PacketSlotVisibility(inputVisible, outputVisible));
}
}
public void setInventorySlotsVisible(boolean visible) {
setSlotsVisible(visible, 0, 36);
}
private void setSlotsVisible(boolean visible, int startIndex, int endIndex) {
for (int i = startIndex; i < endIndex; i++) {
Slot s = (Slot) inventorySlots.get(i);
if(visible) {
s.xDisplayPosition = slotLocations.get(i).x;
s.yDisplayPosition = slotLocations.get(i).y;
} else {
s.xDisplayPosition = -3000;
s.yDisplayPosition = -3000;
}
}
}
@Override
public ItemStack slotClick(int par1, int par2, int par3, EntityPlayer par4EntityPlayer) {
ItemStack st = par4EntityPlayer.inventory.getItemStack();
setSpeedUpgradeSlotLimit(st);
try {
return super.slotClick(par1, par2, par3, par4EntityPlayer);
} catch (Exception e) {
//Horrible work around for a bug when double clicking on a stack in inventory which matches a filter item
//This does does double clicking to fill a stack from working with this GUI open.
return null;
}
}
private void setSpeedUpgradeSlotLimit(ItemStack st) {
if(st != null && st.getItem() == EnderIO.itemExtractSpeedUpgrade) {
SpeedUpgrade speedUpgrade = EnderIO.itemExtractSpeedUpgrade.getSpeedUpgrade(st);
speedUpgradeSlotLimit = speedUpgrade.maxStackSize;
}
}
private boolean mergeItemStackSpecial(ItemStack origStack, Slot targetSlot) {
if (!targetSlot.isItemValid(origStack)) {
return false;
}
public List<String> getFunctionUpgradeToolTipText() {
return Collections.emptyList();
setSpeedUpgradeSlotLimit(origStack);
ItemStack curStack = targetSlot.getStack();
int maxStackSize = Math.min(origStack.getMaxStackSize(), targetSlot.getSlotStackLimit());
if(curStack == null) {
curStack = origStack.copy();
curStack.stackSize = Math.min(origStack.stackSize, maxStackSize);
origStack.stackSize -= curStack.stackSize;
targetSlot.putStack(curStack);
targetSlot.onSlotChanged();
return true;
} else if(ItemUtil.areStackMergable(curStack, origStack)) {
int mergedSize = curStack.stackSize + origStack.stackSize;
if(mergedSize <= maxStackSize) {
origStack.stackSize = 0;
curStack.stackSize = mergedSize;
targetSlot.onSlotChanged();
return true;
} else if(curStack.stackSize < maxStackSize) {
origStack.stackSize -= maxStackSize - curStack.stackSize;
curStack.stackSize = maxStackSize;
targetSlot.onSlotChanged();
return true;
}
}
return false;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer entityPlayer, int slotIndex) {
ItemStack copystack = null;
Slot slot = (Slot) inventorySlots.get(slotIndex);
if(slot != null && slot.getHasStack()) {
ItemStack origStack = slot.getStack();
copystack = origStack.copy();
boolean merged = false;
if (slotIndex < outputFilterUpgradeSlot) {
for (int targetSlotIdx = outputFilterUpgradeSlot; targetSlotIdx <= functionUpgradeSlot; targetSlotIdx++) {
Slot targetSlot = (Slot) inventorySlots.get(targetSlotIdx);
if(targetSlot.xDisplayPosition >= 0 && mergeItemStackSpecial(origStack, targetSlot)) {
merged = true;
break;
}
}
} else {
merged = mergeItemStack(origStack, 0, outputFilterUpgradeSlot, false);
}
if(!merged) {
return null;
}
slot.onSlotChange(origStack, copystack);
if(origStack.stackSize == 0) {
slot.putStack((ItemStack) null);
} else {
slot.onSlotChanged();
}
if(origStack.stackSize == copystack.stackSize) {
return null;
}
slot.onPickupFromSlot(entityPlayer, origStack);
}
return copystack;
}
private class FilterSlot extends Slot {
public FilterSlot(IInventory par1iInventory, int par2, int par3, int par4) {
super(par1iInventory, par2, par3, par4);
}
@Override
public int getSlotStackLimit() {
return 1;
}
@Override
public void onSlotChanged() {
filterChanged();
}
@Override
public boolean isItemValid(ItemStack par1ItemStack) {
return inventory.isItemValidForSlot(getSlotIndex(), par1ItemStack);
}
}
}
@@ -1,78 +0,0 @@
package crazypants.enderio.conduit.gui;
import javax.annotation.Nonnull;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import com.enderio.core.api.client.gui.IGuiScreen;
import com.enderio.core.api.client.render.IWidgetIcon;
import com.enderio.core.client.gui.button.TooltipButton;
public class FakeButton extends TooltipButton {
public static final int DEFAULT_WIDTH = 16;
public static final int DEFAULT_HEIGHT = 16;
protected @Nonnull IWidgetIcon icon;
private int marginY = 0;
private int marginX = 0;
public FakeButton(@Nonnull IGuiScreen gui, int x, int y, @Nonnull IWidgetIcon icon) {
super(gui, -1, x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, "");
this.icon = icon;
}
@Override
public FakeButton setPosition(int x, int y) {
super.setPosition(x, y);
return this;
}
public FakeButton setIconMargin(int x, int y) {
marginX = x;
marginY = y;
return this;
}
public @Nonnull IWidgetIcon getIcon() {
return icon;
}
public void setIcon(@Nonnull IWidgetIcon icon) {
this.icon = icon;
}
public boolean mousePressedButton(@Nonnull Minecraft mc, int mouseX, int mouseY, int button) {
return false;
}
protected boolean checkMousePress(@Nonnull Minecraft mc, int mouseX, int mouseY) {
return false;
}
/**
* Draws this button to the screen.
*/
@Override
public void drawButton(@Nonnull Minecraft mc, int mouseX, int mouseY) {
updateTooltip(mc, mouseX, mouseY);
if (isVisible()) {
GL11.glPushAttrib(GL11.GL_ENABLE_BIT);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
icon.getMap().render(
icon,
xPosition + marginX,
yPosition + marginY,
width - 2 * marginX,
height - 2 * marginY,
0,
true);
GL11.glPopAttrib();
}
}
}
@@ -2,5 +2,6 @@ package crazypants.enderio.conduit.gui;
public interface FilterChangeListener {
void onFilterChanged();
void onFilterChanged();
}
@@ -1,21 +0,0 @@
package crazypants.enderio.conduit.gui;
public class FilterGuiUtil {
// List of filter indexes for reference in guis
public static final int INDEX_INPUT_ITEM = 1;
public static final int INDEX_OUTPUT_ITEM = 2;
public static final int INDEX_INPUT_FLUID = 3;
public static final int INDEX_OUTPUT_FLUID = 4;
public static final int INDEX_INPUT_REDSTONE = 6;
public static final int INDEX_OUTPUT_REDSTONE = 5;
public static final int INDEX_NONE = 0;
public static final int INDEX_FILTER_HANDHELD = -1;
private static int nextButtonId = 1;
public static int nextButtonId() {
return nextButtonId++;
}
}
@@ -2,6 +2,7 @@ package crazypants.enderio.conduit.gui;
import java.awt.Color;
import mekanism.api.gas.Gas;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.IIcon;
@@ -20,102 +21,108 @@ import crazypants.enderio.gui.RedstoneModeButton;
import crazypants.enderio.machine.IRedstoneModeControlable;
import crazypants.enderio.machine.RedstoneControlMode;
import crazypants.enderio.network.PacketHandler;
import mekanism.api.gas.Gas;
public class GasSettings extends BaseSettingsPanel {
static final int ID_REDSTONE_BUTTON = GuiExternalConnection.nextButtonId();
static final int ID_REDSTONE_BUTTON = GuiExternalConnection.nextButtonId();
private static final int ID_COLOR_BUTTON = GuiExternalConnection.nextButtonId();
private static final int ID_COLOR_BUTTON = GuiExternalConnection.nextButtonId();
private final RedstoneModeButton rsB;
private RedstoneModeButton rsB;
private final ColorButton colorB;
private ColorButton colorB;
private final String autoExtractStr = EnderIO.lang.localize("gui.conduit.gas.autoExtract");
private String autoExtractStr = EnderIO.lang.localize("gui.conduit.gas.autoExtract");
private final IGasConduit conduit;
private IGasConduit conduit;
protected GasSettings(final GuiExternalConnection gui, IConduit con) {
super(IconEIO.WRENCH_OVERLAY_GAS, EnderIO.lang.localize("itemGasConduit.name"), gui, con);
protected GasSettings(final GuiExternalConnection gui, IConduit con) {
super(IconEIO.WRENCH_OVERLAY_GAS, EnderIO.lang.localize("itemGasConduit.name"), gui, con);
conduit = (IGasConduit) con;
gui.getContainer().setInventorySlotsVisible(false);
conduit = (IGasConduit) con;
gui.getContainer().setInventorySlotsVisible(false);
int x = gap + gui.getFontRenderer().getStringWidth(autoExtractStr) + gap * 2;
int y = customTop;
int x = gap + gui.getFontRenderer().getStringWidth(autoExtractStr) + gap * 2;
int y = customTop;
rsB = new RedstoneModeButton(gui, ID_REDSTONE_BUTTON, x, y, new IRedstoneModeControlable() {
rsB = new RedstoneModeButton(gui, ID_REDSTONE_BUTTON, x, y, new IRedstoneModeControlable() {
@Override
public void setRedstoneControlMode(RedstoneControlMode mode) {
RedstoneControlMode curMode = getRedstoneControlMode();
conduit.setExtractionRedstoneMode(mode, gui.getDir());
if (curMode != mode) {
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
}
}
@Override
public RedstoneControlMode getRedstoneControlMode() {
return conduit.getExtractionRedstoneMode(gui.getDir());
}
});
x += rsB.getWidth() + gap;
colorB = new ColorButton(gui, ID_COLOR_BUTTON, x, y);
colorB.setToolTipHeading(EnderIO.lang.localize("gui.conduit.redstone.signalColor"));
colorB.setColorIndex(conduit.getExtractionSignalColor(gui.getDir()).ordinal());
}
@Override
public void actionPerformed(GuiButton guiButton) {
super.actionPerformed(guiButton);
if (guiButton.id == ID_COLOR_BUTTON) {
conduit.setExtractionSignalColor(gui.getDir(), DyeColor.VALUES[colorB.getColorIndex()]);
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
@Override
public void setRedstoneControlMode(RedstoneControlMode mode) {
RedstoneControlMode curMode = getRedstoneControlMode();
conduit.setExtractionRedstoneMode(mode, gui.getDir());
if(curMode != mode) {
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
}
}
@Override
public RedstoneControlMode getRedstoneControlMode() {
return conduit.getExtractionRedstoneMode(gui.getDir());
}
});
x += rsB.getWidth() + gap;
colorB = new ColorButton(gui, ID_COLOR_BUTTON, x, y);
colorB.setToolTipHeading(EnderIO.lang.localize("gui.conduit.redstone.signalColor"));
colorB.setColorIndex(conduit.getExtractionSignalColor(gui.getDir()).ordinal());
}
@Override
public void actionPerformed(GuiButton guiButton) {
super.actionPerformed(guiButton);
if(guiButton.id == ID_COLOR_BUTTON) {
conduit.setExtractionSignalColor(gui.getDir(), DyeColor.values()[colorB.getColorIndex()]);
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
}
}
@Override
protected void connectionModeChanged(ConnectionMode conectionMode) {
super.connectionModeChanged(conectionMode);
if(conectionMode == ConnectionMode.INPUT) {
rsB.onGuiInit();
colorB.onGuiInit();
} else {
rsB.detach();
colorB.detach();
}
@Override
protected void connectionModeChanged(ConnectionMode conectionMode) {
super.connectionModeChanged(conectionMode);
if (conectionMode == ConnectionMode.INPUT) {
rsB.onGuiInit();
colorB.onGuiInit();
} else {
rsB.detach();
colorB.detach();
}
}
@Override
public void mouseClicked(int x, int y, int par3) {
}
@Override
public void deactivate() {
super.deactivate();
rsB.setToolTip((String[]) null);
colorB.setToolTip((String[]) null);
}
@Override
protected void renderCustomOptions(int top, float par1, int par2, int par3) {
boolean isInput = isInput();
if(isInput) {
int x = gui.getGuiLeft() + gap + gui.getFontRenderer().getStringWidth(autoExtractStr) + gap + 2;
int y = customTop;
gui.getFontRenderer().drawString(autoExtractStr, left, top, ColorUtil.getRGB(Color.DARK_GRAY));
}
}
private void renderGas(Gas f, int x, int y) {
IIcon icon = f.getIcon();
if(icon != null) {
RenderUtil.bindBlockTexture();
gui.drawTexturedModelRectFromIcon(x + 1, y + 1, icon, 16, 16);
}
@Override
public void mouseClicked(int x, int y, int par3) {}
}
@Override
public void deactivate() {
super.deactivate();
rsB.setToolTip((String[]) null);
colorB.setToolTip((String[]) null);
}
private boolean isInput() {
return conduit.getConnectionMode(gui.getDir()) == ConnectionMode.INPUT;
}
@Override
protected void renderCustomOptions(int top, float par1, int par2, int par3) {
boolean isInput = isInput();
if (isInput) {
gui.getFontRenderer().drawString(autoExtractStr, left, top, ColorUtil.getRGB(Color.DARK_GRAY));
}
}
private void renderGas(Gas f, int x, int y) {
IIcon icon = f.getIcon();
if (icon != null) {
RenderUtil.bindBlockTexture();
gui.drawTexturedModelRectFromIcon(x + 1, y + 1, icon, 16, 16);
}
}
private boolean isInput() {
return conduit.getConnectionMode(gui.getDir()) == ConnectionMode.INPUT;
}
}
@@ -18,7 +18,6 @@ import org.lwjgl.opengl.GL11;
import com.enderio.core.api.client.gui.ITabPanel;
import com.enderio.core.api.client.render.IWidgetIcon;
import com.enderio.core.client.gui.widget.GhostSlot;
import com.enderio.core.client.render.RenderUtil;
import cpw.mods.fml.common.Optional;
@@ -36,281 +35,207 @@ import crazypants.enderio.gui.IconEIO;
public class GuiExternalConnection extends GuiContainerBaseEIO {
private static final int TAB_HEIGHT = 24;
private static final int TAB_HEIGHT = 24;
private static int nextButtonId = 1;
private static int nextButtonId = 1;
public static int nextButtonId() {
return nextButtonId++;
}
public static int nextButtonId() {
return nextButtonId++;
}
public static int nextButtonIds(int count) {
int id = nextButtonId;
nextButtonId += count;
return id;
}
private static final Map<Class<? extends IConduit>, Integer> TAB_ORDER = new HashMap<Class<? extends IConduit>, Integer>();
static {
TAB_ORDER.put(IItemConduit.class, 0);
TAB_ORDER.put(ILiquidConduit.class, 1);
TAB_ORDER.put(IRedstoneConduit.class, 2);
TAB_ORDER.put(IPowerConduit.class, 3);
TAB_ORDER.put(IMEConduit.class, 4);
TAB_ORDER.put(IGasConduit.class, 5);
TAB_ORDER.put(IOCConduit.class, 6);
}
private static final Map<Class<? extends IConduit>, Integer> TAB_ORDER = new HashMap<>();
final InventoryPlayer playerInv;
final IConduitBundle bundle;
private final ForgeDirection dir;
static {
TAB_ORDER.put(IItemConduit.class, 0);
TAB_ORDER.put(ILiquidConduit.class, 1);
TAB_ORDER.put(IRedstoneConduit.class, 2);
TAB_ORDER.put(IPowerConduit.class, 3);
TAB_ORDER.put(IMEConduit.class, 4);
TAB_ORDER.put(IGasConduit.class, 5);
TAB_ORDER.put(IOCConduit.class, 6);
}
private final List<IConduit> conduits = new ArrayList<IConduit>();
private final List<ITabPanel> tabs = new ArrayList<ITabPanel>();
private int activeTab = 0;
final InventoryPlayer playerInv;
final IConduitBundle bundle;
private final ForgeDirection dir;
private int tabYOffset = 4;
private final List<IConduit> conduits = new ArrayList<>();
private final List<ITabPanel> tabs = new ArrayList<>();
private int activeTab = 0;
private final ExternalConnectionContainer container;
private static final int tabYOffset = 4;
public GuiExternalConnection(InventoryPlayer playerInv, IConduitBundle bundle, ForgeDirection dir) {
super(new ExternalConnectionContainer(playerInv, bundle, dir), "externalConduitConnection", "itemFilter");
container = (ExternalConnectionContainer) inventorySlots;
this.playerInv = playerInv;
this.bundle = bundle;
this.dir = dir;
private final ExternalConnectionContainer container;
ySize = 166 + 29;
xSize = 206;
public GuiExternalConnection(InventoryPlayer playerInv, IConduitBundle bundle, ForgeDirection dir) {
super(new ExternalConnectionContainer(playerInv, bundle, dir), "externalConduitConnection", "itemFilter");
container = (ExternalConnectionContainer) inventorySlots;
this.playerInv = playerInv;
this.bundle = bundle;
this.dir = dir;
container.setInoutSlotsVisible(false, false);
container.setInventorySlotsVisible(false);
ySize = 166 + 29 + 48;
xSize = 206;
List<IConduit> cons = new ArrayList<IConduit>(bundle.getConduits());
Collections.sort(cons, new Comparator<IConduit>() {
container.setInoutSlotsVisible(false, false);
List<IConduit> cons = new ArrayList<>(bundle.getConduits());
Collections.sort(cons, new Comparator<>() {
@Override
public int compare(IConduit o1, IConduit o2) {
Integer int1 = TAB_ORDER.get(o1.getBaseConduitType());
if (int1 == null) {
return 1;
}
Integer int2 = TAB_ORDER.get(o2.getBaseConduitType());
if (int2 == null) {
return 1;
}
return Integer.compare(int1, int2);
}
});
for (IConduit con : cons) {
if (con.containsExternalConnection(dir) || con.canConnectToExternal(dir, true)) {
@SuppressWarnings("LeakingThisInConstructor")
ITabPanel tab = TabFactory.instance.createPanelForConduit(this, con);
if (tab != null) {
conduits.add(con);
tabs.add(tab);
tab.deactivate();
}
}
@Override
public int compare(IConduit o1, IConduit o2) {
Integer int1 = TAB_ORDER.get(o1.getBaseConduitType());
if(int1 == null) {
return 1;
}
}
public IConduitBundle getBundle() {
return bundle;
}
@Override
public void initGui() {
super.initGui();
buttonList.clear();
((ExternalConnectionContainer) inventorySlots).createGhostSlots(getGhostSlots());
for (int i = 0; i < tabs.size(); i++) {
if (i == activeTab) {
tabs.get(i).onGuiInit(guiLeft + 10, guiTop, xSize - 20, ySize - 20);
}
Integer int2 = TAB_ORDER.get(o2.getBaseConduitType());
if(int2 == null) {
return 1;
}
}
//NB: using Double.comp instead of Integer.comp as the int version is only from Java 1.7+
return Double.compare(int1, int2);
@Override
public boolean doesGuiPauseGame() {
return false;
}
}
});
/**
* Returns true when slots outside of standard gui bounds are clicked to prevent setting ghost filters dropping
* items on the ground.
*/
private boolean handleOobClick(int x, int y, int button) {
boolean outOfBounds = x < guiLeft || y < guiTop || x >= guiLeft + xSize || y >= guiTop + ySize;
boolean hasItem = playerInv.getItemStack() != null;
if (outOfBounds && hasItem && !getGhostSlots().isEmpty()) {
GhostSlot slot = getGhostSlot(x, y);
if (slot != null) {
ghostSlotClicked(slot, x, y, button);
return true;
}
for (IConduit con : cons) {
if(con.containsExternalConnection(dir) || con.canConnectToExternal(dir, true)) {
@SuppressWarnings("LeakingThisInConstructor")
ITabPanel tab = TabFactory.instance.createPanelForConduit(this, con);
if(tab != null) {
conduits.add(con);
tabs.add(tab);
}
return false;
}
}
@Override
protected void mouseMovedOrUp(int x, int y, int button) {
if (handleOobClick(x, y, button)) {
return;
}
super.mouseMovedOrUp(x, y, button);
}
@Override
public void initGui() {
super.initGui();
buttonList.clear();
((ExternalConnectionContainer) inventorySlots).createGhostSlots(getGhostSlots());
for (int i = 0; i < tabs.size(); i++) {
if(i == activeTab) {
tabs.get(i).onGuiInit(guiLeft + 10, guiTop, xSize - 20, ySize - 20);
} else {
tabs.get(i).deactivate();
}
}
}
@Override
protected void mouseClicked(int x, int y, int button) {
// handle out-of-bounds ghost slots
if (handleOobClick(x, y, button)) {
return;
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
int tabLeftX = xSize;
int tabRightX = tabLeftX + 22;
@Override
protected void mouseClicked(int x, int y, int par3) {
super.mouseClicked(x, y, par3);
int minY = tabYOffset;
int maxY = minY + (conduits.size() * TAB_HEIGHT);
int tabLeftX = xSize;
int tabRightX = tabLeftX + 22;
x = (x - guiLeft);
y = (y - guiTop);
int minY = tabYOffset;
int maxY = minY + (conduits.size() * TAB_HEIGHT);
if (x > tabLeftX && x < tabRightX + 24) {
if (y > minY && y < maxY) {
tabs.get(activeTab).deactivate();
getGhostSlots().clear();
activeTab = (y - minY) / 24;
initGui();
return;
}
}
tabs.get(activeTab).mouseClicked(x, y, button);
super.mouseClicked(x + guiLeft, y + guiTop, button);
x = (x - guiLeft);
y = (y - guiTop);
if(x > tabLeftX && x < tabRightX + 24) {
if(y > minY && y < maxY) {
activeTab = (y - minY) / 24;
initGui();
return;
}
}
tabs.get(activeTab).mouseClicked(x, y, par3);
public void setSize(int x, int y) {
xSize = x;
ySize = y;
}
}
@Override
protected void actionPerformed(GuiButton guiButton) {
super.actionPerformed(guiButton);
tabs.get(activeTab).actionPerformed(guiButton);
}
public void setSize(int x, int y) {
xSize = x;
ySize = y;
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
@Override
protected void actionPerformed(GuiButton guiButton) {
super.actionPerformed(guiButton);
tabs.get(activeTab).actionPerformed(guiButton);
}
int sx = (width - xSize) / 2;
int sy = (height - ySize) / 2;
int tabX = sx + xSize - 3;
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
Tessellator tes = Tessellator.instance;
tes.startDrawingQuads();
for (int i = 0; i < tabs.size(); i++) {
if (i != activeTab) {
RenderUtil.bindTexture(IconEIO.TEXTURE);
IconEIO.map.render(IconEIO.INACTIVE_TAB, tabX, sy + tabYOffset + (i * 24));
IWidgetIcon icon = tabs.get(i).getIcon();
icon.getMap().render(icon, tabX - 1, sy + tabYOffset + (i * TAB_HEIGHT) + 4);
}
}
tes.draw();
int textureHeight = 166 + 29;
if (tabs.isEmpty()) {
bindGuiTexture();
} else {
ITabPanel tab = tabs.get(activeTab);
RenderUtil.bindTexture(tab.getTexture());
if (tab instanceof BaseSettingsPanel) {
textureHeight = ((BaseSettingsPanel) tab).getTextureHeight();
}
}
drawTexturedModalRect(sx, sy, 0, 0, this.xSize, textureHeight);
int sx = (width - xSize) / 2;
int sy = (height - ySize) / 2;
int tabX = sx + xSize - 3;
Tessellator tes = Tessellator.instance;
tes.startDrawingQuads();
for (int i = 0; i < tabs.size(); i++) {
if(i != activeTab) {
RenderUtil.bindTexture(IconEIO.TEXTURE);
tes.startDrawingQuads();
IconEIO.map.render(IconEIO.ACTIVE_TAB, tabX, sy + tabYOffset + (activeTab * TAB_HEIGHT));
if (tabs.size() > 0) {
IWidgetIcon icon = tabs.get(activeTab).getIcon();
icon.getMap().render(icon, tabX - 1, sy + tabYOffset + (activeTab * TAB_HEIGHT) + 4);
tes.draw();
tabs.get(activeTab).render(par1, par2, par3);
} else {
tes.draw();
}
super.drawGuiContainerBackgroundLayer(par1, par2, par3);
IconEIO.map.render(IconEIO.INACTIVE_TAB, tabX, sy + tabYOffset + (i * 24));
IWidgetIcon icon = tabs.get(i).getIcon();
icon.getMap().render(icon, tabX - 1, sy + tabYOffset + (i * TAB_HEIGHT) + 4);
}
}
public ForgeDirection getDir() {
return dir;
tes.draw();
bindGuiTexture();
drawTexturedModalRect(sx, sy, 0, 0, this.xSize, this.ySize);
RenderUtil.bindTexture(IconEIO.TEXTURE);
tes.startDrawingQuads();
IconEIO.map.render(IconEIO.ACTIVE_TAB, tabX, sy + tabYOffset + (activeTab * TAB_HEIGHT));
if(tabs.size() > 0) {
IWidgetIcon icon = tabs.get(activeTab).getIcon();
icon.getMap().render(icon, tabX - 1, sy + tabYOffset + (activeTab * TAB_HEIGHT) + 4);
tes.draw();
tabs.get(activeTab).render(par1, par2, par3);
} else {
tes.draw();
}
public ExternalConnectionContainer getContainer() {
return container;
}
super.drawGuiContainerBackgroundLayer(par1, par2, par3);
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean hideItemPanelSlot(GuiContainer gc, int x, int y, int w, int h) {
int sx = (width - xSize) / 2;
int sy = (height - ySize) / 2;
if (tabs.size() > 0) {
int tabX = sx + xSize - 3;
int tabY = sy + tabYOffset;
public ForgeDirection getDir() {
return dir;
}
if ((x + w) >= tabX && x < (tabX + 14) && (y + h) >= tabY && y < (tabY + tabs.size() * TAB_HEIGHT)) {
return true;
}
}
List<GhostSlot> slots = getGhostSlots();
if (slots != null && !slots.isEmpty()) {
for (GhostSlot slot : slots) {
int slotX = sx + slot.x;
int slotY = sy + slot.y;
if ((x + w) >= slotX && x < (slotX + 20) && (y + h) >= slotY && y < (slotY + 20)) {
return true;
}
}
}
return false;
}
public ExternalConnectionContainer getContainer() {
return container;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean handleDragNDrop(GuiContainer gc, int x, int y, ItemStack is, int button) {
if (super.handleDragNDrop(gc, x, y, is, button)) {
return true;
}
x -= guiLeft;
y -= guiTop;
if (is != null && is.stackSize > 0 && !tabs.isEmpty() && tabs.get(activeTab) instanceof LiquidSettings) {
LiquidSettings settings = (LiquidSettings) tabs.get(activeTab);
if (settings.setFilterFromItem(x, y, is)) {
is.stackSize = 0;
return true;
}
}
return false;
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public boolean hideItemPanelSlot(GuiContainer gc, int x, int y, int w, int h) {
if(tabs.size() > 0) {
int sx = (width - xSize) / 2;
int sy = (height - ySize) / 2;
int tabX = sx + xSize - 3;
int tabY = sy + tabYOffset;
@Override
protected void drawFakeItemStack(int x, int y, ItemStack stack) {
super.drawFakeItemStack(x, y, stack);
itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, stack, x, y, "");
return (x+w) >= tabX && x < (tabX + 14) && (y+h) >= tabY && y < (tabY + tabs.size()*TAB_HEIGHT);
}
return false;
}
@Override
protected void drawFakeItemStack(int x, int y, ItemStack stack) {
super.drawFakeItemStack(x, y, stack);
itemRender.renderItemOverlayIntoGUI(fontRendererObj, mc.renderEngine, stack, x, y, "");
}
public void clearGhostSlots() {
getGhostSlots().clear();
((ExternalConnectionContainer) inventorySlots).createGhostSlots(getGhostSlots());
}
public void clearGhostSlots() {
getGhostSlots().clear();
((ExternalConnectionContainer) inventorySlots).createGhostSlots(getGhostSlots());
}
}
@@ -23,118 +23,107 @@ import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.conduit.redstone.IInsulatedRedstoneConduit;
import crazypants.enderio.network.PacketHandler;
import crazypants.util.ForgeDirections;
public class GuiExternalConnectionSelector extends GuiScreen {
Set<ForgeDirection> cons;
IConduitBundle cb;
String adjacentBlockNames[] = new String[6];
Point textPositions[] = new Point[6];
Set<ForgeDirection> cons;
IConduitBundle cb;
String adjacentBlockNames[] = new String[6];
Point textPositions[] = new Point[6];
public GuiExternalConnectionSelector(IConduitBundle cb) {
this.cb = cb;
cons = new HashSet<>();
for (IConduit con : cb.getConduits()) {
if (con instanceof IInsulatedRedstoneConduit) {
Set<ForgeDirection> conCons = con.getConduitConnections();
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
if (!conCons.contains(dir)) {
cons.add(dir);
}
}
} else {
cons.addAll(con.getExternalConnections());
}
public GuiExternalConnectionSelector(IConduitBundle cb) {
this.cb = cb;
cons = new HashSet<ForgeDirection>();
for (IConduit con : cb.getConduits()) {
if(con instanceof IInsulatedRedstoneConduit) {
Set<ForgeDirection> conCons = con.getConduitConnections();
for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
if(!conCons.contains(dir)) {
cons.add(dir);
}
}
} else {
cons.addAll(con.getExternalConnections());
}
}
}
@Override
protected void actionPerformed(GuiButton b) {
ForgeDirection dir = ForgeDirections.DIRECTIONS[b.id];
EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
BlockCoord loc = cb.getLocation();
PacketHandler.INSTANCE.sendToServer(new PacketOpenConduitUI(cb.getEntity(), dir));
player.openGui(
EnderIO.instance,
GuiHandler.GUI_ID_EXTERNAL_CONNECTION_BASE + dir.ordinal(),
player.worldObj,
loc.x,
loc.y,
loc.z);
@Override
protected void actionPerformed(GuiButton b) {
ForgeDirection dir = ForgeDirection.values()[b.id];
EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer;
BlockCoord loc = cb.getLocation();
PacketHandler.INSTANCE.sendToServer(new PacketOpenConduitUI(cb.getEntity(), dir));
player.openGui(EnderIO.instance, GuiHandler.GUI_ID_EXTERNAL_CONNECTION_BASE + dir.ordinal(), player.worldObj, loc.x, loc.y, loc.z);
}
protected String getBlockNameForDirection(ForgeDirection direction) {
BlockCoord coords = cb.getLocation();
Block b = cb.getWorld().getBlock(coords.x + direction.offsetX, coords.y + direction.offsetY, coords.z + direction.offsetZ);
if (b != null && b != Blocks.air) {
return b.getLocalizedName();
}
return null;
}
protected String getBlockNameForDirection(ForgeDirection direction) {
BlockCoord coords = cb.getLocation();
Block b = cb.getWorld()
.getBlock(coords.x + direction.offsetX, coords.y + direction.offsetY, coords.z + direction.offsetZ);
if (b != null && b != Blocks.air) {
return b.getLocalizedName();
}
return null;
@Override
public void initGui() {
GuiButton b;
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
Point p = getOffsetForDir(dir);
adjacentBlockNames[dir.ordinal()] = getBlockNameForDirection(dir);
textPositions[dir.ordinal()] = new Point(p.x, p.y + 20);
b = new GuiButton(dir.ordinal(), p.x, p.y, 60, 20, dir.toString());
buttonList.add(b);
if(!cons.contains(dir)) {
b.enabled = false;
}
}
}
@Override
public void initGui() {
GuiButton b;
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
Point p = getOffsetForDir(dir);
adjacentBlockNames[dir.ordinal()] = getBlockNameForDirection(dir);
textPositions[dir.ordinal()] = new Point(p.x, p.y + 20);
b = new GuiButton(dir.ordinal(), p.x, p.y, 60, 20, dir.toString());
buttonList.add(b);
if (!cons.contains(dir)) {
b.enabled = false;
}
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
@Override
public void drawScreen(int par1, int par2, float par3) {
drawDefaultBackground();
super.drawScreen(par1, par2, par3);
int butHeight = 20;
String txt = "Select Connection to Adjust";
int x = width / 2 - (Minecraft.getMinecraft().fontRenderer.getStringWidth(txt) / 2);
int y = height / 2 - butHeight * 3 - 5;
Tessellator.instance.startDrawingQuads();
drawString(Minecraft.getMinecraft().fontRenderer, txt, x, y, ColorUtil.getARGB(Color.white));
for (int i = 0; i < 6; i++) {
String blockName = adjacentBlockNames[i];
if (blockName == null) {
continue;
}
int textWidth = Minecraft.getMinecraft().fontRenderer.getStringWidth(blockName);
drawString(Minecraft.getMinecraft().fontRenderer, blockName, textPositions[i].x + 60 / 2 - textWidth / 2, textPositions[i].y, ColorUtil.getARGB(Color.gray));
}
Tessellator.instance.draw();
@Override
public boolean doesGuiPauseGame() {
return false;
}
}
@Override
public void drawScreen(int par1, int par2, float par3) {
private Point getOffsetForDir(ForgeDirection dir) {
int mx = width / 2;
int my = height / 2;
int butWidth = 60;
int butHeight = 20;
drawDefaultBackground();
int x = mx - butWidth / 2 + (dir.offsetX * butWidth);
int y = my - butHeight / 2 + (dir.offsetZ * butHeight * 2);
x += Math.abs(dir.offsetY) * (5 + butWidth * 2);
y -= (dir.offsetY * butHeight * 2);
super.drawScreen(par1, par2, par3);
return new Point(x, y);
}
int butHeight = 20;
String txt = "Select Connection to Adjust";
int x = width / 2 - (Minecraft.getMinecraft().fontRenderer.getStringWidth(txt) / 2);
int y = height / 2 - butHeight * 3 - 5;
Tessellator.instance.startDrawingQuads();
drawString(Minecraft.getMinecraft().fontRenderer, txt, x, y, ColorUtil.getARGB(Color.white));
for (int i = 0; i < 6; i++) {
String blockName = adjacentBlockNames[i];
if (blockName == null) {
continue;
}
int textWidth = Minecraft.getMinecraft().fontRenderer.getStringWidth(blockName);
drawString(
Minecraft.getMinecraft().fontRenderer,
blockName,
textPositions[i].x + 60 / 2 - textWidth / 2,
textPositions[i].y,
ColorUtil.getARGB(Color.gray));
}
Tessellator.instance.draw();
}
private Point getOffsetForDir(ForgeDirection dir) {
int mx = width / 2;
int my = height / 2;
int butWidth = 60;
int butHeight = 20;
int x = mx - butWidth / 2 + (dir.offsetX * butWidth);
int y = my - butHeight / 2 + (dir.offsetZ * butHeight * 2);
x += Math.abs(dir.offsetY) * (5 + butWidth * 2);
y -= (dir.offsetY * butHeight * 2);
return new Point(x, y);
}
}
@@ -5,18 +5,21 @@ import java.awt.Rectangle;
import java.util.Collections;
import java.util.List;
import com.enderio.core.client.gui.button.ToggleButton;
import crazypants.enderio.conduit.packet.PacketRoundRobinMode;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import org.lwjgl.opengl.GL11;
import com.enderio.core.client.gui.button.ColorButton;
import com.enderio.core.client.gui.button.IconButton;
import com.enderio.core.client.gui.button.ToggleButton;
import com.enderio.core.client.gui.button.MultiIconButton;
import com.enderio.core.client.gui.widget.GuiToolTip;
import com.enderio.core.client.render.ColorUtil;
import com.enderio.core.client.render.RenderUtil;
@@ -29,7 +32,6 @@ import crazypants.enderio.conduit.liquid.AbstractEnderLiquidConduit;
import crazypants.enderio.conduit.liquid.FluidFilter;
import crazypants.enderio.conduit.liquid.ILiquidConduit;
import crazypants.enderio.conduit.packet.PacketExtractMode;
import crazypants.enderio.conduit.packet.PacketRoundRobinMode;
import crazypants.enderio.gui.IconEIO;
import crazypants.enderio.gui.RedstoneModeButton;
import crazypants.enderio.machine.IRedstoneModeControlable;
@@ -38,402 +40,398 @@ import crazypants.enderio.network.PacketHandler;
public class LiquidSettings extends BaseSettingsPanel {
static final int ID_REDSTONE_BUTTON = GuiExternalConnection.nextButtonId();
static final int ID_REDSTONE_BUTTON = GuiExternalConnection.nextButtonId();
private static final int ID_COLOR_BUTTON = GuiExternalConnection.nextButtonId();
private static final int ID_ROUND_ROBIN_BUTTON = GuiExternalConnection.nextButtonId();
private static final int ID_INSERT_WHITELIST = GuiExternalConnection.nextButtonId();
private static final int ID_EXTRACT_WHITELIST = GuiExternalConnection.nextButtonId();
private static final int ID_COLOR_BUTTON = GuiExternalConnection.nextButtonId();
private static final int ID_ROUND_ROBIN_BUTTON = GuiExternalConnection.nextButtonId();
private static final int ID_WHITELIST = GuiExternalConnection.nextButtonId();
private static final int NEXT_FILTER_ID = 989322;
private static final int NEXT_FILTER_ID = 989322;
private static final int ID_INSERT_CHANNEL = GuiExternalConnection.nextButtonId();
private static final int ID_EXTRACT_CHANNEL = GuiExternalConnection.nextButtonId();
private static final int ID_CHANNEL = GuiExternalConnection.nextButtonId();
private final RedstoneModeButton rsB;
private final ToggleButton roundRobinB;
private final ColorButton colorB;
private ColorButton insertChannelB;
private ColorButton extractChannelB;
private final RedstoneModeButton rsB;
private final ToggleButton roundRobinB;
private final ColorButton colorB;
private ColorButton channelB;
private static final String autoExtractStr = EnderIO.lang.localize("gui.conduit.fluid.autoExtract");
private static final String filterStr = EnderIO.lang.localize("gui.conduit.fluid.filter");
private static final String autoExtractStr = EnderIO.lang.localize("gui.conduit.fluid.autoExtract");
private static final String filterStr = EnderIO.lang.localize("gui.conduit.fluid.filter");
private final ILiquidConduit conduit;
private final ILiquidConduit conduit;
private AbstractEnderLiquidConduit eConduit;
private final boolean isEnder;
private static final int filterIX = 4;
private static final int filterEX = 104;
private static final int filterY = 63;
private static final Rectangle insertFilterBounds = new Rectangle(filterIX, filterY, 90, 18);
private static final Rectangle extractFilterBounds = new Rectangle(filterEX, filterY, 90, 18);
private GuiToolTip[] filterToolTips;
private AbstractEnderLiquidConduit eConduit;
private boolean isEnder;
private static final int filterX = 59;
private static final int filterY = 63;
private static final Rectangle filterBounds = new Rectangle(filterX, filterY, 90, 18);
private GuiToolTip[] filterToolTips;
private static final boolean inOutShowIn = true;
private IconButton insertWhiteListB;
private IconButton extractWhiteListB;
private boolean inOutShowIn = true;
private MultiIconButton inOutNextB;
private IconButton whiteListB;
protected LiquidSettings(final GuiExternalConnection gui, IConduit con) {
super(
IconEIO.WRENCH_OVERLAY_FLUID,
EnderIO.lang.localize("itemLiquidConduit.name"),
gui,
con,
"in_out_settings");
this.textureHeight += 48;
protected LiquidSettings(final GuiExternalConnection gui, IConduit con) {
super(IconEIO.WRENCH_OVERLAY_FLUID, EnderIO.lang.localize("itemLiquidConduit.name"), gui, con);
conduit = (ILiquidConduit) con;
if (con instanceof AbstractEnderLiquidConduit) {
eConduit = (AbstractEnderLiquidConduit) con;
isEnder = true;
conduit = (ILiquidConduit) con;
if(con instanceof AbstractEnderLiquidConduit) {
eConduit = (AbstractEnderLiquidConduit) con;
isEnder = true;
int x = leftColumn;
int y = customTop;
insertWhiteListB = new IconButton(gui, ID_INSERT_WHITELIST, x, y, IconEIO.FILTER_WHITELIST);
insertWhiteListB.setToolTip(EnderIO.lang.localize("gui.conduit.fluid.whitelist"));
x = rightColumn;
extractWhiteListB = new IconButton(gui, ID_EXTRACT_WHITELIST, x, y, IconEIO.FILTER_WHITELIST);
extractWhiteListB.setToolTip(EnderIO.lang.localize("gui.conduit.fluid.whitelist"));
} else {
isEnder = false;
gui.getContainer().setInventorySlotsVisible(false);
int x = 52;
int y = customTop;
inOutNextB = MultiIconButton.createRightArrowButton(gui, NEXT_FILTER_ID, x, y);
x = filterX - 20;
y = filterY + 1;
whiteListB = new IconButton(gui, ID_WHITELIST, x, y, IconEIO.FILTER_WHITELIST);
whiteListB.setToolTip(EnderIO.lang.localize("gui.conduit.fluid.whitelist"));
} else {
isEnder = false;
gui.getContainer().setInventorySlotsVisible(false);
}
int x = 66;
int y = customTop;
if(isEnder)
{
channelB = new ColorButton(gui, ID_CHANNEL, x, y);
channelB.setColorIndex(0);
channelB.setToolTipHeading(EnderIO.lang.localize("gui.conduit.item.channel"));
x += channelB.getWidth() + gap;
}
rsB = new RedstoneModeButton(gui, ID_REDSTONE_BUTTON, x, y, new IRedstoneModeControlable() {
@Override
public void setRedstoneControlMode(RedstoneControlMode mode) {
RedstoneControlMode curMode = getRedstoneControlMode();
conduit.setExtractionRedstoneMode(mode, gui.getDir());
if(curMode != mode) {
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
}
int x = leftColumn + 21;
int y = customTop;
}
@Override
public RedstoneControlMode getRedstoneControlMode() {
return conduit.getExtractionRedstoneMode(gui.getDir());
}
});
x += rsB.getWidth() + gap;
colorB = new ColorButton(gui, ID_COLOR_BUTTON, x, y);
colorB.setToolTipHeading(EnderIO.lang.localize("gui.conduit.redstone.signalColor"));
colorB.setColorIndex(conduit.getExtractionSignalColor(gui.getDir()).ordinal());
if (isEnder) {
x += rsB.getWidth() + gap;
roundRobinB = new ToggleButton(gui, ID_ROUND_ROBIN_BUTTON, x, y, IconEIO.ROUND_ROBIN_OFF, IconEIO.ROUND_ROBIN);
roundRobinB.setSelectedToolTip(EnderIO.lang.localize("gui.conduit.item.roundRobinEnabled"));
roundRobinB.setUnselectedToolTip(EnderIO.lang.localize("gui.conduit.item.roundRobinDisabled"));
roundRobinB.setPaintSelectedBorder(false);
} else {
roundRobinB = null;
}
}
private void addFilterTooltips() {
filterToolTips = new GuiToolTip[5];
for (int i = 0; i < 5; i++) {
Rectangle bound = new Rectangle(filterX + (i * 18), filterY, 18, 18);
filterToolTips[i] = new FilterToolTip(bound, i);
gui.addToolTip(filterToolTips[i]);
}
}
@Override
public void actionPerformed(GuiButton guiButton) {
super.actionPerformed(guiButton);
if(guiButton.id == ID_COLOR_BUTTON) {
conduit.setExtractionSignalColor(gui.getDir(), DyeColor.values()[colorB.getColorIndex()]);
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
} else if(guiButton.id == ID_WHITELIST) {
toggleBlacklist();
} else if(guiButton.id == NEXT_FILTER_ID) {
inOutShowIn = !inOutShowIn;
if(channelB != null) {
channelB.onGuiInit();
if(isInput()) {
channelB.setColorIndex(eConduit.getInputColor(gui.getDir()).ordinal());
} else {
channelB.setColorIndex(eConduit.getOutputColor(gui.getDir()).ordinal());
}
}
if(isInput()) {
if (isEnder) {
insertChannelB = new ColorButton(gui, ID_INSERT_CHANNEL, x, y);
insertChannelB.setColorIndex(0);
insertChannelB.setToolTipHeading(EnderIO.lang.localize("gui.conduit.item.channel"));
extractChannelB = new ColorButton(gui, ID_EXTRACT_CHANNEL, x + rightColumn - leftColumn, y);
extractChannelB.setColorIndex(0);
extractChannelB.setToolTipHeading(EnderIO.lang.localize("gui.conduit.item.channel"));
x += insertChannelB.getWidth();
roundRobinB.onGuiInit();
}
x += rightColumn - leftColumn;
rsB = new RedstoneModeButton(gui, ID_REDSTONE_BUTTON, x, y, new IRedstoneModeControlable() {
@Override
public void setRedstoneControlMode(RedstoneControlMode mode) {
RedstoneControlMode curMode = getRedstoneControlMode();
conduit.setExtractionRedstoneMode(mode, gui.getDir());
if (curMode != mode) {
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
}
}
@Override
public RedstoneControlMode getRedstoneControlMode() {
return conduit.getExtractionRedstoneMode(gui.getDir());
}
});
x += rsB.getWidth();
colorB = new ColorButton(gui, ID_COLOR_BUTTON, x, y);
colorB.setToolTipHeading(EnderIO.lang.localize("gui.conduit.redstone.signalColor"));
colorB.setColorIndex(conduit.getExtractionSignalColor(gui.getDir()).ordinal());
if (isEnder) {
x += rsB.getWidth();
roundRobinB = new ToggleButton(
gui,
ID_ROUND_ROBIN_BUTTON,
x,
y,
IconEIO.ROUND_ROBIN_OFF,
IconEIO.ROUND_ROBIN);
roundRobinB.setSelectedToolTip(EnderIO.lang.localize("gui.conduit.item.roundRobinEnabled"));
roundRobinB.setUnselectedToolTip(EnderIO.lang.localize("gui.conduit.item.roundRobinDisabled"));
roundRobinB.setPaintSelectedBorder(false);
} else {
roundRobinB = null;
}
}
private void addFilterTooltips() {
filterToolTips = new GuiToolTip[5];
for (int i = 0; i < 5; i++) {
Rectangle bound = new Rectangle(filterIX + (i * 18), filterY, 18, 18);
filterToolTips[i] = new FilterToolTip(bound, i, false);
gui.addToolTip(filterToolTips[i]);
}
for (int i = 0; i < 5; i++) {
Rectangle bound = new Rectangle(filterEX + (i * 18), filterY, 18, 18);
filterToolTips[i] = new FilterToolTip(bound, i, true);
gui.addToolTip(filterToolTips[i]);
}
}
@Override
public void actionPerformed(GuiButton guiButton) {
super.actionPerformed(guiButton);
if (guiButton.id == ID_COLOR_BUTTON) {
conduit.setExtractionSignalColor(gui.getDir(), DyeColor.VALUES[colorB.getColorIndex()]);
PacketHandler.INSTANCE.sendToServer(new PacketExtractMode(conduit, gui.getDir()));
} else if (guiButton.id == ID_INSERT_WHITELIST || guiButton.id == ID_EXTRACT_WHITELIST) {
toggleBlacklist(guiButton.id == ID_EXTRACT_WHITELIST);
} else if (guiButton.id == ID_INSERT_CHANNEL || guiButton.id == ID_EXTRACT_CHANNEL) {
ColorButton btn = (ColorButton) guiButton;
if (isEnder) {
DyeColor col = DyeColor.VALUES[btn.getColorIndex()];
boolean isInput = guiButton.id == ID_EXTRACT_CHANNEL;
if (isInput) {
eConduit.setInputColor(gui.getDir(), col);
} else {
eConduit.setOutputColor(gui.getDir(), col);
}
setConduitChannel(isInput, col);
}
} else if (guiButton.id == ID_ROUND_ROBIN_BUTTON) {
if (isEnder) {
final boolean selected = roundRobinB.isSelected();
eConduit.setRoundRobin(gui.getDir(), selected);
PacketHandler.INSTANCE.sendToServer(new PacketRoundRobinMode(eConduit, gui.getDir()));
}
}
}
@Override
protected void connectionModeChanged(ConnectionMode conectionMode) {
super.connectionModeChanged(conectionMode);
updateGuiVisibility();
}
private void toggleBlacklist(boolean isInput) {
if (!isFilterVisible()) {
return;
}
FluidFilter filter = eConduit.getFilter(gui.getDir(), isInput);
if (filter == null) {
filter = new FluidFilter();
}
filter.setBlacklist(!filter.isBlacklist());
setConduitFilter(isInput, filter);
updateWhiteListButton(filter, isInput);
}
@Override
public void mouseClicked(int x, int y, int button) {
if (!isFilterVisible()) {
return;
}
ItemStack st = Minecraft.getMinecraft().thePlayer.inventory.getItemStack();
setFilterFromItem(x, y, st);
}
public boolean setFilterFromItem(int x, int y, ItemStack st) {
if (insertFilterBounds.contains(x, y)) {
FluidFilter filter = eConduit.getFilter(gui.getDir(), false);
if (filter == null && st == null) {
return false;
}
if (filter == null) {
filter = new FluidFilter();
}
int slot = (x - filterIX) / 18;
filter.setFluid(slot, st);
setConduitFilter(false, filter);
return true;
}
if (extractFilterBounds.contains(x, y)) {
FluidFilter filter = eConduit.getFilter(gui.getDir(), true);
if (filter == null && st == null) {
return false;
}
if (filter == null) {
filter = new FluidFilter();
}
int slot = (x - filterEX) / 18;
filter.setFluid(slot, st);
setConduitFilter(true, filter);
return true;
}
return false;
}
protected void setConduitFilter(boolean isInput, FluidFilter filter) {
eConduit.setFilter(gui.getDir(), filter, isInput);
PacketHandler.INSTANCE.sendToServer(new PacketFluidFilter(eConduit, gui.getDir(), filter, isInput));
}
protected void setConduitChannel(boolean isInput, DyeColor channel) {
if (isInput) {
eConduit.setInputColor(gui.getDir(), channel);
} else {
eConduit.setOutputColor(gui.getDir(), channel);
}
PacketHandler.INSTANCE.sendToServer(new PacketFluidChannel(eConduit, gui.getDir(), isInput, channel));
}
@Override
protected void initCustomOptions() {
updateGuiVisibility();
}
private void updateGuiVisibility() {
deactivate();
rsB.onGuiInit();
colorB.onGuiInit();
gui.getContainer().setInventorySlotsVisible(true);
if (!isEnder) {
return;
} else {
if (isEnder) {
roundRobinB.detach();
}
insertChannelB.onGuiInit();
insertChannelB.setColorIndex(eConduit.getOutputColor(gui.getDir()).ordinal());
extractChannelB.onGuiInit();
extractChannelB.setColorIndex(eConduit.getInputColor(gui.getDir()).ordinal());
roundRobinB.onGuiInit();
roundRobinB.setSelected(eConduit.isRoundRobin(gui.getDir()));
if (isFilterVisible()) {
addFilterTooltips();
insertWhiteListB.onGuiInit();
extractWhiteListB.onGuiInit();
updateWhiteListButtons();
}
}
private void updateWhiteListButtons() {
updateWhiteListButton(eConduit.getFilter(gui.getDir(), false), false);
updateWhiteListButton(eConduit.getFilter(gui.getDir(), true), true);
}
private void updateWhiteListButton(FluidFilter filter, boolean isInput) {
IconButton whiteListB = isInput ? extractWhiteListB : insertWhiteListB;
if (filter != null && filter.isBlacklist()) {
whiteListB.setIcon(IconEIO.FILTER_BLACKLIST);
whiteListB.setToolTip(EnderIO.lang.localize("gui.conduit.fluid.blacklist"));
} else {
whiteListB.setIcon(IconEIO.FILTER_WHITELIST);
whiteListB.setToolTip(EnderIO.lang.localize("gui.conduit.fluid.whitelist"));
}
}
@Override
public void deactivate() {
rsB.detach();
colorB.detach();
gui.getContainer().setInventorySlotsVisible(false);
if (isEnder) {
roundRobinB.detach();
if (filterToolTips != null) {
for (GuiToolTip tt : filterToolTips) {
if (tt != null) {
gui.removeToolTip(tt);
}
}
}
insertWhiteListB.detach();
extractWhiteListB.detach();
insertChannelB.detach();
extractChannelB.detach();
}
if(isFilterVisible()) {
updateWhiteListButton(eConduit.getFilter(gui.getDir(), isInput()));
}
} else if(guiButton.id == ID_CHANNEL) {
if(isEnder) {
DyeColor col = DyeColor.values()[channelB.getColorIndex()];
if (isInput()) {
eConduit.setInputColor(gui.getDir(), col);
} else {
eConduit.setOutputColor(gui.getDir(), col);
}
setConduitChannel(col);
}
} else if(guiButton.id == ID_ROUND_ROBIN_BUTTON) {
if (isEnder && isInput()) {
final boolean selected = roundRobinB.isSelected();
eConduit.setRoundRobin(gui.getDir(), selected);
PacketHandler.INSTANCE.sendToServer(new PacketRoundRobinMode(eConduit, gui.getDir()));
}
}
}
@Override
protected void connectionModeChanged(ConnectionMode conectionMode) {
super.connectionModeChanged(conectionMode);
updateGuiVisibility();
}
private void toggleBlacklist() {
if(!isFilterVisible()) {
return;
}
FluidFilter filter = eConduit.getFilter(gui.getDir(), isInput());
if(filter == null) {
filter = new FluidFilter();
}
filter.setBlacklist(!filter.isBlacklist());
setConduitFilter(filter);
updateWhiteListButton(filter);
}
@Override
public void mouseClicked(int x, int y, int par3) {
if(!isFilterVisible()) {
return;
}
if(!filterBounds.contains(x, y)) {
return;
}
ItemStack st = Minecraft.getMinecraft().thePlayer.inventory.getItemStack();
FluidFilter filter = eConduit.getFilter(gui.getDir(), isInput());
if(filter == null && st == null) {
return;
}
if(filter == null) {
filter = new FluidFilter();
}
int slot = (x - filterX) / 18;
filter.setFluid(slot, st);
setConduitFilter(filter);
}
protected void setConduitFilter(FluidFilter filter) {
eConduit.setFilter(gui.getDir(), filter, isInput());
PacketHandler.INSTANCE.sendToServer(new PacketFluidFilter(eConduit, gui.getDir(), filter, isInput()));
}
protected void setConduitChannel(DyeColor channel) {
if(isInput()) {
eConduit.setInputColor(gui.getDir(), channel);
} else {
eConduit.setOutputColor(gui.getDir(), channel);
}
PacketHandler.INSTANCE.sendToServer(new PacketFluidChannel(eConduit, gui.getDir(), isInput(), channel));
}
@Override
protected void initCustomOptions() {
updateGuiVisibility();
}
private void updateGuiVisibility() {
deactivate();
if(isInput()) {
rsB.onGuiInit();
colorB.onGuiInit();
}
if(!isEnder) {
return;
}
if(conduit.getConnectionMode(gui.getDir()) == ConnectionMode.DISABLED) {
channelB.detach();
} else {
channelB.onGuiInit();
if (isInput()) {
channelB.setColorIndex(eConduit.getInputColor(gui.getDir()).ordinal());
} else {
channelB.setColorIndex(eConduit.getOutputColor(gui.getDir()).ordinal());
}
}
if(isInput()) {
roundRobinB.onGuiInit();
roundRobinB.setSelected(eConduit.isRoundRobin(gui.getDir()));
}
if(isFilterVisible()) {
gui.getContainer().setInventorySlotsVisible(true);
addFilterTooltips();
whiteListB.onGuiInit();
updateWhiteListButton(eConduit.getFilter(gui.getDir(), isInput()));
} else {
gui.getContainer().setInventorySlotsVisible(false);
}
ConnectionMode mode = con.getConnectionMode(gui.getDir());
if(mode == ConnectionMode.IN_OUT) {
inOutNextB.onGuiInit();
}
}
private void updateWhiteListButton(FluidFilter filter) {
if(filter != null && filter.isBlacklist()) {
whiteListB.setIcon(IconEIO.FILTER_BLACKLIST);
whiteListB.setToolTip(EnderIO.lang.localize("gui.conduit.fluid.blacklist"));
} else {
whiteListB.setIcon(IconEIO.FILTER_WHITELIST);
whiteListB.setToolTip(EnderIO.lang.localize("gui.conduit.fluid.whitelist"));
}
}
@Override
public void deactivate() {
rsB.detach();
colorB.detach();
if(isEnder) {
roundRobinB.detach();
gui.getContainer().setInventorySlotsVisible(false);
if(filterToolTips != null) {
for (GuiToolTip tt : filterToolTips) {
if(tt != null) {
gui.removeToolTip(tt);
}
}
}
inOutNextB.detach();
whiteListB.detach();
channelB.detach();
}
}
@Override
protected void renderCustomOptions(int top, float par1, int par2, int par3) {
boolean isInput = isInput();
if(isEnder && isFilterVisible()) {
String inOutStr = EnderIO.lang.localize("gui.conduit.ioMode.output");
if(conduit.getConnectionMode(gui.getDir()) == ConnectionMode.IN_OUT) {
inOutStr = inOutShowIn ? EnderIO.lang.localize("gui.conduit.ioMode.input") : EnderIO.lang.localize("gui.conduit.ioMode.output");
} else if(conduit.getConnectionMode(gui.getDir()) == ConnectionMode.INPUT){
inOutStr = EnderIO.lang.localize("gui.conduit.ioMode.input");
}
int x = left;
int y = top;
gui.getFontRenderer().drawString(inOutStr, x, y, ColorUtil.getRGB(Color.DARK_GRAY));
GL11.glColor3f(1, 1, 1);
gui.bindGuiTexture(1);
gui.drawTexturedModalRect(gui.getGuiLeft(), gui.getGuiTop() + 55, 0, 55, gui.getXSize(), 145);
FontRenderer fr = gui.getFontRenderer();
int sw = fr.getStringWidth(filterStr);
x = (gui.width / 2) - sw / 2;
y = top + 20;
fr.drawString(filterStr, x, y, ColorUtil.getRGB(Color.DARK_GRAY));
x = gui.getGuiLeft() + filterX;
y = gui.getGuiTop() + filterY;
GL11.glColor3f(1, 1, 1);
gui.bindGuiTexture();
gui.drawTexturedModalRect(x, y, 24, 238, 90, 18);
FluidFilter filter = eConduit.getFilter(gui.getDir(), isInput);
if(filter != null && !filter.isEmpty()) {
for (int i = 0; i < filter.size(); i++) {
FluidStack f = filter.getFluidStackAt(i);
if(f != null) {
renderFluid(f, x + (i * 18), y);
}
}
}
}
}
private void renderFluid(FluidStack f, int x, int y) {
IIcon icon = f.getFluid().getIcon();
if(icon != null) {
RenderUtil.bindBlockTexture();
int color = f.getFluid().getColor(f);
GL11.glColor3ub((byte) (color >> 16 & 0xFF), (byte) (color >> 8 & 0xFF), (byte) (color & 0xFF));
gui.drawTexturedModelRectFromIcon(x + 1, y + 1, icon, 16, 16);
GL11.glColor3f(1, 1, 1);
}
}
private boolean isInput() {
ConnectionMode mode = conduit.getConnectionMode(gui.getDir());
return (mode == ConnectionMode.IN_OUT && inOutShowIn) || (mode == ConnectionMode.INPUT);
}
private boolean isFilterVisible() {
if(!isEnder) {
return false;
}
ConnectionMode mode = conduit.getConnectionMode(gui.getDir());
return mode == ConnectionMode.INPUT || mode == ConnectionMode.OUTPUT || mode == ConnectionMode.IN_OUT;
}
private class FilterToolTip extends GuiToolTip {
int index;
public FilterToolTip(Rectangle bounds, int index) {
super(bounds, (String[]) null);
this.index = index;
}
@Override
protected void renderCustomOptions(int top, float par1, int par2, int par3) {
if (isEnder && isFilterVisible()) {
int x = left;
int y = top;
GL11.glColor3f(1, 1, 1);
gui.bindGuiTexture(1);
// gui.drawTexturedModalRect(gui.getGuiLeft(), gui.getGuiTop() + 55, 0, 55, gui.getXSize(), 145);
FontRenderer fr = gui.getFontRenderer();
int sw = fr.getStringWidth(filterStr);
x = left + 50 - sw / 2;
y = top + 20;
fr.drawString(filterStr, x, y, ColorUtil.getRGB(Color.DARK_GRAY));
x = left + 150 - sw / 2;
fr.drawString(filterStr, x, y, ColorUtil.getRGB(Color.DARK_GRAY));
x = gui.getGuiLeft() + filterIX;
y = gui.getGuiTop() + filterY;
GL11.glColor3f(1, 1, 1);
gui.bindGuiTexture();
gui.drawTexturedModalRect(x, y, 24, 238, 90, 18);
FluidFilter filter = eConduit.getFilter(gui.getDir(), false);
if (filter != null && !filter.isEmpty()) {
for (int i = 0; i < filter.size(); i++) {
FluidStack f = filter.getFluidStackAt(i);
if (f != null) {
renderFluid(f, x + (i * 18), y);
}
}
}
x = gui.getGuiLeft() + filterEX;
GL11.glColor3f(1, 1, 1);
gui.bindGuiTexture();
gui.drawTexturedModalRect(x, y, 24, 238, 90, 18);
filter = eConduit.getFilter(gui.getDir(), true);
if (filter != null && !filter.isEmpty()) {
for (int i = 0; i < filter.size(); i++) {
FluidStack f = filter.getFluidStackAt(i);
if (f != null) {
renderFluid(f, x + (i * 18), y);
}
}
}
}
public List<String> getToolTipText() {
if(!isFilterVisible()) {
return null;
}
FluidFilter filter = eConduit.getFilter(gui.getDir(), isInput());
if(filter == null) {
return null;
}
if (filter.getFluidStackAt(index) == null) {
return null;
}
return Collections.singletonList(filter.getFluidStackAt(index).getLocalizedName());
}
private void renderFluid(FluidStack f, int x, int y) {
IIcon icon = f.getFluid().getIcon();
if (icon != null) {
RenderUtil.bindBlockTexture();
int color = f.getFluid().getColor(f);
GL11.glColor3ub((byte) (color >> 16 & 0xFF), (byte) (color >> 8 & 0xFF), (byte) (color & 0xFF));
gui.drawTexturedModelRectFromIcon(x + 1, y + 1, icon, 16, 16);
GL11.glColor3f(1, 1, 1);
}
}
}
private boolean isFilterVisible() {
return isEnder;
}
private class FilterToolTip extends GuiToolTip {
int index;
boolean isInput;
public FilterToolTip(Rectangle bounds, int index, boolean isInput) {
super(bounds, (String[]) null);
this.index = index;
this.isInput = isInput;
}
@Override
public List<String> getToolTipText() {
if (!isFilterVisible()) {
return null;
}
FluidFilter filter = eConduit.getFilter(gui.getDir(), isInput);
if (filter == null) {
return null;
}
if (filter.getFluidStackAt(index) == null) {
return null;
}
return Collections.singletonList(filter.getFluidStackAt(index).getLocalizedName());
}
}
}
Loaded 100 of 1660 files, more files were not shown because too many files have changed in this diff. Show more