Compare commits

..
8 Commits
36 changed files with 515 additions and 2209 deletions

No files matched your search

-9
View File
@@ -1,9 +0,0 @@
directory="run/crash-reports"
if [ -d $directory ]; then
echo "Crash reports detected:"
cat $directory/*
exit 1
else
echo "No crash reports detected"
exit 0
fi
@@ -1,16 +1,14 @@
# 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
name: Build pull request
on:
pull_request:
branches: [ master, main ]
push:
branches: [ master, main ]
jobs:
build-and-test:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -32,14 +30,3 @@ jobs:
- name: Build the mod
run: ./gradlew build
- name: Run server for 1 minute
run: |
mkdir run
echo "eula=true" > run/eula.txt
timeout 10 ./gradlew runServer || true
- name: Test no crashes happend
run: |
chmod +x .github/scripts/test-no-crash-reports.sh
.github/scripts/test-no-crash-reports.sh
-45
View File
@@ -1,45 +0,0 @@
# 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:
- '*'
jobs:
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
+41
View File
@@ -0,0 +1,41 @@
# 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 release main branch
on:
push:
branches: [ master, main ]
jobs:
build:
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
- uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "latest"
prerelease: true
title: "Latest Development Build"
files: build/libs/*.jar
-1
View File
@@ -26,4 +26,3 @@ whitelist.json
*.ipr
*.iws
src/main/resources/mixins.*.json
*.bat
+50 -133
View File
@@ -1,4 +1,4 @@
//version: 8fa7883b6196c1765266f4e6ddf3118d5043aafb
//version: eb0b030ab9cb1d0f9a31f11e69e1ceed1dab2c89
/*
DO NOT CHANGE THIS FILE!
@@ -42,7 +42,6 @@ plugins {
id("org.ajoberstar.grgit") version("3.1.1")
id("com.github.johnrengelman.shadow") version("4.0.4")
id("com.palantir.git-version") version("0.12.3")
id("maven-publish")
}
apply plugin: 'forge'
@@ -63,10 +62,6 @@ idea {
}
}
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")
@@ -88,27 +83,33 @@ checkPropertyExists("containsMixinsAndOrCoreModOnly")
checkPropertyExists("usesShadowedDependencies")
checkPropertyExists("developmentEnvironmentUserName")
def checkPropertyExists(String propertyName) {
if (project.hasProperty(propertyName) == false) {
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/SinTh0r4s/ExampleMod1.7.10/blob/main/gradle.properties")
}
}
String javaSourceDir = "src/main/java/"
String scalaSourceDir = "src/main/scala/"
String targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/")
String targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/")
if((getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists()) == false) {
if((new File(targetPackageJava).exists() || new File(targetPackageScala).exists()) == false) {
throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava + " or " + targetPackageScala)
}
if(apiPackage) {
targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/")
targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/")
if((getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists()) == false) {
if((new File(targetPackageJava).exists() || new File(targetPackageScala).exists()) == false) {
throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala)
}
}
if(accessTransformersFile) {
String targetFile = "src/main/resources/META-INF/" + accessTransformersFile
if(getFile(targetFile).exists() == false) {
if(new File(targetFile).exists() == false) {
throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile)
}
}
@@ -120,14 +121,14 @@ if(usesMixins.toBoolean()) {
targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/")
targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/")
if((getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists()) == false) {
if((new File(targetPackageJava).exists() || new File(targetPackageScala).exists()) == false) {
throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala)
}
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"
if((getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists()) == false) {
if((new File(targetFileJava).exists() || new File(targetFileScala).exists() || new File(targetFileScalaJava).exists()) == false) {
throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava)
}
}
@@ -136,7 +137,7 @@ 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"
if((getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists()) == false) {
if((new File(targetFileJava).exists() || new File(targetFileScala).exists() || new File(targetFileScalaJava).exists()) == false) {
throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava)
}
}
@@ -152,20 +153,9 @@ configurations.all {
// Fix Jenkins' Git: chmod a file should not be detected as a change and append a '.dirty' to the version
'git config core.fileMode false'.execute()
// Pulls version from git tag
try {
version = minecraftVersion + "-" + gitVersion()
}
catch (Exception e) {
throw new IllegalStateException("This mod must be version controlled by Git AND the repository must provide at least one tag!");
}
version = minecraftVersion + "-" + gitVersion()
group = modGroup
if(project.hasProperty("customArchiveBaseName") && customArchiveBaseName) {
archivesBaseName = customArchiveBaseName
}
else {
archivesBaseName = modId
}
archivesBaseName = modId
minecraft {
version = minecraftVersion + "-" + forgeVersion + "-" + minecraftVersion
@@ -195,9 +185,7 @@ if(file("addon.gradle").exists()) {
apply from: 'repositories.gradle'
configurations {
implementation.extendsFrom(shadowImplementation) // TODO: remove after all uses are refactored
implementation.extendsFrom(shadowCompile)
implementation.extendsFrom(shadeCompile)
implementation.extendsFrom(shadowImplementation)
}
repositories {
@@ -237,13 +225,14 @@ dependencies {
apply from: 'dependencies.gradle'
def mixinConfigJson = "mixins." + modId + ".json"
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()) {
getFile("/src/main/resources/mixins." + modId + ".json").text = """{
new File(projectDir.toString() + "/src/main/resources/", mixinConfigJson).text = """{
"required": true,
"minVersion": "0.7.11",
"package": "${modGroup}.${mixinsPackage}",
@@ -263,28 +252,16 @@ task relocateShadowJar(type: ConfigureShadowRelocation) {
}
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]
configurations = [project.configurations.shadowImplementation]
dependsOn(relocateShadowJar)
}
jar {
project.configurations.shadeCompile.each { dep ->
from(project.zipTree(dep)) {
exclude 'META-INF', 'META-INF/**'
}
}
manifest {
attributes(getManifestAttributes())
}
@@ -358,35 +335,31 @@ tasks.withType(JavaExec).configureEach {
}
processResources
{
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
{
// 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 stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand "minecraftVersion": project.minecraft.version,
"modVersion": versionDetails().lastTag,
"modId": modId,
"modName": modName
}
// replace version and mcversion
expand "minecraftVersion": project.minecraft.version,
"modVersion": versionDetails().lastTag,
"modId": modId,
"modName": modName
}
if(usesMixins.toBoolean()) {
from refMap
}
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
// copy everything else, thats not the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
def getManifestAttributes() {
def manifestAttributes = [:]
if(containsMixinsAndOrCoreModOnly.toBoolean() == false && (usesMixins.toBoolean() || coreModClass)) {
if(containsMixinsAndOrCoreModOnly.toBoolean() == false) {
manifestAttributes += ["FMLCorePluginContainsFMLMod": true]
}
@@ -401,7 +374,7 @@ def getManifestAttributes() {
if(usesMixins.toBoolean()) {
manifestAttributes += [
"TweakClass" : "org.spongepowered.asm.launch.MixinTweaker",
"MixinConfigs" : "mixins." + modId + ".json",
"MixinConfigs" : mixinConfigJson,
"ForceLoadAsMod" : containsMixinsAndOrCoreModOnly.toBoolean() == false
]
}
@@ -415,12 +388,6 @@ task sourcesJar(type: Jar) {
}
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")
@@ -429,7 +396,7 @@ task shadowDevJar(type: ShadowJar) {
}
minimize() // This will only allow shading for actually used classes
configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile]
configurations = [project.configurations.shadowImplementation]
}
task relocateShadowDevJar(type: ConfigureShadowRelocation) {
@@ -444,12 +411,6 @@ task circularResolverJar(type: Jar) {
}
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")
@@ -465,11 +426,11 @@ task devJar(type: Jar) {
task apiJar(type: Jar) {
from (sourceSets.main.allJava) {
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**'
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString() + '/**'
}
from (sourceSets.main.output) {
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**'
include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString() + '/**'
}
from (sourceSets.main.resources.srcDirs) {
@@ -487,50 +448,18 @@ artifacts {
}
}
// publishing
publishing {
publications {
maven(MavenPublication) {
artifact source: jar
artifact source: sourcesJar, classifier: "src"
artifact source: devJar, classifier: "dev"
if (apiPackage) {
artifact source: apiJar, classifier: "api"
}
groupId = System.getenv("ARTIFACT_GROUP_ID") ?: group
artifactId = System.getenv("ARTIFACT_ID") ?: project.name
version = System.getenv("ARTIFACT_VERSION") ?: project.version
}
}
repositories {
maven {
String owner = System.getenv("REPOSITORY_OWNER") ?: "Unknown"
String repositoryName = System.getenv("REPOSITORY_NAME") ?: "Unknown"
String githubRepositoryUrl = "https://maven.pkg.github.com/$owner/$repositoryName"
name = "GitHubPackages"
url = githubRepositoryUrl
credentials {
username = System.getenv("GITHUB_ACTOR") ?: "NONE"
password = System.getenv("GITHUB_TOKEN") ?: "NONE"
}
}
}
}
// Updating
task updateBuildScript {
doLast {
if (performBuildScriptUpdate(projectDir.toString())) return
if (updateBuildScript()) return
print("Build script already up-to-date!")
}
}
if (isNewBuildScriptVersionAvailable(projectDir.toString())) {
if (isNewBuildScriptVersionAvailable()) {
if (autoUpdateBuildScript.toBoolean()) {
performBuildScriptUpdate(projectDir.toString())
updateBuildScript()
} else {
println("Build script update available! Run 'gradle updateBuildScript'")
}
@@ -540,9 +469,9 @@ static URL availableBuildScriptUrl() {
new URL("https://raw.githubusercontent.com/SinTh0r4s/ExampleMod1.7.10/main/build.gradle")
}
boolean performBuildScriptUpdate(String projectDir) {
if (isNewBuildScriptVersionAvailable(projectDir)) {
def buildscriptFile = getFile("build.gradle")
static boolean updateBuildScript() {
if (isNewBuildScriptVersionAvailable()) {
def buildscriptFile = new File("build.gradle")
availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } }
print("Build script updated. Please REIMPORT the project or RESTART your IDE!")
return true
@@ -550,10 +479,10 @@ boolean performBuildScriptUpdate(String projectDir) {
return false
}
boolean isNewBuildScriptVersionAvailable(String projectDir) {
static boolean isNewBuildScriptVersionAvailable() {
Map parameters = ["connectTimeout": 2000, "readTimeout": 2000]
String currentBuildScript = getFile("build.gradle").getText()
String currentBuildScript = new File("build.gradle").getText()
String currentBuildScriptHash = getVersionHash(currentBuildScript)
String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText()
String availableBuildScriptHash = getVersionHash(availableBuildScript)
@@ -574,15 +503,3 @@ configure(updateBuildScript) {
group = 'forgegradle'
description = 'Updates the build script to the latest version'
}
// Helper methods
def checkPropertyExists(String propertyName) {
if (project.hasProperty(propertyName) == false) {
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/SinTh0r4s/ExampleMod1.7.10/blob/main/gradle.properties")
}
}
def getFile(String relativePath) {
return new File(projectDir, relativePath)
}
+76 -686
View File
@@ -1,481 +1,94 @@
package codechicken.nei;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.util.NBTJson;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.BookmarkRecipeId;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.ItemPanel.ItemPanelSlot;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.io.IOUtils;
import static codechicken.lib.gui.GuiDraw.getMousePosition;
import static codechicken.lib.gui.GuiDraw.drawRect;
import java.awt.Point;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class BookmarkPanel extends ItemPanel
{
/*
* TODO:
* 1) Bookmark button to toggle visibility
*/
public class BookmarkPanel extends ItemPanel {
protected boolean bookmarksIsLoaded = false;
public int sortedStackIndex = -1;
public int sortedNamespaceIndex = -1;
public Button namespacePrev;
public Button namespaceNext;
public Label namespaceLabel;
protected ArrayList<BookmarkGrid> namespaces = new ArrayList<>();
public int activeNamespaceIndex = 0;
protected static class BookmarkStackMeta
{
public int factor;
public BookmarkRecipeId recipeId;
public boolean ingredient = false;
public BookmarkStackMeta(BookmarkRecipeId recipeId, int count, boolean ingredient)
{
this.recipeId = recipeId;
this.factor = count;
this.ingredient = ingredient;
}
}
protected static class BookmarkGrid extends ItemsGrid
{
protected List<BookmarkStackMeta> metadata = new ArrayList<>();
public int indexOf(ItemStack stackA, BookmarkRecipeId recipeId)
{
final boolean useNBT = NEIClientConfig.useNBTInBookmarks();
for (int idx = 0; idx < realItems.size(); idx++) {
final BookmarkStackMeta meta = getMetadata(idx);
if ((recipeId == null && meta.recipeId == null || recipeId != null && meta.recipeId != null && recipeId.equals(meta.recipeId)) && StackInfo.equalItemAndNBT(stackA, realItems.get(idx), useNBT)) {
return idx;
}
}
return -1;
}
public BookmarkStackMeta getMetadata(int idx)
{
return metadata.get(idx);
}
public void addItem(ItemStack stackA, BookmarkStackMeta meta)
{
realItems.add(stackA);
metadata.add(meta);
needRefresh = true;
}
public void replaceItem(int idx, ItemStack stack)
{
realItems.set(idx, stack);
}
public void removeRecipe(int idx, boolean removeFullRecipe)
{
final BookmarkStackMeta meta = getMetadata(idx);
if (removeFullRecipe && meta.recipeId != null) {
removeRecipe(meta.recipeId);
} else {
removeItem(idx);
}
}
public void removeRecipe(BookmarkRecipeId recipeIdA)
{
BookmarkRecipeId recipeIdB;
for (int slotIndex = metadata.size() - 1; slotIndex >= 0; slotIndex--) {
recipeIdB = getRecipeId(slotIndex);
if (recipeIdB != null && recipeIdA.equals(recipeIdB)) {
removeItem(slotIndex);
}
}
}
protected boolean removeItem(int idx)
{
realItems.remove(idx);
metadata.remove(idx);
needRefresh = true;
return true;
}
public BookmarkRecipeId getRecipeId(int idx)
{
return getMetadata(idx).recipeId;
}
public BookmarkRecipeId findRecipeId(ItemStack stackA)
{
final boolean useNBT = NEIClientConfig.useNBTInBookmarks();
for (int idx = 0; idx < realItems.size(); idx++) {
if (StackInfo.equalItemAndNBT(stackA, getItem(idx), useNBT)) {
return getRecipeId(idx);
}
}
return null;
}
public void moveItem(int src, int dst)
{
realItems.add(dst, realItems.remove(src));
metadata.add(dst, metadata.remove(src));
needRefresh = true;
}
@Override
protected void drawItem(Rectangle4i rect, int idx, ItemPanelSlot focus)
{
if (LayoutManager.bookmarkPanel.sortedNamespaceIndex == LayoutManager.bookmarkPanel.activeNamespaceIndex && LayoutManager.bookmarkPanel.sortedStackIndex == idx) {
drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555);//highlight
} else {
if (focus != null) {
if (focus.slotIndex == idx) {
drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555);//highlight
} else if (
LayoutManager.bookmarkPanel.sortedStackIndex == -1 && //disabled when sorting
NEIClientUtils.shiftKey() && //show only with shift key
getRecipeId(focus.slotIndex) != null && getRecipeId(idx) != null && getRecipeId(focus.slotIndex).equals(getRecipeId(idx))//is some recipeId
) {
drawRect(rect.x, rect.y, rect.w, rect.h, getMetadata(idx).ingredient? 0x88b3b300: 0x88009933);//highlight recipe
}
}
GuiContainerManager.drawItem(rect.x + 1, rect.y + 1, getItem(idx), true);
}
}
}
public BookmarkPanel()
{
grid = new BookmarkGrid();
}
public void init()
{
public void init() {
super.init();
namespaceLabel = new Label("1", true);
namespacePrev = new Button("Prev")
{
public boolean onButtonPress(boolean rightclick)
{
if (rightclick) {
return false;
}
return prevNamespace();
}
@Override
public String getRenderLabel()
{
return "<";
}
};
namespaceNext = new Button("Next")
{
public boolean onButtonPress(boolean rightclick)
{
if (rightclick) {
return false;
}
return nextNamespace();
}
@Override
public String getRenderLabel()
{
return ">";
}
};
namespaces.add(new BookmarkGrid());
grid = namespaces.get(activeNamespaceIndex);
}
@Override
public String getLabelText()
{
return super.getLabelText() + " [" + grid.size() + "]";
protected void setItems() {
realItems = _items;
}
public void addOrRemoveItem(ItemStack stackA)
{
addOrRemoveItem(stackA, "", null);
public String getLabelText() {
return super.getLabelText() + " [" + realItems.size() + "]";
}
public void addOrRemoveItem(ItemStack stackover, String handlerName, List<PositionedStack> ingredients)
{
loadBookmarksIfNeeded();
final Point mousePos = getMousePosition();
final ItemPanelSlot slot = getSlotMouseOver(mousePos.x, mousePos.y);
final boolean addFullRecipe = NEIClientUtils.shiftKey();
final BookmarkGrid BGrid = (BookmarkGrid) grid;
if (slot != null && StackInfo.equalItemAndNBT(slot.item, stackover, true)) {
BGrid.removeRecipe(slot.slotIndex, addFullRecipe);
} else {
final boolean saveStackSize = NEIClientUtils.controlKey();
final NBTTagCompound nbTagA = StackInfo.itemStackToNBT(stackover, saveStackSize);
final ItemStack normalizedA = StackInfo.loadFromNBT(nbTagA);
BookmarkRecipeId recipeId = null;
if (NEIClientConfig.saveCurrentRecipeInBookmarksEnabled() && handlerName != "" && ingredients != null && ingredients.size() > 0) {
recipeId = new BookmarkRecipeId(handlerName, ingredients);
}
final int idx = BGrid.indexOf(normalizedA, recipeId);
if (idx != -1) {
BGrid.removeRecipe(idx, addFullRecipe);
} else {
if (addFullRecipe && handlerName != "" && ingredients != null) {
final Map<NBTTagCompound, Integer> unique = new HashMap<>();
final ArrayList<NBTTagCompound> sorted = new ArrayList<>();
BGrid.removeRecipe(recipeId);
for (PositionedStack stack : ingredients) {
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(stack.item, saveStackSize);
if (nbTag.getInteger("Count") > 0) {
if (unique.get(nbTag) == null) {
unique.put(nbTag, 1);
sorted.add(nbTag);
} else if (saveStackSize) {
unique.put(nbTag, unique.get(nbTag) + 1);
}
}
}
for (NBTTagCompound nbTag : sorted) {
nbTag.setInteger("Count", nbTag.getInteger("Count") * unique.get(nbTag));
BGrid.addItem(StackInfo.loadFromNBT(nbTag), new BookmarkStackMeta(recipeId, nbTag.getInteger("Count"), true));
}
}
BGrid.addItem(normalizedA, new BookmarkStackMeta(recipeId, nbTagA.getInteger("Count"), false));
}
public void addOrRemoveItem(ItemStack item) {
ItemStack normalized = normalize(item);
if(!remove(normalized)) {
_items.add(normalized);
}
saveBookmarks();
}
public BookmarkRecipeId getBookmarkRecipeId(ItemStack stackA)
public static NBTTagCompound itemStackToNBT(ItemStack stack, NBTTagCompound nbTag)
{
String strId = Item.itemRegistry.getNameForObject(stack.getItem());
nbTag.setString("strId", strId);
nbTag.setByte("Count", (byte)stack.stackSize);
nbTag.setShort("Damage", (short)stack.getItemDamage());
final Point mousePos = getMousePosition();
final ItemPanelSlot slot = getSlotMouseOver(mousePos.x, mousePos.y);
if (slot != null && StackInfo.equalItemAndNBT(slot.item, stackA, true)) {
return ((BookmarkGrid) grid).getRecipeId(slot.slotIndex);
if (stack.stackTagCompound != null)
{
nbTag.setTag("tag", stack.stackTagCompound);
}
BookmarkRecipeId recipeId = ((BookmarkGrid) grid).findRecipeId(stackA);
if (recipeId == null) {
for (int idx = 0; idx < namespaces.size() && recipeId == null; idx++) {
if (idx == activeNamespaceIndex) continue;
recipeId = namespaces.get(idx).findRecipeId(stackA);
}
}
return recipeId;
return nbTag;
}
protected String getNamespaceLabelText(boolean shortFormat)
public static ItemStack loadFromNBT(NBTTagCompound nbtTag)
{
String activePage = String.valueOf(activeNamespaceIndex + 1);
return shortFormat? activePage: (activePage + "/" + fixCountOfNamespaces());
if (!nbtTag.hasKey("id")) {
final short id = (short)GameData.getItemRegistry().getId(nbtTag.getString("strId"));
nbtTag.setShort("id", id);
}
ItemStack stack = ItemStack.loadItemStackFromNBT(nbtTag);
return stack;
}
protected int fixCountOfNamespaces()
{
if (namespaces.get(namespaces.size() - 1).size() > 0) {
namespaces.add(new BookmarkGrid());
} else if (activeNamespaceIndex == namespaces.size() - 2 && grid.size() == 0) {
namespaces.remove(namespaces.size() - 1);
public void saveBookmarks() {
List<String> strings = new ArrayList<>();
for (ItemStack item:_items) {
strings.add(NBTJson.toJson(itemStackToNBT(item, new NBTTagCompound())));
}
return namespaces.size();
}
protected boolean removeEmptyNamespaces()
{
if (activeNamespaceIndex != namespaces.size() - 1 && grid.size() == 0) {
namespaces.remove(activeNamespaceIndex);
grid = namespaces.get(activeNamespaceIndex);
return true;
}
return false;
}
protected boolean prevNamespace()
{
if (!bookmarksIsLoaded) {
return false;
}
fixCountOfNamespaces();
removeEmptyNamespaces();
if (activeNamespaceIndex == 0) {
activeNamespaceIndex = namespaces.size() - 1;
} else {
activeNamespaceIndex --;
}
grid = namespaces.get(activeNamespaceIndex);
return true;
}
protected boolean nextNamespace()
{
if (!bookmarksIsLoaded) {
return false;
}
if (removeEmptyNamespaces()) {
return true;
}
if (activeNamespaceIndex == fixCountOfNamespaces() - 1) {
activeNamespaceIndex = 0;
} else {
activeNamespaceIndex ++;
}
grid = namespaces.get(activeNamespaceIndex);
return true;
}
public void saveBookmarks()
{
ArrayList<String> strings = new ArrayList<>();
for (int grpIdx = 0; grpIdx < namespaces.size() - 1; grpIdx++) {
final BookmarkGrid grid = namespaces.get(grpIdx);
if (grpIdx > 0) {
strings.add("");//namespace separator; ignore first namespace
}
for (int idx = 0; idx < grid.size(); idx++) {
try {
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(grid.getItem(idx));
if (nbTag != null) {
JsonObject row = new JsonObject();
BookmarkStackMeta meta = grid.getMetadata(idx);
row.add("item", NBTJson.toJsonObject(nbTag));
row.add("factor", new JsonPrimitive(meta.factor));
row.add("ingredient", new JsonPrimitive(meta.ingredient));
if (meta.recipeId != null) {
row.add("recipeId", meta.recipeId.toJsonObject());
}
strings.add(NBTJson.toJson(row));
}
} catch (JsonSyntaxException e) {
NEIClientConfig.logger.error("Failed to stringify bookmarked ItemStack to json string");
}
}
}
File file = NEIClientConfig.bookmarkFile;
if (file != null) {
if(file != null) {
try(FileWriter writer = new FileWriter(file)) {
IOUtils.writeLines(strings, "\n", writer);
} catch (IOException e) {
NEIClientConfig.logger.error("Filed to save bookmarks list to file {}", file, e);
}
}
}
public void loadBookmarksIfNeeded()
{
if (bookmarksIsLoaded) {
return;
}
bookmarksIsLoaded = true;
public void loadBookmarks() {
File file = NEIClientConfig.bookmarkFile;
if (file == null || !file.exists()) {
return;
}
List<String> itemStrings;
try (FileReader reader = new FileReader(file)) {
NEIClientConfig.logger.info("Loading bookmarks from file {}", file);
@@ -484,301 +97,78 @@ public class BookmarkPanel extends ItemPanel
NEIClientConfig.logger.error("Failed to load bookmarks from file {}", file, e);
return;
}
namespaces.clear();
namespaces.add(new BookmarkGrid());
activeNamespaceIndex = 0;
final JsonParser parser = new JsonParser();
_items.clear();
JsonParser parser = new JsonParser();
for (String itemStr: itemStrings) {
try {
if (itemStr.isEmpty()) {
if (namespaces.get(activeNamespaceIndex).size() > 0) {
//do not create empty namespaces
namespaces.add(new BookmarkGrid());
activeNamespaceIndex++;
}
continue;
}
JsonObject jsonObject = parser.parse(itemStr).getAsJsonObject();
BookmarkRecipeId recipeId = null;
NBTTagCompound itemStackNBT;
if (jsonObject.get("item") != null) {
itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject.get("item"));
} else {// old format
itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject);
}
if (jsonObject.get("recipeId") != null && jsonObject.get("recipeId") instanceof JsonObject) {
recipeId = new BookmarkRecipeId((JsonObject) jsonObject.get("recipeId"));
}
ItemStack itemStack = StackInfo.loadFromNBT(itemStackNBT);
NBTTagCompound itemStackNBT = (NBTTagCompound) NBTJson.toNbt(parser.parse(itemStr));
ItemStack itemStack = loadFromNBT(itemStackNBT);
if (itemStack != null) {
namespaces.get(activeNamespaceIndex).addItem(itemStack, new BookmarkStackMeta(
recipeId,
jsonObject.has("factor")? jsonObject.get("factor").getAsInt(): 1,
jsonObject.has("ingredient")? jsonObject.get("ingredient").getAsBoolean(): false
));
_items.add(itemStack);
} else {
NEIClientConfig.logger.warn("Failed to load bookmarked ItemStack from json string, the item no longer exists:\n{}", itemStr);
}
} catch (IllegalArgumentException | JsonSyntaxException e) {
NEIClientConfig.logger.error("Failed to load bookmarked ItemStack from json string:\n{}", itemStr);
}
}
}
if (namespaces.get(activeNamespaceIndex).size() == 0) {
activeNamespaceIndex = Math.max(activeNamespaceIndex - 1, 0);
protected ItemStack normalize(ItemStack item) {
ItemStack copy = item.copy();
copy.stackSize = 1;
return copy;
}
private boolean remove(ItemStack item) {
int i = 0;
for (ItemStack existing : _items) {
if (existing == item || existing.isItemEqual(item)) {
_items.remove(i);
return true;
}
i++;
}
grid = namespaces.get(activeNamespaceIndex);
}
@Override
public void resize(GuiContainer gui)
{
loadBookmarksIfNeeded();
super.resize(gui);
final int buttonHeight = 16;
final int buttonWidth = 16;
final int buttonTop = gui.height - buttonHeight - 2;
final int leftBorder = LayoutManager.bookmarksButton.x + LayoutManager.bookmarksButton.w + 2;
final int rightBorder = x + w;
final int center = leftBorder + (rightBorder - leftBorder) / 2;
int labelWidth = 2;
namespacePrev.h = namespaceNext.h = buttonHeight;
namespacePrev.w = namespaceNext.w = buttonWidth;
namespacePrev.y = namespaceNext.y = buttonTop;
if (rightBorder - leftBorder >= 70) {
labelWidth = 36;
namespaceLabel.text = getNamespaceLabelText(false);
} else {
labelWidth = 18;
namespaceLabel.text = getNamespaceLabelText(true);
}
namespaceLabel.y = buttonTop + 5;
namespaceLabel.x = center;
namespacePrev.x = center - labelWidth / 2 - 2 - namespacePrev.w;
namespaceNext.x = center + labelWidth / 2 + 2;
return false;
}
@Override
public void setVisible()
{
super.setVisible();
LayoutManager.addWidget(namespacePrev);
LayoutManager.addWidget(namespaceNext);
LayoutManager.addWidget(namespaceLabel);
}
@Override
public int getMarginLeft(GuiContainer gui)
{
public int getX(GuiContainer gui) {
return 5;
}
@Override
public int getMarginTop(GuiContainer gui)
{
public int getMarginLeft() {
return 5;
}
@Override
public int getButtonTop() {
LayoutStyleMinecraft layout = (LayoutStyleMinecraft)LayoutManager.getLayoutStyle();
return 2 + (((int)Math.ceil((double)layout.buttonCount / layout.numButtons)) * 18);
}
@Override
public int getWidth(GuiContainer gui)
{
return LayoutManager.getLeftSize(gui) - ((gui.xSize + gui.width) / 2 + 3) - 16;
public int getNextX(GuiContainer gui) {
return gui.width - prev.w - 2 - ((gui.xSize + gui.width) /2 + 2) - 16;
}
@Override
public int getHeight(GuiContainer gui)
{
// - 19 = 22 + 1 -> input in bottom
return gui.height - getMarginTop(gui) - 23;
}
@Override
public void mouseDragged(int mousex, int mousey, int button, long heldTime)
{
if (button == 0 && NEIClientUtils.shiftKey() && mouseDownSlot >= 0) {
ItemPanelSlot mouseOverSlot = getSlotMouseOver(mousex, mousey);
if (sortedStackIndex == -1) {
final ItemStack stack = grid.getItem(mouseDownSlot);
if (stack != null && (mouseOverSlot == null || mouseOverSlot.slotIndex != mouseDownSlot || heldTime > 250)) {
sortedNamespaceIndex = activeNamespaceIndex;
sortedStackIndex = mouseDownSlot;
}
} else {
if (mouseOverSlot == null && sortedNamespaceIndex != activeNamespaceIndex) {
mouseOverSlot = getNextSlot(mousex, mousey);
}
if (mouseOverSlot != null) {
if (sortedNamespaceIndex != activeNamespaceIndex) {
BookmarkGrid BGrid = namespaces.get(sortedNamespaceIndex);
BookmarkStackMeta meta = BGrid.getMetadata(sortedStackIndex);
ItemStack stack = BGrid.getItem(sortedStackIndex);
BGrid.removeItem(sortedStackIndex);
((BookmarkGrid) grid).addItem(stack, meta);
sortedNamespaceIndex = activeNamespaceIndex;
sortedStackIndex = grid.size() - 1;
}
if (mouseOverSlot.slotIndex != sortedStackIndex) {
((BookmarkGrid) grid).moveItem(sortedStackIndex, mouseOverSlot.slotIndex);
sortedStackIndex = mouseOverSlot.slotIndex;
}
}
}
return;
}
super.mouseDragged(mousex, mousey, button, heldTime);
}
private ItemPanelSlot getNextSlot(int mousex, int mousey)
{
int idx = grid.getPage() * grid.getPerPage() - grid.getPerPage();
int gSize = grid.size();
for (int i = 0; i < grid.getRows() * grid.getColumns() && idx <= gSize; i++) {
if (!grid.isInvalidSlot(i)) {
if (idx == gSize && grid.getSlotRect(i).contains(mousex, mousey)) {
return new ItemPanelSlot(idx, null);
}
idx++;
}
}
return null;
public int getPrevX(GuiContainer gui) {
return 2;
}
@Override
public void postDraw(int mousex, int mousey)
{
if (sortedStackIndex != -1) {
GuiContainerManager.drawItems.zLevel += 100;
GuiContainerManager.drawItem(mousex - 8, mousey - 8, namespaces.get(sortedNamespaceIndex).getItem(sortedStackIndex).copy(), true);
GuiContainerManager.drawItems.zLevel -= 100;
}
super.postDraw(mousex, mousey);
public int getPageX(GuiContainer gui) {
return gui.guiLeft * 3 / 2 + gui.xSize + 1 - ((gui.xSize + gui.width) / 2 + 2) - 16;
}
@Override
protected ItemStack getDraggedStackWithQuantity(int mouseDownSlot)
{
ItemStack stack = grid.getItem(mouseDownSlot);
return stack != null? stack.copy(): null;
public int getHightAdjustment() {
return 0;
}
@Override
public void mouseUp(int mousex, int mousey, int button)
{
if (sortedStackIndex != -1) {
sortedNamespaceIndex = -1;
sortedStackIndex = -1;
mouseDownSlot = -1;
saveBookmarks();
} else {
super.mouseUp(mousex, mousey, button);
}
}
@Override
public boolean onMouseWheel(int shift, int mousex, int mousey)
{
if (new Rectangle4i(namespacePrev.x, namespacePrev.y, namespaceNext.x + namespaceNext.w - namespacePrev.x, namespacePrev.h).contains(mousex, mousey)) {
if (shift > 0) {
prevNamespace();
} else {
nextNamespace();
}
return true;
}
if (!contains(mousex, mousey)) {
return false;
}
if (NEIClientUtils.controlKey()) {
final ItemPanelSlot slot = getSlotMouseOver(mousex, mousey);
if (slot != null) {
final BookmarkGrid BGrid = (BookmarkGrid)grid;
final BookmarkRecipeId recipeId = BGrid.getRecipeId(slot.slotIndex);
final BookmarkStackMeta meta = BGrid.getMetadata(slot.slotIndex);
final boolean addFullRecipe = NEIClientUtils.shiftKey();
if (addFullRecipe) {
BookmarkStackMeta iMeta;
for (int slotIndex = grid.size() - 1; slotIndex >= 0; slotIndex--) {
iMeta = BGrid.getMetadata(slotIndex);
if (iMeta.recipeId != null && iMeta.recipeId.equals(recipeId)) {
NBTTagCompound nbTag = StackInfo.itemStackToNBT(BGrid.getItem(slotIndex), true);
nbTag.setInteger("Count", Math.max(nbTag.getInteger("Count") + iMeta.factor * shift, iMeta.factor));
BGrid.replaceItem(slotIndex, StackInfo.loadFromNBT(nbTag));
}
}
}
NBTTagCompound nbTag = StackInfo.itemStackToNBT(slot.item, true);
nbTag.setInteger("Count", Math.max(nbTag.getInteger("Count") + meta.factor * shift, meta.factor));
BGrid.replaceItem(slot.slotIndex, StackInfo.loadFromNBT(nbTag));
saveBookmarks();
return true;
}
}
return super.onMouseWheel(shift, mousex, mousey);
public int getWidth(GuiContainer gui) {
return LayoutManager.getLeftSize(gui) - ( (gui.xSize + gui.width) / 2 + 3 ) - 16;
}
}
@@ -46,24 +46,18 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ClientHandler
{
private static String[] defaultSerialHandlers = {
"WayofTime.alchemicalWizardry.client.nei.NEIAlchemyRecipeHandler"
};
private static String[] defaultHeightHackHandlerRegex = {
"buildcraft.compat.nei.*",
"cofh.thermalexpansion.plugins.nei.handlers.*",
"crazypants.enderio.nei.*",
"forestry.factory.recipes.nei.*",
"ic2.neiIntegration.core.recipehandler.*",
"mariculture.plugins.nei.*",
"redgear.brewcraft.plugins.nei.*",
"tconstruct.plugins.nei.*",
"WayofTime.alchemicalWizardry.client.nei.*",
private static String[] defaultHeightHackHandlers = {
"ic2.neiIntegration.core.recipehandler.FluidCannerRecipeHandler",
"tconstruct.plugins.nei.RecipeHandlerAlloying",
"tconstruct.plugins.nei.RecipeHandlerCastingBasin",
"tconstruct.plugins.nei.RecipeHandlerCastingTable",
"tconstruct.plugins.nei.RecipeHandlerMelting",
};
private static String[] defaultHandlerOrdering = {
"# Each line in this file should either be a comment (starts with '#') or an ordering.",
@@ -186,7 +180,7 @@ public class ClientHandler
if (!file.exists()) {
try (FileWriter writer = new FileWriter(file)) {
NEIClientConfig.logger.info("Creating default height hack handlers list {}", file);
Collection<String> toSave = Arrays.asList(defaultHeightHackHandlerRegex);
Collection<String> toSave = Loader.isModLoaded("dreamcraft") ? Collections.singletonList("") : Arrays.asList(defaultHeightHackHandlers);
IOUtils.writeLines(toSave, "\n", writer);
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to save default height hack handlers list to file {}", file, e);
@@ -195,10 +189,7 @@ public class ClientHandler
try (FileReader reader = new FileReader(file)) {
NEIClientConfig.logger.info("Loading height hack handlers from file {}", file);
NEIClientConfig.heightHackHandlerRegex =
IOUtils.readLines(reader).stream()
.map(Pattern::compile)
.collect(Collectors.toCollection(HashSet::new));
NEIClientConfig.heightHackHandlers = new HashSet<>(IOUtils.readLines(reader));
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to load height hack handlers from file {}", file, e);
}
+257 -288
View File
@@ -1,117 +1,85 @@
package codechicken.nei;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
import codechicken.nei.recipe.StackInfo;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import java.util.ArrayList;
public class ItemPanel extends Widget
{
public ItemStack draggedStack;
public int mouseDownSlot = -1;
public Button pagePrev;
public Button pageNext;
public Label pageLabel;
import static codechicken.lib.gui.GuiDraw.drawRect;
import static codechicken.nei.NEIClientConfig.canPerformAction;
public class ItemPanel extends Widget {
/**
* Backwards compat :-/
*/
@Deprecated
private int itemsPerPage = 0;
@Deprecated
public static ArrayList<ItemStack> items = new ArrayList<>();
@Deprecated
/**
* Should not be externally modified, use updateItemList
*/
public ArrayList<ItemStack> realItems = new ArrayList<>();
/**
* Swapped into visible items on update
*/
protected ArrayList<ItemStack> _items = realItems;
public static class ItemPanelSlot
public ArrayList<ItemStack> getItems() {
return realItems;
}
public static void updateItemList(ArrayList<ItemStack> newItems) {
ItemPanels.itemPanel._items = newItems;
}
public class ItemPanelSlot
{
public ItemStack item;
public int slotIndex;
public ItemPanelSlot(int idx, ItemStack stack)
{
slotIndex = idx;
item = stack;
public ItemPanelSlot(int index) {
item = realItems.get(index);
slotIndex = index;
}
@Deprecated
public ItemPanelSlot(int idx)
{
this(idx, ItemPanels.itemPanel.getGrid().getItem(idx));
}
}
protected static class ItemPanelGrid extends ItemsGrid
{
public ArrayList<ItemStack> newItems;
public ItemStack draggedStack;
public int mouseDownSlot = -1;
public void setItems(ArrayList<ItemStack> items)
{
newItems = items;
needRefresh = true;
}
public Button prev;
public Button next;
public Label pageLabel;
public void refresh(GuiContainer gui)
{
if (newItems != null) {
realItems = newItems;
newItems = null;
}
private int marginLeft;
private int marginTop;
private int rows;
private int columns;
super.refresh(gui);
}
private boolean[] validSlotMap;
private int firstIndex;
private int itemsPerPage;
}
private int page;
private int numPages;
protected ItemsGrid grid = new ItemPanelGrid();
public ArrayList<ItemStack> getItems()
{
return grid.getItems();
}
public static void updateItemList(ArrayList<ItemStack> newItems)
{
((ItemPanelGrid) ItemPanels.itemPanel.getGrid()).setItems(newItems);
ItemPanels.itemPanel.realItems = newItems;
}
@Deprecated
public void scroll(int i)
{
grid.shiftPage(i);
}
public ItemsGrid getGrid()
{
return grid;
}
public void init() {
pageLabel = new Label("(0/0)", true);
pagePrev = new Button("Prev")
prev = new Button("Prev")
{
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
grid.shiftPage(-1);
scroll(-1);
return true;
}
return false;
@@ -122,11 +90,11 @@ public class ItemPanel extends Widget
return "<";
}
};
pageNext = new Button("Next")
next = new Button("Next")
{
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
grid.shiftPage(1);
scroll(1);
return true;
}
return false;
@@ -137,89 +105,169 @@ public class ItemPanel extends Widget
return ">";
}
};
}
public int getMarginLeft(GuiContainer gui)
{
if (gui instanceof GuiContainerCreative && NEIClientUtils.getGamemode() == 2) {
//then activate creative+ first render creative gui and oly then creative+
return (gui.width + 176) / 2 + 2;
}
return (gui.width + gui.xSize) / 2 + 2;
public int getX(GuiContainer gui) {
return (gui.xSize + gui.width) / 2 + 3;
}
public int getMarginTop(GuiContainer gui)
{
public int getMarginLeft() {
return x + (w % 18) / 2;
}
public int getMarginTop() {
return y + (h % 18) / 2;
}
public int getButtonTop() {
return 2;
}
public int getWidth(GuiContainer gui)
{
return LayoutManager.getSideWidth(gui) - getMarginLeft(gui);
public int getNextX(GuiContainer gui) {
return gui.width - prev.w - 2;
}
public int getHeight(GuiContainer gui)
{
// - 19 = 2 + 16 + 1 -> input in bottom
return gui.height - getMarginTop(gui) - 19;
public int getPrevX(GuiContainer gui) {
return (gui.xSize + gui.width) / 2 + 2;
}
public String getLabelText()
{
return "(" + getPage() + "/" + Math.max(1, getNumPages()) + ")";
public int getPageX(GuiContainer gui) {
return gui.guiLeft * 3 / 2 + gui.xSize + 1;
}
public void resize(GuiContainer gui)
{
final int marginLeft = getMarginLeft(gui);
final int marginTop = getMarginTop(gui);
final int width = getWidth(gui);
final int height = getHeight(gui);
public int getHeight(GuiContainer gui) {
return gui.height - 15 - y;
}
public int getWidth(GuiContainer gui) {
return LayoutManager.getSideWidth(gui) - x;
}
public String getLabelText() {
return pageLabel.text = "(" + getPage() + "/" + getNumPages() + ")";
}
protected void setItems() {
realItems = _items;
// Backwards compat
ItemPanels.itemPanel._items = _items;
}
public void resize(GuiContainer gui) {
setItems();
final int buttonHeight = 16;
final int buttonWidth = 16;
pagePrev.w = pageNext.w = buttonWidth;
pagePrev.h = pageNext.h = buttonHeight;
pagePrev.y = pageNext.y = marginTop;
prev.x = getPrevX(gui);
prev.y = getButtonTop();
prev.h = buttonHeight;
prev.w = buttonWidth;
pagePrev.x = marginLeft;
pageNext.x = marginLeft + width - buttonWidth;
next.x = getNextX(gui);
next.y = getButtonTop();
next.h = buttonHeight;
next.w = buttonWidth;
pageLabel.x = marginLeft + width / 2;
pageLabel.y = marginTop + 5;
pageLabel.x = getPageX(gui);
pageLabel.y = prev.y + 5;
pageLabel.text = getLabelText();
y = prev.h + prev.y;
x = getX(gui);
w = getWidth(gui);
h = getHeight(gui);
y = marginTop + buttonHeight + 2;
x = marginLeft;
w = width;
h = height - buttonHeight - 2;
grid.setGridSize(x, y, w, h);
grid.refresh(gui);
marginLeft = getMarginLeft();
marginTop = getMarginTop();
columns = w / 18;
rows = h / 18;
//sometimes width and height can be negative with certain resizing
if(rows < 0) rows = 0;
if(columns < 0) columns = 0;
calculatePage();
updateValidSlots();
}
public void setVisible()
{
LayoutManager.addWidget(pagePrev);
LayoutManager.addWidget(pageNext);
private void calculatePage() {
if (itemsPerPage == 0)
numPages = 0;
else
numPages = (int) Math.ceil((float) realItems.size() / (float) itemsPerPage);
if (firstIndex >= realItems.size())
firstIndex = 0;
if (numPages == 0)
page = 0;
else
page = firstIndex / itemsPerPage + 1;
}
public void setVisible() {
LayoutManager.addWidget(prev);
LayoutManager.addWidget(next);
LayoutManager.addWidget(pageLabel);
}
private void updateValidSlots() {
GuiContainer gui = NEIClientUtils.getGuiContainer();
validSlotMap = new boolean[rows * columns];
itemsPerPage = 0;
for (int i = 0; i < validSlotMap.length; i++)
if (slotValid(gui, i)) {
validSlotMap[i] = true;
itemsPerPage++;
}
}
private boolean slotValid(GuiContainer gui, int i) {
Rectangle4i rect = getSlotRect(i);
try {
GuiInfo.readLock.lock();
if(GuiInfo.guiHandlers.stream().anyMatch(handler -> handler.hideItemPanelSlot(gui, rect.x, rect.y, rect.w, rect.h)))
return false;
} finally {
GuiInfo.readLock.unlock();
}
return true;
}
public Rectangle4i getSlotRect(int i) {
return getSlotRect(i / columns, i % columns);
}
public Rectangle4i getSlotRect(int row, int column) {
return new Rectangle4i(marginLeft + column * 18, marginTop + row * 18, 18, 18);
}
@Override
public void draw(int mousex, int mousey)
{
grid.draw(mousex, mousey);
public void draw(int mousex, int mousey) {
if (itemsPerPage == 0)
return;
GuiContainerManager.enableMatrixStackLogging();
int index = firstIndex;
for (int i = 0; i < rows * columns && index < realItems.size(); i++) {
if (validSlotMap[i]) {
Rectangle4i rect = getSlotRect(i);
if (rect.contains(mousex, mousey))
drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555);//highlight
GuiContainerManager.drawItem(rect.x + 1, rect.y + 1, realItems.get(index));
index++;
}
}
GuiContainerManager.disableMatrixStackLogging();
}
@Override
public void postDraw(int mousex, int mousey) {
if (draggedStack != null) {
GuiContainerManager.drawItems.zLevel += 100;
GuiContainerManager.drawItem(mousex - 8, mousey - 8, draggedStack, true);
GuiContainerManager.drawItem(mousex - 8, mousey - 8, draggedStack);
GuiContainerManager.drawItems.zLevel -= 100;
}
}
@@ -229,42 +277,29 @@ public class ItemPanel extends Widget
if (mouseDownSlot >= 0 && draggedStack == null && NEIClientUtils.getHeldItem() == null &&
NEIClientConfig.hasSMPCounterPart() && !GuiInfo.hasCustomSlots(NEIClientUtils.getGuiContainer())) {
ItemPanelSlot mouseOverSlot = getSlotMouseOver(mousex, mousey);
ItemStack stack = new ItemPanelSlot(mouseDownSlot).item;
if (stack != null && (mouseOverSlot == null || mouseOverSlot.slotIndex != mouseDownSlot || heldTime > 500)) {
int amount = NEIClientConfig.getItemQuantity();
if (amount == 0)
amount = stack.getMaxStackSize();
if (mouseOverSlot == null || mouseOverSlot.slotIndex != mouseDownSlot || heldTime > 500) {
draggedStack = getDraggedStackWithQuantity(mouseDownSlot);
draggedStack = NEIServerUtils.copyStack(stack, amount);
}
}
}
protected ItemStack getDraggedStackWithQuantity(int mouseDownSlot)
{
ItemStack stack = grid.getItem(mouseDownSlot);
if (stack != null) {
int amount = NEIClientConfig.getItemQuantity();
if (amount == 0) {
amount = stack.getMaxStackSize();
}
return NEIServerUtils.copyStack(stack, amount);
}
return null;
}
@Override
public boolean handleClick(int mousex, int mousey, int button)
{
if (handleClickExt(mousex, mousey, button))
public boolean handleClick(int mousex, int mousey, int button) {
if (handleDraggedClick(mousex, mousey, button))
return true;
if (NEIClientUtils.getHeldItem() != null) {
if (!grid.contains(mousex, mousey)) {
return false;
try {
GuiInfo.readLock.lock();
if (GuiInfo.guiHandlers.stream().anyMatch(handler -> handler.hideItemPanelSlot(NEIClientUtils.getGuiContainer(), mousex, mousey, 1, 1)))
return false;
} finally {
GuiInfo.readLock.unlock();
}
if (NEIClientConfig.canPerformAction("delete") && NEIClientConfig.canPerformAction("item"))
@@ -280,177 +315,84 @@ public class ItemPanel extends Widget
ItemPanelSlot hoverSlot = getSlotMouseOver(mousex, mousey);
if (hoverSlot != null) {
if (button == 2) {
ItemStack stack = hoverSlot.item;
if (stack != null) {
int amount = NEIClientConfig.getItemQuantity();
if (amount == 0)
amount = stack.getMaxStackSize();
if (hoverSlot.item != null) {
draggedStack = getDraggedStackWithQuantity(hoverSlot.slotIndex);
draggedStack = NEIServerUtils.copyStack(stack, amount);
}
} else {
mouseDownSlot = hoverSlot.slotIndex;
}
return true;
}
return false;
}
@Override
public boolean handleClickExt(int mouseX, int mouseY, int button)
{
if (ItemPanels.itemPanel.draggedStack != null) {
return ItemPanels.itemPanel.handleDraggedClick(mouseX, mouseY, button);
}
if (ItemPanels.bookmarkPanel.draggedStack != null) {
return ItemPanels.bookmarkPanel.handleDraggedClick(mouseX, mouseY, button);
}
return false;
}
protected boolean handleDraggedClick(int mouseX, int mouseY, int button)
{
if (draggedStack == null) {
private boolean handleDraggedClick(int mousex, int mousey, int button) {
if (draggedStack == null)
return false;
}
if (handleFillFluidContainerClick(mouseX, mouseY, button)) {
return true;
}
if (handleGUIContainerClick(mouseX, mouseY, button)) {
return true;
}
if (handleCheatItemClick(mouseX, mouseY, button)) {
return true;
}
final GuiContainer gui = NEIClientUtils.getGuiContainer();
if (mouseX < gui.guiLeft || mouseY < gui.guiTop || mouseX >= gui.guiLeft + gui.xSize || mouseY >= gui.guiTop + gui.ySize) {
draggedStack = null;
}
return true;
}
protected boolean handleFillFluidContainerClick(int mouseX, int mouseY, int button)
{
if (button == 2) {
return false;
}
ItemPanelSlot mouseOverSlot = ItemPanels.itemPanel.getSlotMouseOver(mouseX, mouseY);
if (mouseOverSlot == null) {
mouseOverSlot = ItemPanels.bookmarkPanel.getSlotMouseOver(mouseX, mouseY);
}
if (mouseOverSlot != null && draggedStack.getItem() instanceof IFluidContainerItem) {
FluidStack fluidStack = StackInfo.getFluid(mouseOverSlot.item);
if (fluidStack != null) {
final int stackSize = draggedStack.stackSize;
fluidStack = fluidStack.copy();
if (fluidStack.amount == 0) {
fluidStack.amount = 1000;
}
if (mouseOverSlot.item.stackSize > 1) {
fluidStack.amount *= mouseOverSlot.item.stackSize;
}
draggedStack.stackSize = 1;
((IFluidContainerItem) draggedStack.getItem()).fill(draggedStack, fluidStack, true);
draggedStack.stackSize = stackSize;
if (button == 1 && ((IFluidContainerItem) draggedStack.getItem()).getFluid(draggedStack) != null) {
ItemPanels.bookmarkPanel.addOrRemoveItem(draggedStack.copy());
}
}
return true;
}
return false;
}
protected boolean handleGUIContainerClick(int mouseX, int mouseY, int button)
{
final GuiContainer gui = NEIClientUtils.getGuiContainer();
GuiContainer gui = NEIClientUtils.getGuiContainer();
boolean handled = false;
try {
GuiInfo.readLock.lock();
for (INEIGuiHandler handler : GuiInfo.guiHandlers) {
if (handler.handleDragNDrop(gui, mouseX, mouseY, draggedStack, button)) {
if (handler.handleDragNDrop(gui, mousex, mousey, draggedStack, button)) {
handled = true;
break;
if (draggedStack.stackSize == 0) {
draggedStack = null;
return true;
}
}
}
} finally {
GuiInfo.readLock.unlock();
}
if (handled)
return true;
if (draggedStack.stackSize == 0) {
draggedStack = null;
}
return handled;
}
protected boolean handleCheatItemClick(int mouseX, int mouseY, int button)
{
final GuiContainer gui = NEIClientUtils.getGuiContainer();
final Slot overSlot = gui.getSlotAtPosition(mouseX, mouseY);
Slot overSlot = gui.getSlotAtPosition(mousex, mousey);
if (overSlot != null && overSlot.isItemValid(draggedStack)) {
if (NEIClientConfig.canCheatItem(draggedStack)) {
int contents = overSlot.getHasStack() ? overSlot.getStack().stackSize : 0;
final int add = button == 0 ? draggedStack.stackSize : 1;
if (overSlot.getHasStack() && !NEIServerUtils.areStacksSameType(draggedStack, overSlot.getStack())) {
int add = button == 0 ? draggedStack.stackSize : 1;
if (overSlot.getHasStack() && !NEIServerUtils.areStacksSameType(draggedStack, overSlot.getStack()))
contents = 0;
}
final int total = Math.min(contents + add, Math.min(overSlot.getSlotStackLimit(), draggedStack.getMaxStackSize()));
int total = Math.min(contents + add, Math.min(overSlot.getSlotStackLimit(), draggedStack.getMaxStackSize()));
if (total > contents) {
NEIClientUtils.setSlotContents(overSlot.slotNumber, NEIServerUtils.copyStack(draggedStack, total), true);
NEICPH.sendGiveItem(NEIServerUtils.copyStack(draggedStack, total), false, false);
draggedStack.stackSize -= total - contents;
}
if (draggedStack.stackSize == 0) {
if (draggedStack.stackSize == 0)
draggedStack = null;
}
} else {
draggedStack = null;
}
return true;
} else if (mousex < gui.guiLeft || mousey < gui.guiTop || mousex >= gui.guiLeft + gui.xSize || mousey >= gui.guiTop + gui.ySize) {
draggedStack = null;
}
return false;
return true;
}
@Override
public boolean handleClickExt(int mousex, int mousey, int button) {
return handleDraggedClick(mousex, mousey, button);
}
@Override
public void mouseUp(int mousex, int mousey, int button) {
ItemPanelSlot hoverSlot = getSlotMouseOver(mousex, mousey);
if (hoverSlot != null && hoverSlot.slotIndex == mouseDownSlot && draggedStack == null) {
ItemStack item = hoverSlot.item;
if (NEIController.manager.window instanceof GuiRecipe || !NEIClientConfig.canCheatItem(item)) {
if (button == 0)
GuiCraftingRecipe.openRecipeGui("item", item);
else if (button == 1)
@@ -461,7 +403,7 @@ public class ItemPanel extends Widget
return;
}
NEIClientUtils.cheatItem(getDraggedStackWithQuantity(hoverSlot.slotIndex), button, -1);
NEIClientUtils.cheatItem(item, button, -1);
}
mouseDownSlot = -1;
@@ -472,23 +414,20 @@ public class ItemPanel extends Widget
if (!contains(mousex, mousey))
return false;
grid.shiftPage(-i);
scroll(-i);
return true;
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
if (keyID == NEIClientConfig.getKeyBinding("gui.next")) {
grid.shiftPage(1);
scroll(1);
return true;
}
if (keyID == NEIClientConfig.getKeyBinding("gui.prev")) {
grid.shiftPage(-1);
scroll(-1);
return true;
}
return false;
}
@@ -498,23 +437,53 @@ public class ItemPanel extends Widget
return slot == null ? null : slot.item;
}
public ItemPanelSlot getSlotMouseOver(int mousex, int mousey)
{
return grid.getSlotMouseOver(mousex, mousey);
public ItemPanelSlot getSlotMouseOver(int mousex, int mousey) {
int index = firstIndex;
for (int i = 0; i < rows * columns && index < realItems.size(); i++)
if (validSlotMap[i]) {
if (getSlotRect(i).contains(mousex, mousey))
return new ItemPanelSlot(index);
index++;
}
return null;
}
public void scroll(int i) {
if (itemsPerPage != 0) {
int oldIndex = firstIndex;
firstIndex += i * itemsPerPage;
if (firstIndex >= realItems.size())
firstIndex = 0;
if (firstIndex < 0)
if (oldIndex > 0)
firstIndex = 0;
else
firstIndex = (realItems.size() - 1) / itemsPerPage * itemsPerPage;
calculatePage();
}
}
public int getPage() {
return grid.page + 1;
return page;
}
public int getNumPages() {
return grid.numPages;
return numPages;
}
@Override
public boolean contains(int px, int py)
{
return grid.contains(px, py);
public boolean contains(int px, int py) {
GuiContainer gui = NEIClientUtils.getGuiContainer();
Rectangle4i rect = new Rectangle4i(px, py, 1, 1);
try {
GuiInfo.readLock.lock();
if(GuiInfo.guiHandlers.stream().anyMatch(handler -> handler.hideItemPanelSlot(gui, rect.x, rect.y, rect.w, rect.h)))
return false;
} finally {
GuiInfo.readLock.unlock();
}
return super.contains(px, py);
}
}
@@ -1,315 +0,0 @@
package codechicken.nei;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.ItemPanel.ItemPanelSlot;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import static codechicken.lib.gui.GuiDraw.drawRect;
public class ItemsGrid
{
protected static final int SLOT_SIZE = 18;
protected int width;
protected int height;
protected int marginLeft;
protected int marginTop;
protected ArrayList<ItemStack> realItems = new ArrayList<>();
protected int page;
protected int perPage;
protected int firstIndex;
protected int numPages;
protected int rows;
protected int columns;
protected boolean[] validSlotMap;
protected boolean[] invalidSlotMap;
private int[] guiSize;
protected boolean needRefresh = false;
public ArrayList<ItemStack> getItems()
{
return realItems;
}
public ItemStack getItem(int idx)
{
return realItems.get(idx);
}
public int size()
{
return realItems.size();
}
public int indexOf(ItemStack stackA, boolean useNBT)
{
for (int idx = 0; idx < realItems.size(); idx++) {
if (StackInfo.equalItemAndNBT(stackA, realItems.get(idx), useNBT)) {
return idx;
}
}
return -1;
}
public int getPage()
{
return page + 1;
}
public int getPerPage()
{
return perPage;
}
public int getNumPages()
{
return numPages;
}
public int getRows()
{
return rows;
}
public int getColumns()
{
return columns;
}
public void setGridSize(int mleft, int mtop, int w, int h)
{
//I don't like this big condition
if (marginLeft != mleft || marginTop != mtop || width != w || height != h) {
marginLeft = mleft;
marginTop = mtop;
width = Math.max(0, w);
height = Math.max(0, h);
columns = width / SLOT_SIZE;
rows = height / SLOT_SIZE;
needRefresh = true;
}
}
public void shiftPage(int shift)
{
if (perPage == 0) {
numPages = 0;
page = 0;
return;
}
numPages = (int) Math.ceil((float) realItems.size() / (float) perPage);
page += shift;
if (page >= numPages) {
page = page - numPages;
}
if (page < 0) {
page = numPages + page;
}
page = Math.max(0, Math.min(page, numPages - 1));
needRefresh = true;
}
public void refresh(GuiContainer gui)
{
if (!needRefresh(gui)) {
return;
}
updateGuiOverlapSlots(gui);
shiftPage(0);
needRefresh = false;
}
private boolean needRefresh(GuiContainer gui)
{
if (needRefresh == true) {
return true;
}
if (gui == null && guiSize == null) {
return false;
}
if (gui == null) {
guiSize = null;
return true;
}
if (guiSize == null) {
guiSize = new int[]{ gui.guiLeft, gui.guiTop, gui.width, gui.height };
return true;
}
if (gui.guiLeft != guiSize[0] || gui.guiTop != guiSize[1] || gui.width != guiSize[2] || gui.height != guiSize[3]) {
guiSize = new int[]{ gui.guiLeft, gui.guiTop, gui.width, gui.height };
return true;
}
return false;
}
private void updateGuiOverlapSlots(GuiContainer gui)
{
invalidSlotMap = new boolean[rows * columns];
perPage = columns * rows;
checkGuiOverlap(gui, 0, columns - 2, 1);
checkGuiOverlap(gui, columns - 1, 1, -1);
}
private void checkGuiOverlap(GuiContainer gui, int start, int end, int dir)
{
boolean validColumn = false;
for (int c = start; c != end && !validColumn; c += dir) {
validColumn = true;
for (int r = 0; r < rows; r++) {
if (!slotValid(gui, r, c) && !invalidSlotMap[columns * r + c]) {
invalidSlotMap[columns * r + c] = true;
validColumn = false;
perPage--;
}
}
}
}
private boolean slotValid(GuiContainer gui, int row, int column)
{
Rectangle4i rect = getSlotRect(row, column);
try {
GuiInfo.readLock.lock();
if (GuiInfo.guiHandlers.stream().anyMatch(handler -> handler.hideItemPanelSlot(gui, rect.x, rect.y, rect.w, rect.h))) {
return false;
}
} finally {
GuiInfo.readLock.unlock();
}
return true;
}
public Rectangle4i getSlotRect(int i)
{
return getSlotRect(i / columns, i % columns);
}
public Rectangle4i getSlotRect(int row, int column)
{
return new Rectangle4i(marginLeft + (width % SLOT_SIZE) / 2 + column * SLOT_SIZE, marginTop + row * SLOT_SIZE, SLOT_SIZE, SLOT_SIZE);
}
public boolean isInvalidSlot(int idx)
{
return invalidSlotMap[idx] == true;
}
public void draw(int mousex, int mousey)
{
if (getPerPage() == 0) {
return;
}
ItemPanelSlot slot = getSlotMouseOver(mousex, mousey);
GuiContainerManager.enableMatrixStackLogging();
int idx = page * perPage;
for (int i = 0; i < rows * columns && idx < size(); i++) {
if (!invalidSlotMap[i]) {
drawItem(getSlotRect(i), idx, slot);
idx ++;
}
}
GuiContainerManager.disableMatrixStackLogging();
}
protected void drawItem(Rectangle4i rect, int idx, ItemPanelSlot focus)
{
if (focus != null && focus.slotIndex == idx) {
drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555);//highlight
}
GuiContainerManager.drawItem(rect.x + 1, rect.y + 1, getItem(idx));
}
public ItemPanelSlot getSlotMouseOver(int mousex, int mousey)
{
if (!contains(mousex, mousey)) {
return null;
}
final int overRow = (int) ((mousey - marginTop) / SLOT_SIZE);
final int overColumn = (int) ((mousex - marginLeft - (width % SLOT_SIZE) / 2) / SLOT_SIZE);
final int slt = columns * overRow + overColumn;
int idx = page * perPage + slt;
if (overRow >= rows || overColumn >= columns) {
return null;
}
for (int i = 0; i < slt; i++) {
if (invalidSlotMap[i]) {
idx--;
}
}
return idx < size()? new ItemPanelSlot(idx, realItems.get(idx)): null;
}
public boolean contains(int px, int py)
{
if (!(new Rectangle4i(marginLeft, marginTop, width, height)).contains(px, py)) {
return false;
}
final int r = (int) ((py - marginTop) / SLOT_SIZE);
final int c = (int) ((px - marginLeft - (width % SLOT_SIZE) / 2) / SLOT_SIZE);
final int slt = columns * r + c;
return r >= rows || c >= columns || !invalidSlotMap[slt];
}
}
@@ -265,7 +265,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
}
@Override
public void postRenderObjects(GuiContainer gui, int mousex, int mousey) {
if (!isHidden() && isEnabled()) {
@@ -310,13 +310,13 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
VisiblityData visiblity = new VisiblityData();
if (isHidden())
visiblity.showNEI = false;
if (isBookmarkPanelHidden())
visiblity.showBookmarkPanel = false;
if (gui.height - gui.ySize <= 40)
visiblity.showSearchSection = false;
if (gui.guiLeft - 4 < 76)
visiblity.showWidgets = false;
try {
@@ -325,7 +325,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
} finally {
GuiInfo.readLock.unlock();
}
visiblity.translateDependancies();
getLayoutStyle().layout(gui, visiblity);
@@ -351,7 +351,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
this.icons[1] = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 48, 0, 16, 16).build();
this.icons[2] = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 64, 0, 16, 16).build();
}
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
@@ -367,7 +367,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
return false;
}
@Override
public void addTooltips(List<String> tooltip) {
tooltip.add(translate("inventory.options.tip"));
@@ -380,9 +380,9 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
String controlKeyLocalization = translate(Minecraft.isRunningOnMac ? "key.ctrl.mac" : "key.ctrl");
tooltip.add(modeColor + translate("inventory.options.tip.cheatmode." + cheatMode));
tooltip.add(modeColor + translate("inventory.options.tip.cheatmode.disable", controlKeyLocalization));
}
@Override
public String getRenderLabel() {
return translate("inventory.options");
@@ -396,7 +396,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
this.icons[0] = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 0, 0, 16, 16).build();
this.icons[1] = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 16, 0, 16, 16).build();
}
@Override
public boolean onButtonPress(boolean rightclick) {
NEIClientConfig.toggleBooleanSetting("inventory.bookmarksEnabled");
@@ -619,7 +619,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
return true;
}
public static void markItemsDirty() {
// If anything has modified data this depends on, we'll need to reload the item list
itemsLoaded = false;
@@ -683,7 +683,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (visiblity.showBookmarkPanel) {
addWidget(bookmarkPanel);
bookmarkPanel.setVisible();
}
}
if (visiblity.showSearchSection) {
addWidget(searchField);
@@ -707,7 +707,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (canPerformAction("delete"))
addWidget(delete);
}
if (!visiblity.showBookmarkPanel) {
// Bookmarks or Subset/dropdown
addWidget(dropDown);
@@ -761,7 +761,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public boolean shouldShowTooltip(GuiContainer gui) {
return itemPanel.draggedStack == null && bookmarkPanel.sortedStackIndex == -1;
return itemPanel.draggedStack == null;
}
/** Note: this method isn't actually used by this mod, but NEI add-ons might need it. */
@@ -799,16 +799,16 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
public static void drawIcon(int x, int y, Image image) {
final boolean isDrawableResource = image instanceof DrawableResource;
if (!isDrawableResource)
changeTexture("nei:textures/nei_sprites.png");
GL11.glColor4f(1, 1, 1, 1);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(!isDrawableResource)
drawTexturedModalRect(x, y, image.x, image.y, image.width, image.height);
else
else
((DrawableResource)image).draw(x, y);
GL11.glDisable(GL11.GL_BLEND);
}
@@ -884,3 +884,4 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
}
@@ -119,7 +119,7 @@ public class LayoutStyleMinecraft extends LayoutStyle
bookmarkPanel.resize(gui);
more.w = more.h = less.w = less.h = 16;
less.x = itemPanel.pagePrev.x;
less.x = itemPanel.prev.x;
more.x = gui.width - less.w - 2;
more.y = less.y = gui.height - more.h - 2;
@@ -48,7 +48,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;
public class NEIClientConfig {
private static boolean configLoaded;
@@ -69,9 +68,8 @@ public class NEIClientConfig {
// Set of handlers that need to be run in serial
public static HashSet<String> serialHandlers = new HashSet<>();
// Set of regexes matching handler ID of handlers that need the hack in GuiRecipe.startHeightHack().
// We use regex here so that we can apply the height hack to entire mods with one entry.
public static HashSet<Pattern> heightHackHandlerRegex = new HashSet<>();
// Set of handler ID of handlers that need the hack in GuiRecipe.startHeightHack().
public static HashSet<String> heightHackHandlers = new HashSet<>();
// Map of handler ID to sort order.
// Handlers will be sorted in ascending order, so smaller numbers show up earlier.
@@ -119,7 +117,7 @@ public class NEIClientConfig {
tag.getTag("inventory.widgetsenabled").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.widgetsenabled"));
tag.getTag("inventory.hidden").getBooleanValue(false);
tag.getTag("inventory.cheatmode").getIntValue(2);
tag.getTag("inventory.lockmode").setComment("For those who can't help themselves.\nSet this to a mode and you will be unable to change it ingame").getIntValue(-1);
@@ -176,20 +174,14 @@ public class NEIClientConfig {
API.addOption(new OptionTextField("command.rain"));
tag.getTag("command.heal").setDefaultValue("");
API.addOption(new OptionTextField("command.heal"));
tag.getTag("inventory.bookmarksEnabled").setComment("Enable/disable bookmarks").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.bookmarksEnabled", true));
tag.getTag("inventory.saveCurrentRecipeInBookmarksEnabled").setComment("Save Current Recipe in Bookmarks").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.saveCurrentRecipeInBookmarksEnabled", true));
tag.getTag("inventory.useNBTInBookmarks").setComment("Use NBT in Bookmarks").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.useNBTInBookmarks", true));
tag.getTag("inventory.jei_style_tabs").setComment("Enable/disable JEI Style Tabs").getBooleanValue(true);
API.addOption(new OptionToggleButtonBoubs("inventory.jei_style_tabs", true));
tag.getTag("inventory.jei_style_item_presence_overlay").setComment("Enable/disable JEI Style item presence overlay on ?-hover").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.jei_style_item_presence_overlay", true));
tag.getTag("inventory.creative_tab_style").setComment("Creative or JEI style tabs").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.creative_tab_style", true));
@@ -316,6 +308,7 @@ public class NEIClientConfig {
GuiInfo.load();
RecipeInfo.load();
LayoutManager.load();
ItemPanels.bookmarkPanel.loadBookmarks();
NEIController.load();
configLoaded = true;
@@ -364,12 +357,6 @@ public class NEIClientConfig {
public static boolean isBookmarkPanelHidden() {
return !getBooleanSetting("inventory.bookmarksEnabled");
}
public static boolean saveCurrentRecipeInBookmarksEnabled() {
return getBooleanSetting("inventory.saveCurrentRecipeInBookmarksEnabled");
}
public static boolean useNBTInBookmarks() {
return getBooleanSetting("inventory.useNBTInBookmarks");
}
public static boolean areJEIStyleTabsVisible() {
return getBooleanSetting("inventory.jei_style_tabs");
}
@@ -383,7 +370,7 @@ public class NEIClientConfig {
return enabledOverride && getBooleanSetting("inventory.widgetsenabled");
}
public static boolean loadHandlersFromJar() {
return !getBooleanSetting("tools.handler_load_from_config");
return !getBooleanSetting("tools.handler_load_from_config");
}
public static void setEnabled(boolean flag) {
@@ -454,7 +441,7 @@ public class NEIClientConfig {
public static boolean shouldInvertMouseScrollTransfer() {
return !getBooleanSetting("inventory.invertMouseScrollTransfer");
}
public static boolean getMagnetMode() {
return enabledActions.contains("magnet");
}
@@ -541,5 +528,5 @@ public class NEIClientConfig {
if (file.isDirectory() && !saveFileNames.contains(file.getName()))
ObfuscationRun.deleteDir(file, true);
}
}
@@ -5,6 +5,7 @@ import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.util.LangProxy;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IInfiniteItemHandler;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.ItemInfo;
import com.google.common.collect.Iterables;
import net.minecraft.client.Minecraft;
@@ -135,7 +136,10 @@ public class NEIClientUtils extends NEIServerUtils
if (mode == 1 && stack.stackSize < stack.getMaxStackSize()) {
giveStack(stack, stack.getMaxStackSize() - stack.stackSize);
} else {
giveStack(stack);
int amount = getItemQuantity();
if (amount == 0)
amount = stack.getMaxStackSize();
giveStack(stack, amount);
}
}
}
@@ -63,9 +63,8 @@ public class SearchField extends TextField implements ItemFilterProvider
}
@Override
public int getTextColour()
{
if (ItemPanels.itemPanel.getItems().isEmpty()) {
public int getTextColour() {
if(ItemPanels.itemPanel.realItems.size() == 0) {
return focused() ? 0xFFcc3300 : 0xFF993300;
} else {
return focused() ? 0xFFE0E0E0 : 0xFF909090;
@@ -20,7 +20,6 @@ import codechicken.nei.recipe.GuiUsageRecipe;
import codechicken.nei.recipe.ICraftingHandler;
import codechicken.nei.recipe.IUsageHandler;
import codechicken.nei.recipe.RecipeInfo;
import codechicken.nei.recipe.StackInfo;
import net.minecraft.block.Block;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
@@ -285,10 +284,4 @@ public class API
ItemInfo.itemVariants.put(item, variant);
LayoutManager.markItemsDirty();
}
public static void registerStackStringifyHandler(IStackStringifyHandler handler)
{
StackInfo.stackStringifyHandlers.add(handler);
}
}
@@ -1,16 +0,0 @@
package codechicken.nei.api;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import net.minecraft.item.ItemStack;
public interface IStackStringifyHandler
{
public NBTTagCompound convertItemStackToNBT(ItemStack stack, boolean saveStackSize);
public ItemStack convertNBTToItemStack(NBTTagCompound nbtTag);
public FluidStack getFluid(ItemStack stack);
}
@@ -22,7 +22,6 @@ import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import javax.imageio.ImageIO;
import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
@@ -101,12 +100,10 @@ public class GuiItemIconDumper extends GuiScreen
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glColor4f(1, 1, 1, 1);
final ArrayList<ItemStack> items = ItemPanels.itemPanel.getItems();
for (int i = 0; drawIndex < items.size() && i < fit; drawIndex++, i++) {
for(int i = 0; drawIndex < ItemPanels.itemPanel.realItems.size() && i < fit; drawIndex++, i++) {
int x = i%cols * 18;
int y = i/cols * 18;
GuiContainerManager.drawItem(x+1, y+1, items.get(drawIndex));
GuiContainerManager.drawItem(x+1, y+1, ItemPanels.itemPanel.realItems.get(drawIndex));
}
GL11.glFlush();
@@ -117,19 +114,14 @@ public class GuiItemIconDumper extends GuiScreen
int rows = img.getHeight() / boxSize;
int cols = img.getWidth() / boxSize;
int fit = rows*cols;
final ArrayList<ItemStack> items = ItemPanels.itemPanel.getItems();
for(int i = 0; parseIndex < items.size() && i < fit; parseIndex++, i++) {
for(int i = 0; parseIndex < ItemPanels.itemPanel.realItems.size() && i < fit; parseIndex++, i++) {
int x = i%cols * boxSize;
int y = i/cols * boxSize;
exportImage(dir, img.getSubimage(x+borderSize, y+borderSize, iconSize, iconSize), items.get(parseIndex));
exportImage(dir, img.getSubimage(x+borderSize, y+borderSize, iconSize, iconSize), ItemPanels.itemPanel.realItems.get(parseIndex));
}
if (parseIndex >= items.size()) {
if(parseIndex >= ItemPanels.itemPanel.realItems.size())
returnScreen(new ChatComponentTranslation(opt.fullName()+".icon.dumped", "dumps/itempanel_icons"));
}
}
public static String cleanFileName(String name) {
@@ -8,13 +8,17 @@ import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.TemplateRecipeHandler;
import codechicken.nei.util.NBTJson;
import com.google.common.base.Objects;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentTranslation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Pair;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
public class HandlerDumper extends DataDumper
@@ -36,7 +36,7 @@ public class ItemPanelDumper extends DataDumper
@Override
public Iterable<String[]> dump(int mode) {
LinkedList<String[]> list = new LinkedList<>();
for (ItemStack stack : ItemPanels.itemPanel.getItems())
for (ItemStack stack : ItemPanels.itemPanel.realItems)
list.add(new String[]{
Item.itemRegistry.getNameForObject(stack.getItem()),
Integer.toString(Item.getIdFromItem(stack.getItem())),
@@ -123,7 +123,7 @@ public class ItemPanelDumper extends DataDumper
public void dumpNBT(File file) throws IOException {
NBTTagList list = new NBTTagList();
for (ItemStack stack : ItemPanels.itemPanel.getItems())
for (ItemStack stack : ItemPanels.itemPanel.realItems)
list.appendTag(stack.writeToNBT(new NBTTagCompound()));
NBTTagCompound tag = new NBTTagCompound();
@@ -134,7 +134,7 @@ public class ItemPanelDumper extends DataDumper
public void dumpJson(File file) throws IOException {
PrintWriter p = new PrintWriter(file);
for (ItemStack stack : ItemPanels.itemPanel.getItems()) {
for (ItemStack stack : ItemPanels.itemPanel.realItems) {
NBTTagCompound tag = stack.writeToNBT(new NBTTagCompound());
tag.removeTag("Count");
p.println(tag);
@@ -181,28 +181,15 @@ public class GuiContainerManager
drawItem(i, j, itemstack, getFontRenderer(itemstack));
}
public static void drawItem(int i, int j, ItemStack itemstack, boolean smallAmount) {
drawItem(i, j, itemstack, getFontRenderer(itemstack), smallAmount);
}
public static void drawItem(int i, int j, ItemStack itemstack, FontRenderer fontRenderer) {
drawItem(i, j, itemstack, fontRenderer, false);
}
private static int modelviewDepth = -1;
private static final HashSet<String> stackTraces = new HashSet<>();
public static void drawItem(int i, int j, ItemStack itemstack, FontRenderer fontRenderer, boolean smallAmount) {
public static void drawItem(int i, int j, ItemStack itemstack, FontRenderer fontRenderer) {
enable3DRender();
float zLevel = drawItems.zLevel += 100F;
try {
drawItems.renderItemAndEffectIntoGUI(fontRenderer, renderEngine, itemstack, i, j);
if (!smallAmount) {
drawItems.renderItemOverlayIntoGUI(fontRenderer, renderEngine, itemstack, i, j);
} else if (itemstack.stackSize > 1) {
drawBigStackSize(i, j, itemstack.stackSize);
}
drawItems.renderItemOverlayIntoGUI(fontRenderer, renderEngine, itemstack, i, j);
if (!checkMatrixStack())
throw new IllegalStateException("Modelview matrix stack too deep");
@@ -230,27 +217,6 @@ public class GuiContainerManager
drawItems.zLevel = zLevel - 100;
}
//copy from appeng.client.render.AppEngRenderItem
protected static void drawBigStackSize(int offsetX, int offsetY, int amount)
{
final float scaleFactor = fontRenderer.getUnicodeFlag() ? 0.85f : 0.5f;
final float inverseScaleFactor = 1.0f / scaleFactor;
final String stackSize = String.valueOf( amount );
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glPushMatrix();
GL11.glScaled(scaleFactor, scaleFactor, scaleFactor);
final int X = (int) ( ( (float) offsetX + 16.0f - fontRenderer.getStringWidth( stackSize ) * scaleFactor ) * inverseScaleFactor );
final int Y = (int) ( ( (float) offsetY + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor );
fontRenderer.drawStringWithShadow(stackSize, X, Y, 16777215);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
public static void enableMatrixStackLogging() {
modelviewDepth = GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH);
}
@@ -1,169 +0,0 @@
package codechicken.nei.recipe;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonArray;
import com.google.gson.JsonPrimitive;
import codechicken.nei.util.NBTJson;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.PositionedStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class BookmarkRecipeId
{
public int position = -1;
public int recipetype = -1;
public String handlerName = null;
public List<NBTTagCompound> ingredients = new ArrayList<>();
public BookmarkRecipeId(String handlerName, List<PositionedStack> stacks)
{
this.handlerName = handlerName;
for (PositionedStack pos : stacks) {
final NBTTagCompound nbt = StackInfo.itemStackToNBT(getItemStackWithMinimumDamage(pos.items));
if (nbt != null) {
ingredients.add(nbt);
}
}
}
public BookmarkRecipeId(JsonObject json)
{
if (json.get("handlerName") != null) {
handlerName = json.get("handlerName").getAsString();
}
if (json.get("ingredients") != null) {
JsonArray arr = (JsonArray) json.get("ingredients");
List<NBTTagCompound> ingredients = convertJsonArrayToIngredients(arr);
if (ingredients != null) {
this.ingredients = ingredients;
}
}
}
public boolean equalsIngredients(List<PositionedStack> stacks)
{
if (ingredients.size() != stacks.size()) {
return false;
}
Short idx = 0;
for (PositionedStack pStack : stacks) {
final NBTTagCompound tagCompoundA = StackInfo.itemStackToNBT(getItemStackWithMinimumDamage(pStack.items));
final NBTTagCompound tagCompoundB = ingredients.get(idx);
if (tagCompoundB == null || !tagCompoundA.equals(tagCompoundB)) {
return false;
}
idx++;
}
return true;
}
public ItemStack getItemStackWithMinimumDamage(ItemStack[] stacks)
{
int damage = Short.MAX_VALUE;
ItemStack result = stacks[0];
if (stacks.length > 1) {
for (ItemStack stack : stacks) {
if (stack.getItemDamage() < damage) {
damage = stack.getItemDamage();
result = stack;
}
}
}
return result.copy();
}
public JsonObject toJsonObject()
{
JsonObject json = new JsonObject();
if (handlerName != null) {
json.add("handlerName", new JsonPrimitive(handlerName));
json.add("ingredients", convertIngredientsToJsonArray(ingredients));
}
return json;
}
protected List<NBTTagCompound> convertJsonArrayToIngredients(JsonArray arr)
{
List<NBTTagCompound> ingredients = new ArrayList<>();
for (JsonElement elem : arr) {
final NBTTagCompound nbt = (NBTTagCompound) NBTJson.toNbt(elem);
if (nbt == null) {
return null;
}
ingredients.add(nbt);
}
return ingredients;
}
protected JsonArray convertIngredientsToJsonArray(List<NBTTagCompound> ingredients)
{
JsonArray arr = new JsonArray();
for (NBTTagCompound nbTag : ingredients) {
arr.add(NBTJson.toJsonObject(nbTag));
}
return arr;
}
public boolean equals(Object anObject)
{
if (this == anObject) {
return true;
}
if (anObject instanceof BookmarkRecipeId) {
final BookmarkRecipeId anRecipeId = (BookmarkRecipeId) anObject;
if (!handlerName.equals(anRecipeId.handlerName)) {
return false;
}
if (ingredients.size() != anRecipeId.ingredients.size()) {
return false;
}
for (int idx = 0; idx < ingredients.size(); idx++) {
if (!ingredients.get(idx).equals(anRecipeId.ingredients.get(idx))) {
return false;
}
}
return true;
}
return false;
}
}
@@ -6,8 +6,6 @@ import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import codechicken.nei.ItemPanels;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
@@ -48,19 +46,9 @@ public class GuiCraftingRecipe extends GuiRecipe
handlers.sort(NEIClientConfig.HANDLER_COMPARATOR);
mc.displayGuiScreen(new GuiCraftingRecipe(prevscreen, handlers));
if (NEIClientConfig.saveCurrentRecipeInBookmarksEnabled() && !NEIClientUtils.shiftKey() && outputId.equals("item") && mc.currentScreen instanceof GuiRecipe) {
GuiCraftingRecipe.openTargetRecipe((GuiRecipe)mc.currentScreen, (ItemStack)results[0]);
}
return true;
}
protected static void openTargetRecipe(GuiRecipe currentScreen, ItemStack stackover)
{
currentScreen.openTargetRecipe(ItemPanels.bookmarkPanel.getBookmarkRecipeId(stackover));
}
private GuiCraftingRecipe(GuiScreen prevgui, ArrayList<ICraftingHandler> handlers) {
super(prevgui);
currenthandlers = handlers;
@@ -35,7 +35,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@@ -110,11 +109,7 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve
private HeightHack() {
trueHeight = height;
boolean applyHeightHack =
NEIClientConfig.heightHackHandlerRegex.stream()
.map(pattern -> pattern.matcher(handler.getHandlerId()))
.anyMatch(Matcher::matches);
if (applyHeightHack) {
if (NEIClientConfig.heightHackHandlers.contains(handler.getHandlerId())) {
// The old mods use the calculation ((height - 166) / 2) to compute the y-value of
// the top edge of the NEI window.
// guiTop is exactly that: the y-value of the top edge of the NEI window.
@@ -198,101 +193,20 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve
yShift = handlerInfo == null ? 0 : handlerInfo.getYShift();
}
public void setRecipePage(int idx) {
setRecipePage(idx, 0);
}
public void setRecipePage(int idx, int position) {
public void setRecipePage(int idx) {
recipetype = idx;
if (recipetype < 0) recipetype = currenthandlers.size() - 1;
else if (recipetype >= currenthandlers.size()) recipetype = 0;
handler = currenthandlers.get(recipetype);
handlerInfo = GuiRecipeTab.getHandlerInfo(handler);
page = Math.min(Math.max(0, position), handler.numRecipes() - 1) / getRecipesPerPage();
handlerInfo = getHandlerInfo(handler);
page = 0;
recipeTabs.calcPageNumber();
checkYShift();
initOverlayButtons();
}
public void openTargetRecipe(BookmarkRecipeId recipeId)
{
if (recipeId == null) {
return;
}
if (recipeId.recipetype == -1 || recipeId.position == -1) {
recipeId.recipetype = 0;
recipeId.position = 0;
if (recipeId.handlerName != null) {
for (int j = 0; j < currenthandlers.size(); j++) {
IRecipeHandler localHandler = currenthandlers.get(j);
HandlerInfo localHandlerInfo = GuiRecipeTab.getHandlerInfo(localHandler);
if (localHandlerInfo.getHandlerName().equals(recipeId.handlerName)) {
recipeId.recipetype = j;
if (!recipeId.ingredients.isEmpty()) {
for (int i = 0; i < localHandler.numRecipes(); i++) {
if (recipeId.equalsIngredients(localHandler.getIngredientStacks(i))) {
recipeId.position = i;
break;
}
}
}
break;
}
}
}
}
setRecipePage(recipeId.recipetype, recipeId.position);
}
public List<PositionedStack> getFocusedRecipeIngredients()
{
final int recipesPerPage = getRecipesPerPage();
for (int idx = page * recipesPerPage; idx < handler.numRecipes() && idx < (page + 1) * recipesPerPage; idx++) {
if (recipeInFocus(idx)) {
return handler.getIngredientStacks(idx);
}
}
return null;
}
protected boolean recipeInFocus(int idx)
{
final PositionedStack result = handler.getResultStack(idx);
if (result != null && isMouseOver(result, idx)) {
return true;
}
final List<PositionedStack> stacks = handler.getOtherStacks(idx);
for (PositionedStack stack : stacks) {
if (isMouseOver(stack, idx)) {
return true;
}
}
return false;
}
public String getHandlerName()
{
return handlerInfo.getHandlerName();
}
public IRecipeHandler getHandler() {
return handler;
}
@@ -305,6 +219,7 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve
return IntStream.range(minIndex, maxIndex).boxed().collect(Collectors.toList());
}
@Override
public void keyTyped(char c, int i) {
if (i == Keyboard.KEY_ESCAPE) //esc
@@ -439,6 +354,21 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve
setRecipePage(--recipetype);
}
public HandlerInfo getHandlerInfo(IRecipeHandler handler) {
final String handlerID;
if(handler instanceof TemplateRecipeHandler) {
handlerID = (((TemplateRecipeHandler)handler).getOverlayIdentifier());
} else {
handlerID = null;
}
HandlerInfo info = GuiRecipeTab.getHandlerInfo(handler.getHandlerId(), handlerID);
if (info == null)
return GuiRecipeTab.DEFAULT_HANDLER_INFO;
return info;
}
private void overlayRecipe(int recipe) {
final IRecipeOverlayRenderer renderer = handler.getOverlayRenderer(firstGui, recipe);
final IOverlayHandler overlayHandler = handler.getOverlayHandler(firstGui, recipe);
@@ -649,12 +579,8 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve
return false;
}
}
private int getRecipesPerPage() {
return getRecipesPerPage(handlerInfo);
}
private int getRecipesPerPage(HandlerInfo handlerInfo) {
private int getRecipesPerPage() {
if(handlerInfo != null)
return Math.max(Math.min(((ySize - (buttonHeight*3)) / handlerInfo.getHeight()), handlerInfo.getMaxRecipesPerPage()), 1);
else
@@ -157,24 +157,6 @@ public abstract class GuiRecipeTab extends Widget {
selected = handler == current;
}
public static HandlerInfo getHandlerInfo(IRecipeHandler handler)
{
final String handlerID;
if (handler instanceof TemplateRecipeHandler) {
handlerID = ((TemplateRecipeHandler) handler).getOverlayIdentifier();
} else {
handlerID = null;
}
HandlerInfo info = getHandlerInfo(handler.getHandlerId(), handlerID);
if (info == null)
return GuiRecipeTab.DEFAULT_HANDLER_INFO;
return info;
}
public static HandlerInfo getHandlerInfo(String name, String name2) {
HandlerInfo res = handlerMap.get(name);
if (res == null) res = handlerMap.get(name2);
@@ -16,7 +16,7 @@ import org.apache.logging.log4j.Level;
public class HandlerInfo {
public static int DEFAULT_HEIGHT = 65;
public static int DEFAULT_WIDTH = 166;
public static int DEFAULT_MAX_PER_PAGE = 1;
public static int DEFAULT_MAX_PER_PAGE = 2;
private String handlerName;
@@ -120,5 +120,4 @@ public class RecipeInfo
API.registerRecipeHandler(new ProfilerRecipeHandler(true));
API.registerUsageHandler(new ProfilerRecipeHandler(false));
}
}
@@ -5,12 +5,9 @@ import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.PositionedStack;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import java.util.List;
public class RecipeItemInputHandler implements IContainerInputHandler
{
@Override
@@ -26,17 +23,9 @@ public class RecipeItemInputHandler implements IContainerInputHandler
if(keyCode == NEIClientConfig.getKeyBinding("gui.usage"))
return GuiUsageRecipe.openRecipeGui("item", stackover.copy());
if (keyCode == NEIClientConfig.getKeyBinding("gui.bookmark")) {
if(keyCode == NEIClientConfig.getKeyBinding("gui.bookmark")) {
NEIClientConfig.logger.debug("Adding or removing {} from bookmarks", stackover.getDisplayName());
List<PositionedStack> ingredients = null;
String handlerName = "";
if (gui instanceof GuiRecipe && NEIClientConfig.saveCurrentRecipeInBookmarksEnabled()) {
ingredients = ((GuiRecipe) gui).getFocusedRecipeIngredients();
handlerName = ((GuiRecipe) gui).getHandlerName();
}
ItemPanels.bookmarkPanel.addOrRemoveItem(stackover.copy(), handlerName, ingredients);
ItemPanels.bookmarkPanel.addOrRemoveItem(stackover.copy());
}
return false;
@@ -53,32 +42,27 @@ public class RecipeItemInputHandler implements IContainerInputHandler
if (!(gui instanceof GuiRecipe))
return false;
//disabled open recipe gui if hold shift (player have move recipe)
if (button == 0 && ItemPanels.bookmarkPanel.getStackMouseOver(mousex, mousey) != null && NEIClientUtils.shiftKey()) {
return false;
}
if(button == 0)
return GuiCraftingRecipe.openRecipeGui("item", stackover.copy());
if(button == 1)
return GuiUsageRecipe.openRecipeGui("item", stackover.copy());
return false;
}
@Override
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID)
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID)
{
}
@Override
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button)
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button)
{
}
@Override
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button)
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button)
{
}
@@ -87,18 +71,18 @@ public class RecipeItemInputHandler implements IContainerInputHandler
{
return false;
}
@Override
public boolean mouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled)
{
return false;
}
@Override
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled)
{
}
@Override
public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime)
{
@@ -1,76 +0,0 @@
package codechicken.nei.recipe;
import codechicken.nei.api.IStackStringifyHandler;
import codechicken.nei.recipe.stackinfo.DefaultStackStringifyHandler;
import codechicken.nei.recipe.stackinfo.GTFluidStackStringifyHandler;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import java.util.ArrayList;
public class StackInfo
{
public static final ArrayList<IStackStringifyHandler> stackStringifyHandlers = new ArrayList<>();
static {
stackStringifyHandlers.add(new DefaultStackStringifyHandler());
stackStringifyHandlers.add(new GTFluidStackStringifyHandler());
}
public static NBTTagCompound itemStackToNBT(ItemStack stack)
{
return itemStackToNBT(stack, true);
}
public static NBTTagCompound itemStackToNBT(ItemStack stack, boolean saveStackSize)
{
NBTTagCompound nbTag = null;
for (int i = stackStringifyHandlers.size() - 1; i >= 0 && nbTag == null; i--) {
nbTag = stackStringifyHandlers.get(i).convertItemStackToNBT(stack, saveStackSize);
}
return nbTag;
}
public static ItemStack loadFromNBT(NBTTagCompound nbtTag)
{
ItemStack stack = null;
for (int i = stackStringifyHandlers.size() - 1; i >= 0 && stack == null; i--) {
stack = stackStringifyHandlers.get(i).convertNBTToItemStack(nbtTag);
}
return stack;
}
public static boolean equalItemAndNBT(ItemStack stackA, ItemStack stackB, boolean useNBT)
{
if (!stackA.isItemEqual(stackB)) {
return false;
}
if (useNBT) {
NBTTagCompound tagCompoundA = itemStackToNBT(stackA, false);
NBTTagCompound tagCompoundB = itemStackToNBT(stackB, false);
return tagCompoundA == null && tagCompoundB == null || tagCompoundA != null && tagCompoundB != null && tagCompoundA.equals(tagCompoundB);
}
return true;
}
public static FluidStack getFluid(ItemStack stack)
{
FluidStack fluid = null;
for (int i = stackStringifyHandlers.size() - 1; i >= 0 && fluid == null; i--) {
fluid = stackStringifyHandlers.get(i).getFluid(stack);
}
return fluid;
}
}
@@ -1,56 +0,0 @@
package codechicken.nei.recipe.stackinfo;
import codechicken.nei.api.IStackStringifyHandler;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
public class DefaultStackStringifyHandler implements IStackStringifyHandler
{
public NBTTagCompound convertItemStackToNBT(ItemStack stack, boolean saveStackSize)
{
final NBTTagCompound nbTag = new NBTTagCompound();
nbTag.setString("strId", Item.itemRegistry.getNameForObject(stack.getItem()));
nbTag.setInteger("Count", saveStackSize? stack.stackSize: 1);
nbTag.setShort("Damage", (short)stack.getItemDamage());
if (stack.hasTagCompound()) {
nbTag.setTag("tag", stack.getTagCompound());
}
return nbTag;
}
public ItemStack convertNBTToItemStack(NBTTagCompound nbtTag)
{
final String strId = nbtTag.getString("strId");
nbtTag = (NBTTagCompound)nbtTag.copy();
nbtTag.setInteger("id", GameData.getItemRegistry().getId(strId)); //getObject
final ItemStack stack = ItemStack.loadItemStackFromNBT(nbtTag);
if (stack != null) {
stack.stackSize = nbtTag.getInteger("Count");
}
return stack;
}
public FluidStack getFluid(ItemStack stack)
{
FluidStack fluidStack = FluidContainerRegistry.getFluidForFilledItem(stack);
if (fluidStack == null && stack.getItem() instanceof IFluidContainerItem) {
fluidStack = ((IFluidContainerItem) stack.getItem()).getFluid(stack);
}
return fluidStack;
}
}
@@ -1,84 +0,0 @@
package codechicken.nei.recipe.stackinfo;
import codechicken.nei.api.IStackStringifyHandler;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import java.lang.reflect.Method;
public class GTFluidStackStringifyHandler implements IStackStringifyHandler
{
public static Class GTDisplayFluid = null;
public static Method getFluidDisplayStack = null;
public static Method getFluidFromDisplayStack = null;
static {
try {
final Class gtUtility = Class.forName("gregtech.api.util.GT_Utility");
GTDisplayFluid = Class.forName("gregtech.common.items.GT_FluidDisplayItem");
getFluidFromDisplayStack = gtUtility.getMethod("getFluidFromDisplayStack", ItemStack.class);
getFluidDisplayStack = gtUtility.getMethod("getFluidDisplayStack", FluidStack.class, boolean.class);
} catch (Exception ignored) { /*Do nothing*/ }
}
public NBTTagCompound convertItemStackToNBT(ItemStack stack, boolean saveStackSize)
{
if (GTDisplayFluid != null && GTDisplayFluid.isInstance(stack.getItem())) {
final NBTTagCompound nbTag = new NBTTagCompound();
final FluidStack fluidStack = getFluid(stack);
nbTag.setString("gtFluidName", fluidStack.getFluid().getName());
nbTag.setInteger("Count", saveStackSize? fluidStack.amount: 1);
return nbTag;
}
return null;
}
public ItemStack convertNBTToItemStack(NBTTagCompound nbtTag)
{
if (getFluidDisplayStack != null && nbtTag.hasKey("gtFluidName")) {
final String fluidName = nbtTag.getString("gtFluidName");
final Fluid fluid = FluidRegistry.getFluid(fluidName);
final int amount = nbtTag.getInteger("Count");
try {
final Object obj = getFluidDisplayStack.invoke(null, new FluidStack(fluid, amount), true);
if (obj != null) {
return (ItemStack) obj;
}
} catch (Exception e) {}
}
return null;
}
public FluidStack getFluid(ItemStack stack)
{
if (getFluidFromDisplayStack != null && GTDisplayFluid != null && GTDisplayFluid.isInstance(stack.getItem())) {
try {
final Object obj = getFluidFromDisplayStack.invoke(null, stack);
if (obj != null) {
return (FluidStack) obj;
}
} catch (Exception e) {}
}
return null;
}
}
@@ -34,11 +34,7 @@ public class NBTJson {
private static final Gson gson = new GsonBuilder().create();
public static String toJson(NBTTagCompound tag) {
return toJson(toJsonObject(tag));
}
public static String toJson(JsonElement json) {
final String jsonString = json.toString();
final String jsonString = toJsonObject(tag).toString();
return gson.toJson(parser.parse(jsonString));
}
@@ -54,24 +50,6 @@ public class NBTJson {
root.add(nbtEntry.getKey(), toJsonObject(nbtEntry.getValue()));
}
return root;
} else if (nbt instanceof NBTTagByte) {
// Number (byte)
return new JsonPrimitive(Byte.toString(((NBTTagByte) nbt).func_150290_f()) + 'B');
} else if (nbt instanceof NBTTagShort) {
// Number (short)
return new JsonPrimitive(Short.toString(((NBTTagShort) nbt).func_150289_e()) + 'S');
} else if (nbt instanceof NBTTagInt) {
// Number (int)
return new JsonPrimitive(((NBTTagInt) nbt).func_150287_d());
} else if (nbt instanceof NBTTagLong) {
// Number (long)
return new JsonPrimitive(Long.toString(((NBTTagLong) nbt).func_150291_c()) + 'L');
} else if (nbt instanceof NBTTagFloat) {
// Number (float)
return new JsonPrimitive(Float.toString(((NBTTagFloat) nbt).func_150288_h()) + 'F');
} else if (nbt instanceof NBTTagDouble) {
// Number (double)
return new JsonPrimitive(Double.toString(((NBTTagDouble) nbt).func_150286_g()) + 'D');
} else if (nbt instanceof NBTBase.NBTPrimitive) {
// Number
return new JsonPrimitive(((NBTBase.NBTPrimitive) nbt).func_150286_g());
@@ -208,7 +208,6 @@ gtPlusPlus.nei.GT_NEI_FluidReactor,GT++,gregtech:gt.blockmachines:998,,miscutils
gtPlusPlus.nei.GT_NEI_MillingMachine,GT++,gregtech:gt.blockmachines:31027,,miscutils,TRUE,,,120,,2,,,,,,
li.cil.oc.integration.nei.CallbackDocHandler,OpenComputers,OpenComputers:item:98,,OpenComputers,TRUE,,,120,,2,,,,,,
li.cil.oc.integration.nei.ManualUsageHandler,OpenComputers,OpenComputers:item:98,,OpenComputers,TRUE,,,120,,2,,,,,,
com.pam.harvestcraft.GardenRecipeHandler,Pam's Harvestcraft,harvestcraft:berrygarden,,harvestcraft,TRUE,,,100,,5,,,,,,
tonius.neiintegration.mods.harvestcraft.RecipeHandlerApiary,Pam's Harvestcraft,harvestcraft:apiary,,harvestcraft,TRUE,,,70,,5,,,,,,There's only 1 though
tonius.neiintegration.mods.harvestcraft.RecipeHandlerChurn,Pam's Harvestcraft,harvestcraft:churn,,harvestcraft,TRUE,,,65,,5,,,,,,Same as above
tonius.neiintegration.mods.harvestcraft.RecipeHandlerOven,Pam's Harvestcraft,harvestcraft:oven,,harvestcraft,TRUE,,,65,,5,,,,,,
@@ -450,4 +449,3 @@ neresources.nei.NEIEnchantmentHandler,Not Enough Resources,minecraft:anvil,,nere
neresources.nei.NEIMobHandler,Not Enough Resources,minecraft:skull:4,,neresources,TRUE,,,130,166,2,,,,,,
neresources.nei.NEIOreHandler,Not Enough Resources,minecraft:diamond_ore,,neresources,TRUE,,,65,166,5,,,,,,
neresources.nei.NEIPlantHandler,Not Enough Resources,minecraft:wheat,,neresources,TRUE,,,130,166,2,,,,,,
wanion.biggercraftingtables.nei.BigShapedRecipeHandler,Bigger Crafting Tables,minecraft:crafting_table,,biggercraftingtables,TRUE,,,130,,2,,,,,,
1 handler modName itemName nbtInfo modId modRequired excludedModId yShift handlerHeight handlerWidth maxRecipesPerPage imageResource imageX imageY imageWidth imageHeight itemNotes
208 gtPlusPlus.nei.GT_NEI_MillingMachine GT++ gregtech:gt.blockmachines:31027 miscutils TRUE 120 2
209 li.cil.oc.integration.nei.CallbackDocHandler OpenComputers OpenComputers:item:98 OpenComputers TRUE 120 2
210 li.cil.oc.integration.nei.ManualUsageHandler OpenComputers OpenComputers:item:98 OpenComputers TRUE 120 2
com.pam.harvestcraft.GardenRecipeHandler Pam's Harvestcraft harvestcraft:berrygarden harvestcraft TRUE 100 5
211 tonius.neiintegration.mods.harvestcraft.RecipeHandlerApiary Pam's Harvestcraft harvestcraft:apiary harvestcraft TRUE 70 5 There's only 1 though
212 tonius.neiintegration.mods.harvestcraft.RecipeHandlerChurn Pam's Harvestcraft harvestcraft:churn harvestcraft TRUE 65 5 Same as above
213 tonius.neiintegration.mods.harvestcraft.RecipeHandlerOven Pam's Harvestcraft harvestcraft:oven harvestcraft TRUE 65 5
449 neresources.nei.NEIMobHandler Not Enough Resources minecraft:skull:4 neresources TRUE 130 166 2
450 neresources.nei.NEIOreHandler Not Enough Resources minecraft:diamond_ore neresources TRUE 65 166 5
451 neresources.nei.NEIPlantHandler Not Enough Resources minecraft:wheat neresources TRUE 130 166 2
wanion.biggercraftingtables.nei.BigShapedRecipeHandler Bigger Crafting Tables minecraft:crafting_table biggercraftingtables TRUE 130 2
@@ -117,12 +117,6 @@ nei.options.inventory.jei_style_tabs.false=No [Weirdo]
nei.options.inventory.jei_style_item_presence_overlay=JEI Style Item Overlay on ?-Hover
nei.options.inventory.jei_style_item_presence_overlay.true=Yes
nei.options.inventory.jei_style_item_presence_overlay.false=No
nei.options.inventory.saveCurrentRecipeInBookmarksEnabled=Save Current Recipe in Bookmarks
nei.options.inventory.saveCurrentRecipeInBookmarksEnabled.true=Enabled
nei.options.inventory.saveCurrentRecipeInBookmarksEnabled.false=Disabled
nei.options.inventory.useNBTInBookmarks=Use NBT in Bookmarks
nei.options.inventory.useNBTInBookmarks.true=Yes
nei.options.inventory.useNBTInBookmarks.false=No
nei.options.inventory.creative_tab_style=Creative or JEI tab style
nei.options.inventory.creative_tab_style.true=Creative
nei.options.inventory.creative_tab_style.false=JEI
@@ -117,12 +117,6 @@ nei.options.inventory.jei_style_tabs.false=否 [不会吧]
nei.options.inventory.jei_style_item_presence_overlay=JEI风格物品覆盖?-悬停
nei.options.inventory.jei_style_item_presence_overlay.true=是
nei.options.inventory.jei_style_item_presence_overlay.false=否
nei.options.inventory.saveCurrentRecipeInBookmarksEnabled=保存书签中的当前合成表
nei.options.inventory.saveCurrentRecipeInBookmarksEnabled.true=启用
nei.options.inventory.saveCurrentRecipeInBookmarksEnabled.false=禁用
nei.options.inventory.useNBTInBookmarks=在书签中启用NBT
nei.options.inventory.useNBTInBookmarks.true=是
nei.options.inventory.useNBTInBookmarks.false=否
nei.options.inventory.creative_tab_style=创造模式/JEI标签页
nei.options.inventory.creative_tab_style.true=创造模式
nei.options.inventory.creative_tab_style.false=JEI
-7
View File
@@ -1,7 +0,0 @@
{
"repo": "https://github.com/GTNewHorizons/CodeChickenLib/releases/download/1.1.4.1/",
"file": "CodeChickenLib-1.7.10-1.1.4.1.jar",
"dev": "CodeChickenLib-1.7.10-1.1.4.1-dev.jar",
"class": "codechicken.lib.asm.ASMHelper",
"coreLib": true
}