Compare commits

...
49 Commits
Author SHA1 Message Date
Alexdoru 2ba0773401 [Memory-opti:fix leak] Fix WorldServer leak in NEIServerConfig (#815) 2025-12-16 19:44:15 +00:00
PLASMAchicken eac913c80c Remove Obsolete Code from ModContainer (#820) 2025-12-13 12:42:40 +02:00
slprime 126f0ea73c Fix missing favorites and incorrect crafting chains for recipes with identical ingredients (#814) 2025-11-25 07:24:30 +01:00
slprimeandMartin Robertz cd4668ec84 Backup bookmarks.ini if loading failed (#798)
Co-authored-by: Martin Robertz <[email protected]>
2025-11-24 08:52:01 +02:00
slprime 7c247dd0d2 Ignore space hotkeys when typing in search bar (#808) 2025-11-24 00:21:24 +02:00
slprime 87b549fab5 Normalize Fluid Packet (#811) 2025-11-16 14:17:56 +02:00
slprimeandMartin Robertz 8ed1f7a043 Properly clears inventory before filling a recipe (#796)
Co-authored-by: Martin Robertz <[email protected]>
2025-11-13 08:19:55 +02:00
slprime f2efa35654 Extend HandlerInfo.Builder interface (#809) 2025-11-08 23:54:35 +02:00
slprime bcef287e71 Fix Permutations for Information Handler (#804) 2025-11-08 09:32:47 +02:00
slprime 7f555f7a7f Add Tooltip for debug option (#805) 2025-11-08 09:27:21 +02:00
slprime 9fd38da205 Correctly collapse recipe (#807) 2025-11-08 09:18:14 +02:00
slprime 2fa5563408 Optimizing cross-dimension loading (#806) 2025-11-08 09:12:40 +02:00
slprimeandMartin Robertz 541c0e2def Add 'Bookmark recipe with count' Option (#776)
Co-authored-by: Martin Robertz <[email protected]>
2025-11-07 19:54:09 +02:00
Martin Robertz ac868097e7 update 2025-11-07 18:32:09 +01:00
slprimeandMartin Robertz 2f0de0b6a8 Add 'Show only favorites' option to the 'Craftables' panel (#800)
Co-authored-by: Martin Robertz <[email protected]>
2025-11-06 17:37:00 +02:00
sisyphussy 32bc29e654 Remove glBlitFramebuffer (#801) 2025-11-06 14:36:30 +02:00
slprimeandMartin Robertz ef8a7d8bd5 Create normalizeRecipeQueryStack (#772)
Co-authored-by: Martin Robertz <[email protected]>
2025-11-05 23:15:45 +02:00
slprimeandMartin Robertz adc5a5df16 Add GuiOverlapSlots for subpanels (#799)
Co-authored-by: Martin Robertz <[email protected]>
2025-11-05 21:55:33 +02:00
slprime a828ff227a Remove try/catch from static block (#797) 2025-11-05 19:08:55 +01:00
slprime 9b6f98330e Remove Permutations from Output (#777) 2025-11-05 19:14:48 +02:00
slprime 667c8cb5b6 Implement Dynamic Handler Height (#792) 2025-11-05 19:00:09 +02:00
slprimeandMartin Robertz a186f69444 Fix favorite state refresh (#787)
Co-authored-by: Martin Robertz <[email protected]>
2025-11-04 23:11:00 +01:00
slprime 16f4f20239 Fixed small mouse movement while double-clicking causing drop all items (#793) 2025-11-04 23:10:43 +01:00
slprime bac207cacb Change item slot size in GuiRecipe (#789) 2025-11-04 23:10:32 +01:00
slprime 630e856d83 Fix hotkeys when keyBinding disabled (#786) 2025-10-30 10:17:16 +02:00
slprime 42d96aed0c Show 'Delete Item' tooltip in Creative Mode (#785) 2025-10-29 21:47:34 +01:00
slprimeandsisyphussy bd6384bf24 Сalculate the height of the container before scrolling to the recipe (#782)
Co-authored-by: sisyphussy <[email protected]>
2025-10-29 07:52:33 +00:00
slprime af9726d356 Fixed shift+scroll of ingredients in the recipe GUI (#783) 2025-10-29 07:42:18 +00:00
Martin Robertz 1e1d2f1076 update 2025-10-29 07:54:19 +01:00
slprimeandWilhelm Schuster 7cb94fb22a Clear rawText before formatting (#780)
Co-authored-by: Wilhelm Schuster <[email protected]>
2025-10-25 15:20:28 +02:00
Martin Robertz 87aa4f9ed5 update 2025-10-25 14:18:58 +02:00
DarkShadow44andMartin Robertz 9760fd3eaf Fix another race condition, affecting IndustrialGrafter (#779)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-25 14:11:49 +02:00
slprime 1054871982 Add Scroll to Recipe Catalysts (#770) 2025-10-21 12:28:14 +00:00
slprime d90a667f68 Fix Bookmarks Chain Tooltip Height (#773) 2025-10-19 21:33:46 +03:00
slprime 69e6df5848 Fix Button Texture (#771) 2025-10-19 19:56:23 +02:00
slprime 25fa7ce44e Add defaultbookmarkcontainers.cfg (#769) 2025-10-19 16:07:45 +03:00
slprime e3cd7b860d Fix recipe result count (#767) 2025-10-18 11:07:39 +00:00
slprime 2a3aabc073 Add recipe index to recipe handler height (#768) 2025-10-18 13:03:08 +02:00
slprimeandMartin Robertz 76db43c835 Optimize permutations (#761)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-17 22:23:10 +03:00
slprimeandMartin Robertz 40e53eea7a Fixing HUD flickering (#762)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-17 21:36:30 +03:00
Martin Robertz 6c4d16d6b9 update 2025-10-17 12:50:52 +02:00
RealSilverMoon 4a2abe9fd7 Add a function to copy item name and meta (#758) 2025-10-17 10:54:47 +03:00
sisyphussy d47417302e Fix recipe tooltip lighting (#757) 2025-10-14 17:09:02 +03:00
e13401ded8 Optimize Bookmark Chains with Containers (#751)
Co-authored-by: Martin Robertz <[email protected]>
Co-authored-by: sisyphussy <[email protected]>
2025-10-13 11:01:58 +00:00
sisyphussy 7ada842ef3 Fix tooltip item lighting (#755) 2025-10-13 00:29:09 +03:00
slprimeandMartin Robertz fe0c5d4e50 Create Recipe Widget; Recipe GUI: Infinity Scroll; Recipe GUI: Max Height Settings (#701)
Co-authored-by: Martin Robertz <[email protected]>
2025-10-12 18:39:21 +02:00
slprime 2ea9ae1eb9 Show Handler Icon in Bookmarks (#747) 2025-10-09 21:22:37 +02:00
slprime f7f0596fda Show Items Loading Message (#745) 2025-10-08 16:58:23 +02:00
sbwaz d5e919a9cd [Extended+] Fix the prefixed sequence parsing. (#741) 2025-10-04 13:19:00 +02:00
108 changed files with 5545 additions and 2883 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
dependencies {
api('com.github.GTNewHorizons:CodeChickenCore:1.4.7:dev')
implementation('com.github.GTNewHorizons:GTNHLib:0.7.0:dev')
implementation('com.github.GTNewHorizons:GTNHLib:0.8.0:dev')
shadowImplementation('org.apache.commons:commons-csv:1.10.0')
+9 -1
View File
@@ -96,7 +96,9 @@ usesMixinDebug = false
# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise.
mixinPlugin =
# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail!
# Specify the package that contains all of your Mixins. The package must exist or
# the build will fail. If you have a package property defined in your mixins.<modid>.json,
# it must match with this or the build will fail.
mixinsPackage =
# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin!
@@ -172,6 +174,12 @@ curseForgeRelations = requiredDependency\:codechickencore-unofficial
# projects. New projects should not use this parameter.
# customArchiveBaseName =
# Optional parameter to customize the default working directory used by the runClient* tasks. Relative to the project directory.
# runClientWorkingDirectory = run/client
# Optional parameter to customize the default working directory used by the runServer* tasks. Relative to the project directory.
# runServerWorkingDirectory = run/server
# Optional parameter to have the build automatically fail if an illegal version is used.
# This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'.
# The check is ONLY performed if the version is a git tag.
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+2 -2
View File
@@ -114,7 +114,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
@@ -213,7 +213,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
Vendored
+2 -2
View File
@@ -70,11 +70,11 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
+1 -1
View File
@@ -17,7 +17,7 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.43'
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.48'
}
+6 -4
View File
@@ -18,20 +18,22 @@ public SearchExpressionLexer(CharStream input, SearchTokenParser searchParser) {
// Lexer rules
REGEX_LEFT : 'r'? '/' -> pushMode(REGEX) ;
QUOTE_LEFT : '"' -> pushMode(QUOTED) ;
DASH : '-' ;
RECIPE_INGREDIENTS : '<&' | '<' ;
RECIPE_RESULT : '>&' | '>' ;
RECIPE_OTHERS : '^&' | '^' ;
PREFIX : CLEAN_SYMBOL {searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
OR : '|' ;
LEFT_BRACKET : '{' ;
RIGHT_BRACKET : '}' ;
PLAIN_TEXT : (CLEAN_SYMBOL | ESCAPED_SYMBOL)+ {!searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
NEWLINE_OR_TAB : [\t\r\n] -> skip ;
SPACE : ' ' ;
ESCAPED_SYMBOL : '\\' . ;
fragment ESCAPED_SYMBOL : '\\' . ;
fragment CLEAN_SYMBOL : ~[-<>^{}|/\\ "] ;
PREFIX : CLEAN_SYMBOL {searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
CLEAN_SYMBOL : ~[-<>^{}|/\\ "] ;
mode REGEX;
+4 -1
View File
@@ -56,7 +56,7 @@ prefixedExpression
token[Character prefix]
: regex[prefix]
| quoted[prefix]
| PLAIN_TEXT
| plainText
;
regex[Character prefix]
@@ -67,4 +67,7 @@ quoted[Character prefix]
: QUOTE_LEFT QUOTED_CONTENT QUOTE_RIGHT?
;
plainText
: (CLEAN_SYMBOL | ESCAPED_SYMBOL)+
;
@@ -5,13 +5,14 @@ import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSlot, ? extends ItemsGrid.MouseContext>>
extends Widget implements IContainerTooltipHandler {
@@ -20,6 +21,7 @@ public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSl
protected int mouseDownItemIndex = -1;
protected int splittingLineColor = 0xffffffff;
protected int linePaddingStart = 0;
protected T grid;
public boolean isEmpty() {
@@ -52,19 +54,30 @@ public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSl
return this.grid.getSlotMouseOver(mousex, mousey);
}
protected void updateLinePadding() {
GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
this.linePaddingStart = 0;
while (GuiInfo
.hideItemPanelSlot(guiContainer, new Rectangle4i(this.x + this.linePaddingStart, this.y - 1, 10, 2))) {
this.linePaddingStart += 10;
}
}
protected void drawSplittingLine() {
float alpha = (this.splittingLineColor >> 24 & 255) / 255.0F;
float red = (this.splittingLineColor >> 16 & 255) / 255.0F;
float green = (this.splittingLineColor >> 8 & 255) / 255.0F;
float blue = (this.splittingLineColor & 255) / 255.0F;
int width = this.grid.columns * ItemsGrid.SLOT_SIZE;
int width = this.grid.columns * ItemsGrid.SLOT_SIZE - this.linePaddingStart;
int repeat = width / 6;
int shiftX = this.x + (this.w - width) / 2;
int shiftX = this.x + this.linePaddingStart + (this.w - width) / 2;
GL11.glColor4f(red, green, blue, alpha);
for (int i = 0; i < repeat; i++) {
DASH.draw(shiftX + i * 6, y);
DASH.draw(shiftX + i * 6, this.y);
}
GL11.glColor4f(1, 1, 1, 1);
}
@@ -122,13 +135,7 @@ public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSl
if (NEIController.manager.window instanceof GuiRecipe || NEIClientUtils.shiftKey()
|| !NEIClientConfig.canCheatItem(hoverSlot.getItemStack())) {
if (button == 0) {
GuiCraftingRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
} else if (button == 1) {
GuiUsageRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
}
ShortcutInputHandler.handleMouseClick(hoverSlot.getItemStack().copy());
} else {
NEIClientUtils.cheatItem(getDraggedStackWithQuantity(hoverSlot.getItemStack()), button, -1);
}
@@ -29,6 +29,7 @@ import codechicken.nei.api.IBookmarkContainerHandler;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarkStorage;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.bookmark.GroupingItem;
@@ -184,23 +185,26 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
final boolean existsRecipe = recipeId != null
&& this.grid.existsRecipe(recipeId, BookmarkGrid.DEFAULT_GROUP_ID);
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(itemStack);
long factor = nbTag.getInteger("Count");
long count = nbTag.getInteger("Count");
long factor = existsRecipe ? Math.max(count, 1) : 1;
if (existsRecipe) {
for (int i = 0; i < this.grid.size(); i++) {
if (this.grid.getBookmarkItem(i).equalsRecipe(recipeId, groupId)) {
final long multiplier = this.grid.getBookmarkItem(i).getMultiplier();
factor *= multiplier;
count *= this.grid.getBookmarkItem(i).getMultiplier();
break;
}
}
} else {
factor = nbTag.hasKey("gtFluidName") ? Math.min(144, nbTag.getInteger("Count")) : 1;
}
this.grid.addItem(BookmarkItem.of(groupId, itemStack, factor, recipeId, false), true);
this.grid.addItem(
BookmarkItem.of(
groupId,
StackInfo.withAmount(itemStack, count),
factor,
recipeId,
existsRecipe ? BookmarkItemType.RESULT : BookmarkItemType.ITEM),
true);
return true;
}
@@ -242,7 +246,8 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
if (stack != null && uniqueRecipe.add(recipeId)) {
this.grid.addItem(
BookmarkItem.of(groupId, stack, StackInfo.getAmount(stack), recipeId, false),
BookmarkItem
.of(groupId, stack, StackInfo.getAmount(stack), recipeId, BookmarkItemType.ITEM),
true);
uniqueStack.add(stack);
}
@@ -302,7 +307,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
final int groupId = slot.getGroupId();
final RecipeId recipeId = slot.getRecipeId();
final RecipeId recipeId = slot.getType() == BookmarkItemType.ITEM ? null : slot.getRecipeId();
final BookmarkGroup group = slot.getGroup();
if (group.crafting != null && group.collapsed) {
@@ -366,7 +371,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
public RecipeId getRecipeId(int itemIndex) {
BookmarkItem meta = this.grid.getCalculatedItem(itemIndex);
return meta.isIngredient ? null : meta.recipeId;
return meta.type == BookmarkItemType.INGREDIENT ? null : meta.recipeId;
}
public boolean existsRecipe(RecipeId recipeId, int groupId) {
@@ -695,7 +700,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
@Override
public List<String> handleTooltip(GuiContainer gui, int mousex, int mousey, List<String> currenttip) {
public List<String> handleTooltip(int mousex, int mousey, List<String> currenttip) {
if (this.grid.getPerPage() == 0 || this.grid.isEmpty()) {
return new ArrayList<>();
@@ -722,7 +727,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
this.recipeChainTooltipLineHandler = null;
}
return super.handleTooltip(gui, mousex, mousey, currenttip);
return super.handleTooltip(mousex, mousey, currenttip);
}
@Override
@@ -748,7 +753,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
final int overRowIndex = this.grid.getHoveredRowIndex(true);
final BookmarksGridSlot slot = getSlotMouseOver(mousex, mousey);
@@ -781,7 +786,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
NEIClientConfig.getKeyName("gui.remove_recipe"),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
if (BookmarkContainerInfo.getBookmarkContainerHandler(gui) != null) {
if (BookmarkContainerInfo.getBookmarkContainerHandler(NEIClientUtils.getGuiContainer()) != null) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark_pull_items"),
NEIClientUtils.translate("bookmark.group.pull_items"));
@@ -878,7 +883,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
}
return hotkeys;
return super.handleHotkeys(mousex, mousey, hotkeys);
}
private List<String> recipeChainTooltip(int groupId, List<String> currenttip) {
@@ -915,13 +920,13 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
@Override
public List<String> handleItemTooltip(GuiContainer gui, ItemStack itemstack, int mousex, int mousey,
List<String> currenttip) {
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> currenttip) {
final BookmarksGridSlot slot = this.grid.getSlotMouseOver(mousex, mousey);
if (slot != null) {
if (slot.isIngredient() && slot.getRecipeId() != null && slot.getBookmarkItem().permutations.size() > 1) {
if (slot.getType() == BookmarkItemType.INGREDIENT && slot.getRecipeId() != null
&& slot.getBookmarkItem().permutations.size() > 1) {
RecipeId recipeId = slot.getRecipeId();
if (recipeId == null) {
@@ -1019,7 +1024,8 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
if (NEIClientUtils.altKey()) {
multiplier = NEIClientConfig.showItemQuantityWidget() ? NEIClientConfig.getItemQuantity() : 0;
if (multiplier == 0) {
multiplier = slot.getItemStack().getMaxStackSize();
multiplier = StackInfo.itemStackToNBT(slot.getItemStack()).hasKey("gtFluidName") ? 144
: slot.getItemStack().getMaxStackSize();
}
}
@@ -1181,7 +1187,15 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
if (!items.isEmpty()) {
containerHandler.pullBookmarkItemsFromContainer(guiContainer, items);
final int helmStackIndex = FastTransferManager.dropHeldItem(guiContainer);
if (guiContainer.mc.thePlayer.inventory.getItemStack() == null) {
containerHandler.pullBookmarkItemsFromContainer(guiContainer, items);
if (helmStackIndex != -1) {
FastTransferManager.clickSlot(guiContainer, helmStackIndex, 0, 0);
}
}
}
return true;
@@ -1252,7 +1266,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
@Deprecated
public BookmarkRecipeId getBookmarkRecipeId(int itemIndex) {
BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
return item == null || item.isIngredient || item.recipeId == null ? null
return item == null || item.type == BookmarkItemType.INGREDIENT || item.recipeId == null ? null
: new BookmarkRecipeId(item.recipeId.getHandleName(), item.recipeId.getIngredients());
}
@@ -24,6 +24,7 @@ import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiErrorScreen;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiSelectWorld;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.resources.IResource;
import net.minecraft.entity.Entity;
@@ -42,7 +43,6 @@ import com.google.common.collect.Lists;
import codechicken.core.ClassDiscoverer;
import codechicken.core.ClientUtils;
import codechicken.core.GuiModListScroll;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
@@ -153,6 +153,7 @@ public class ClientHandler {
loadHiddenHandlers();
loadEnableAutoFocus();
loadGuiCraftablesBlacklist();
loadDefaultBookmarkContainers();
ItemInfo.preInit();
StackInfo.loadGuidFilters();
}
@@ -253,6 +254,20 @@ public class ClientHandler {
lines -> ItemCraftablesPanel.guiBlacklist = lines.collect(Collectors.toList()));
}
public static void loadDefaultBookmarkContainers() {
loadSettingsFile("defaultbookmarkcontainers.cfg", lines -> {
for (String clazz : lines.collect(Collectors.toList())) {
try {
API.registerBookmarkContainerHandler(
(Class<? extends GuiContainer>) Class.forName(clazz),
new DefaultBookmarkContainerHandler());
} catch (Exception e) {
NEIClientConfig.logger.error("Failed to load class '{}' for defaultbookmarkcontainers.cfg", clazz);
}
}
});
}
public static void loadHiddenItems() {
loadSettingsFile("hiddenitems.cfg", lines -> lines.forEach(API::hideItem));
}
@@ -260,7 +275,6 @@ public class ClientHandler {
public static void load() {
instance = new ClientHandler();
GuiModListScroll.register("NotEnoughItems");
PacketCustom.assignHandler(NEICPH.channel, new NEICPH());
FMLCommonHandler.instance().bus().register(instance);
MinecraftForge.EVENT_BUS.register(instance);
@@ -1,7 +1,7 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
@@ -12,36 +12,19 @@ public class DefaultBookmarkContainerHandler implements IBookmarkContainerHandle
@Override
public void pullBookmarkItemsFromContainer(GuiContainer guiContainer, ArrayList<ItemStack> bookmarkItems) {
FastTransferManager manager = new FastTransferManager();
LinkedList<ItemStack> containerStacks = manager.saveContainer(guiContainer.inventorySlots);
final FastTransferManager manager = new FastTransferManager();
final List<ItemStack> containerStacks = getStorageStacks(guiContainer);
for (ItemStack bookmarkItem : bookmarkItems) {
int bookmarkSizeBackup = bookmarkItem.stackSize;
for (int i = 0; i < containerStacks.size() - 4 * 9; i++) { // Last 36 slots are player inventory
ItemStack containerItem = containerStacks.get(i);
if (containerItem == null) {
continue;
}
for (int i = 0; i < containerStacks.size() && bookmarkItem.stackSize > 0; i++) {
final ItemStack containerItem = containerStacks.get(i);
if (bookmarkItem.isItemEqual(containerItem)) {
if (bookmarkItem.stackSize <= 0) {
break;
}
int transferAmount = Math.min(bookmarkItem.stackSize, containerItem.stackSize);
final int transferAmount = Math.min(bookmarkItem.stackSize, containerItem.stackSize);
manager.transferItems(guiContainer, i, transferAmount);
bookmarkItem.stackSize -= transferAmount;
if (bookmarkItem.stackSize == 0) {
break;
}
}
}
bookmarkItem.stackSize = bookmarkSizeBackup;
}
}
}
@@ -9,7 +9,9 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
@@ -281,6 +283,27 @@ public class FastTransferManager {
GuiContainerManager.getManager(window).handleSlotClick(slotIndex, button, modifier);
}
public static int dropHeldItem(GuiContainer window) {
final EntityPlayerSP player = window.mc.thePlayer;
final ItemStack held = player.inventory.getItemStack();
if (held == null) return -1;
for (int i = 0; held != null && i < window.inventorySlots.inventorySlots.size(); i++) {
final Slot slot = window.inventorySlots.inventorySlots.get(i);
if (slot.inventory instanceof InventoryPlayer && !slot.getHasStack() && slot.isItemValid(held)) {
clickSlot(window, i, 0, 0);
if (player.inventory.getItemStack() == null) {
return i;
}
}
}
return -1;
}
private boolean fillZoneWithHeldItem(GuiContainer window, int zoneIndex) {
for (int transferTo : slotZones.get(zoneIndex)) {
ItemStack held = NEIClientUtils.getHeldItem();
@@ -117,12 +117,14 @@ public class FavoriteRecipes {
final RecipeId recipeId = RecipeId.of(jsonObject.getAsJsonObject("recipeId"));
final ItemStack stack = StackInfo.loadFromNBT(itemStackNBT);
if (stack != null) {
final String fluidKey = getFluidKey(stack);
if (recipeId == null || stack == null) {
continue;
}
if (fluidKey != null) {
fluids.put(fluidKey, recipeId);
}
final String fluidKey = getFluidKey(stack);
if (fluidKey != null) {
fluids.put(fluidKey, recipeId);
}
items.put(itemStackNBT, recipeId);
@@ -132,8 +134,8 @@ public class FavoriteRecipes {
}
}
} catch (IllegalArgumentException | JsonSyntaxException | IllegalStateException e) {
NEIClientConfig.logger.error("Failed to load favorite from json string:\n{}", itemStr);
} catch (Exception e) {
NEIClientConfig.logger.error("Failed to load favorite from json string: {}", itemStr);
}
}
@@ -181,6 +183,10 @@ public class FavoriteRecipes {
return null;
}
public static int size() {
return items.size() + fluids.size();
}
public static boolean contains(ItemStack stack) {
return getFavorite(stack) != null;
}
@@ -61,6 +61,11 @@ public class FormattedTextField extends GuiTextField {
super.setFocused(focus);
}
@Override
public void setText(String rawText) {
super.setText(EnumChatFormatting.getTextWithoutFormattingCodes(rawText));
}
@Override
public void setSelectionPos(int p_146199_1_) {
String text = this.getText();
@@ -42,13 +42,11 @@ public class HUDRenderer implements IKeyStateTracker {
&& mc.objectMouseOver != null
&& mc.objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {
World world = mc.theWorld;
ItemStack[] items = ItemInfo.getIdentifierItems(world, mc.thePlayer, mc.objectMouseOver)
.toArray(new ItemStack[0]);
final List<ItemStack> items = ItemInfo.getIdentifierItems(world, mc.thePlayer, mc.objectMouseOver);
if (items.length == 0) return;
ItemStack stack = StackInfo.getItemStackWithMinimumDamage(items);
if (items.isEmpty()) return;
final ItemStack stack = StackInfo.getItemStackWithMinimumDamage(items.toArray(new ItemStack[0]));
renderOverlay(stack, ItemInfo.getText(stack, world, mc.thePlayer, mc.objectMouseOver), getPositioning());
}
}
@@ -27,8 +27,8 @@ public class HeldItemHandler implements IContainerInputHandler, IContainerToolti
protected boolean contains(int mousex, int mousey) {
return NEIClientUtils.getHeldItem() != null && !ItemPanels.bookmarkPanel.inEditingState()
&& !AutoCraftingManager.processing()
&& (ItemPanels.bookmarkPanel.contains(mousex, mousey) || ItemPanels.itemPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.historyPanel.contains(mousex, mousey));
&& (ItemPanels.bookmarkPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.containsWithSubpanels(mousex, mousey));
}
@Override
@@ -36,7 +36,8 @@ public class HeldItemHandler implements IContainerInputHandler, IContainerToolti
if (contains(mousex, mousey)) {
if (NEIClientConfig.canPerformAction("delete") && NEIClientConfig.canPerformAction("item")) {
if (NEIClientConfig.canPerformAction("delete") && NEIClientConfig.canPerformAction("item")
|| NEIClientUtils.mc().playerController.isInCreativeMode()) {
if (button == 1) {
NEIClientUtils.decreaseSlotStack(-999);
} else {
@@ -101,7 +102,8 @@ public class HeldItemHandler implements IContainerInputHandler, IContainerToolti
if (contains(mousex, mousey)) {
currenttip.clear();
if (NEIClientConfig.canPerformAction("delete") && NEIClientConfig.canPerformAction("item")) {
if (NEIClientConfig.canPerformAction("delete") && NEIClientConfig.canPerformAction("item")
|| NEIClientUtils.mc().playerController.isInCreativeMode()) {
currenttip.add(EnumChatFormatting.RED + translate("itempanel.deleteItem"));
}
}
@@ -2,10 +2,11 @@ package codechicken.nei;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import net.minecraft.client.gui.inventory.GuiContainer;
@@ -90,6 +91,7 @@ public class ItemCraftablesPanel
private GuiContainer lastGuiContainer = null;
private ItemStackAmount lastPlayerInventory = null;
private long lastPlayerInventorySync = 0;
private int lastFavoritesCount = 0;
public ItemCraftablesPanel() {
this.grid = new ItemsGrid<>() {
@@ -106,28 +108,42 @@ public class ItemCraftablesPanel
public List<CraftablesGridSlot> getMask() {
if (this.gridMask == null) {
int maxSlotIndex = this.rows * this.columns;
final AtomicInteger slotIndex = new AtomicInteger(0);
final int maxSlotIndex = this.rows * this.columns;
final List<CraftablesGridSlot> gridMask = new ArrayList<>();
this.realItems.clear();
if (!ItemCraftablesPanel.this.availableRecipes.isEmpty()) {
ItemCraftablesPanel.this.availableRecipes.entrySet().stream()
.sorted(Map.Entry.comparingByKey(ItemSorter.instance)).forEach(entry -> {
this.realItems.add(entry.getKey());
gridMask.add(
new CraftablesGridSlot(
slotIndex.get(),
slotIndex.get(),
entry.getKey(),
entry.getValue()));
slotIndex.incrementAndGet();
});
final List<Map.Entry<ItemStack, RecipeId>> entries = ItemCraftablesPanel.this.availableRecipes
.entrySet().stream()
.sorted(
Map.Entry.comparingByKey(
Comparator.comparing(FavoriteRecipes::contains).reversed()
.thenComparing(ItemSorter.instance)))
.limit(maxSlotIndex).collect(Collectors.toList());
int slotIndex = 0;
int itemIndex = 0;
this.gridMask = gridMask.subList(0, Math.min(gridMask.size(), maxSlotIndex));
for (Map.Entry<ItemStack, RecipeId> entry : entries) {
if (!isInvalidSlot(slotIndex)) {
this.realItems.add(entry.getKey());
gridMask.add(
new CraftablesGridSlot(
slotIndex,
itemIndex++,
entry.getKey(),
entry.getValue()));
}
if (slotIndex++ >= maxSlotIndex) {
break;
}
}
this.gridMask = gridMask;
} else {
this.gridMask = Collections.emptyList();
}
ItemCraftablesPanel.this.updateLinePadding();
}
return this.gridMask;
@@ -192,11 +208,16 @@ public class ItemCraftablesPanel
this.lastPlayerInventorySync = System.currentTimeMillis();
if (firstGui != null && !ItemCraftablesPanel.guiBlacklist.contains(firstGui.getClass().getName())) {
final boolean showOnlyFavorites = NEIClientConfig
.getBooleanSetting("inventory.craftables.favoritesOnly");
final ItemStackAmount inv = AutoCraftingManager.getInventoryItems(firstGui);
if (this.lastGuiContainer != (this.lastGuiContainer = firstGui)
if (this.lastGuiContainer != firstGui
|| showOnlyFavorites && this.lastFavoritesCount != FavoriteRecipes.size()
|| !inv.equals(this.lastPlayerInventory)) {
this.lastPlayerInventory = inv;
this.lastGuiContainer = firstGui;
this.lastFavoritesCount = FavoriteRecipes.size();
this.availableRecipes = generateCraftables(firstGui);
this.grid.onGridChanged();
}
@@ -251,12 +272,14 @@ public class ItemCraftablesPanel
private Map<ItemStack, RecipeId> filterHandlerRecipes(IRecipeHandler handler, GuiContainer firstGui,
List<ItemStack> invStacks) {
final Map<ItemStack, RecipeId> availableRecipes = new HashMap<>();
final boolean showOnlyFavorites = NEIClientConfig.getBooleanSetting("inventory.craftables.favoritesOnly");
IntStream.range(0, handler.numRecipes()).parallel().forEach(recipeIndex -> {
if (existsIngredients(firstGui, handler.getIngredientStacks(recipeIndex), invStacks)) {
final Recipe recipe = Recipe.of(handler, recipeIndex);
if (!recipe.getResults().isEmpty()) {
if (!recipe.getResults().isEmpty()
&& (!showOnlyFavorites || FavoriteRecipes.getFavorite(recipe.getRecipeId()) != null)) {
synchronized (availableRecipes) {
availableRecipes.put(recipe.getResult(), recipe.getRecipeId());
}
@@ -40,9 +40,15 @@ public class ItemHistoryPanel extends AbstractSubpanel<ItemsGrid<ItemHistoryPane
if (this.gridMask == null) {
this.gridMask = new ArrayList<>();
for (int slotIndex = 0; slotIndex < Math.min(size(), this.rows * this.columns); slotIndex++) {
this.gridMask.add(new HistoryGridSlot(slotIndex, slotIndex, getItem(slotIndex)));
int itemIndex = 0;
for (int slotIndex = 0; slotIndex < this.rows * this.columns && itemIndex < size(); slotIndex++) {
if (!isInvalidSlot(slotIndex)) {
this.gridMask.add(new HistoryGridSlot(slotIndex, itemIndex, getItem(itemIndex)));
itemIndex++;
}
}
ItemHistoryPanel.this.updateLinePadding();
}
return this.gridMask;
+9 -1
View File
@@ -16,6 +16,7 @@ import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
@@ -308,7 +309,13 @@ public class ItemList {
action.run();
if (stack.hasTagCompound() && hashOld != stack.stackTagCompound.hashCode()) {
FMLLog.warning("NEI: Forced tag update with reason (" + reason + ") for " + stack);
FMLLog.warning(
"NEI: Forced tag update with reason (" + reason
+ ") for "
+ stack
+ "("
+ stack.getItem()
+ ")");
}
}
@@ -330,6 +337,7 @@ public class ItemList {
runChecked(stack, () -> item.getToolClasses(stack), "getToolClasses");
runChecked(stack, () -> item.getUnlocalizedNameInefficiently(stack), "getUnlocalizedNameInefficiently");
runChecked(stack, () -> item.hasEffect(stack), "hasEffect");
runChecked(stack, () -> item.getDigSpeed(stack, Blocks.stone, 0), "getDigSpeed");
/*
* unused... for now runChecked(stack, () -> GameRegistry.getFuelValue(stack), "getFuelValue");
+9 -5
View File
@@ -222,8 +222,7 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
}
@Override
public List<String> handleItemTooltip(GuiContainer gui, ItemStack itemstack, int mousex, int mousey,
List<String> currenttip) {
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> currenttip) {
if (!this.grid.forceExpand && !currenttip.isEmpty()) {
final ItemsPanelGridSlot hoverSlot = this.grid.getSlotMouseOver(mousex, mousey);
@@ -237,7 +236,7 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
}
}
return super.handleItemTooltip(gui, itemstack, mousex, mousey, currenttip);
return super.handleItemTooltip(itemstack, mousex, mousey, currenttip);
}
@Override
@@ -258,7 +257,7 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
final ItemsPanelGridSlot hoverSlot = this.grid.getSlotMouseOver(mousex, mousey);
if (!this.grid.forceExpand && hoverSlot != null && hoverSlot.groupIndex >= 0 && hoverSlot.groupSize > 1) {
@@ -269,7 +268,12 @@ public class ItemPanel extends PanelWidget<ItemsPanelGrid> {
NEIClientUtils.translate(message, hoverSlot.groupSize));
}
return hotkeys;
return super.handleHotkeys(mousex, mousey, hotkeys);
}
public boolean containsWithSubpanels(int px, int py) {
return contains(px, py) || NEIClientConfig.showHistoryPanelWidget() && this.historyPanel.contains(px, py)
|| NEIClientConfig.showCraftablesPanelWidget() && this.craftablesPanel.contains(px, py);
}
}
@@ -15,7 +15,6 @@ import net.minecraft.client.shader.Framebuffer;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.GuiInfo;
@@ -85,21 +84,6 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
} else {
this.framebuffer.framebufferClear();
}
// copy depth buffer from MC (fix Angelica)
OpenGlHelper.func_153171_g(GL30.GL_READ_FRAMEBUFFER, minecraft.getFramebuffer().framebufferObject);
OpenGlHelper.func_153171_g(GL30.GL_DRAW_FRAMEBUFFER, this.framebuffer.framebufferObject);
GL30.glBlitFramebuffer(
0,
0,
minecraft.displayWidth,
minecraft.displayHeight,
0,
0,
minecraft.displayWidth,
minecraft.displayHeight,
GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT,
GL11.GL_NEAREST);
}
public void renderCapturedScreen() {
@@ -281,8 +265,6 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
protected boolean[] invalidSlotMap;
protected Label messageLabel = new Label(getMessageOnEmpty(), true);
protected ScreenCapture screenCapture = null;
public ArrayList<ItemStack> getItems() {
@@ -360,9 +342,6 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
rows = height / SLOT_SIZE;
paddingLeft = (width % SLOT_SIZE) / 2;
messageLabel.x = marginLeft + width / 2;
messageLabel.y = marginTop + height / 2;
}
public void shiftPage(int shift) {
@@ -566,12 +545,6 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
afterDrawItems(mousex, mousey, mouseContext);
}
public void setVisible() {
if (getItems().isEmpty() && getMessageOnEmpty() != null) {
LayoutManager.addWidget(messageLabel);
}
}
public boolean contains(int px, int py) {
final Rectangle4i rect = new Rectangle4i(
marginLeft + paddingLeft,
@@ -586,7 +559,4 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
return !isInvalidSlot(columns * getRowIndex(py) + getColumnIndex(px));
}
public String getMessageOnEmpty() {
return null;
}
}
@@ -11,6 +11,7 @@ import java.util.Set;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.guihook.GuiContainerManager;
@@ -237,9 +238,18 @@ public class ItemsPanelGrid extends ItemsGrid<ItemsPanelGrid.ItemsPanelGridSlot,
Math.min((int) (color.getAlpha() + (255f / 5) * 2), 255));
}
@Override
public String getMessageOnEmpty() {
return ItemList.loadFinished ? null : NEIClientUtils.translate("itempanel.loading");
public void draw(int mousex, int mousey) {
if (ItemList.loadFinished) {
super.draw(mousex, mousey);
} else {
GuiDraw.drawStringC(
NEIClientUtils
.cropText(GuiDraw.fontRenderer, NEIClientUtils.translate("itempanel.loading"), width - 10),
marginLeft + width / 2,
marginTop + height / 2,
0xffffff,
true);
}
}
}
@@ -70,7 +70,7 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler {
}
public void setActiveStack(ItemStack activeStack) {
final ItemStack realStack = items.stream().filter(stack -> StackInfo.equalItemAndNBT(stack, activeStack, true))
final ItemStack realStack = items.stream().filter(stack -> NEIClientUtils.areStacksSameType(stack, activeStack))
.findFirst().orElse(null);
this.activeStackIndex = items.indexOf(realStack);
}
@@ -100,13 +100,15 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler {
fontRenderer.drawStringWithShadow(this.labelColor + this.label + ":", x, y, 0);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glPushMatrix();
RenderHelper.enableGUIStandardItemLighting();
GL11.glScaled(1, 1, 3);
GL11.glTranslatef(x, y + fontRenderer.FONT_HEIGHT + 2, 0);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
final int xTranslation = x;
final int yTranslation = y + fontRenderer.FONT_HEIGHT + 2;
final int zTranslation = GuiContainerManager.TOOLTIP_Z_OFFSET;
GL11.glTranslatef(xTranslation, yTranslation, zTranslation);
int indexShift = 0;
@@ -142,7 +144,7 @@ public class ItemsTooltipLineHandler implements ITooltipLineHandler {
});
}
GL11.glPopMatrix();
GL11.glTranslatef(-xTranslation, -yTranslation, -zTranslation);
GL11.glPopAttrib();
}
@@ -66,6 +66,7 @@ import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerObjectHandler;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.DebugHandlerWidget;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.RecipeCatalysts;
@@ -91,6 +92,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
public static SubsetWidget dropDown;
public static SearchField searchField;
public static ItemZoom itemZoom;
public static DebugHandlerWidget recipeHandlerWidget;
public static ButtonCycled options;
public static ButtonCycled bookmarksButton;
@@ -291,19 +293,6 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
}
@Override
public void postRenderTooltips(GuiContainer gui, int mousex, int mousey, List<String> tooltip) {
if (!isHidden() && isEnabled() && GuiContainerManager.shouldShowTooltip(gui)) {
final Widget focused = getWidgetUnderMouse(mousex, mousey);
if (focused != null) {
focused.postDrawTooltips(mousex, mousey, tooltip);
}
}
}
@Override
public List<String> handleTooltip(GuiContainer gui, int mousex, int mousey, List<String> currenttip) {
@@ -354,6 +343,10 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (!isHidden() && isEnabled() && GuiContainerManager.shouldShowTooltip(gui)) {
final Widget focused = getWidgetUnderMouse(mousex, mousey);
if (focused != null) {
currenttip = focused.handleItemTooltip(itemstack, mousex, mousey, currenttip);
}
if (focused instanceof IContainerTooltipHandler tip) {
currenttip = tip.handleItemTooltip(gui, itemstack, mousex, mousey, currenttip);
}
@@ -368,9 +361,14 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (!isHidden() && isEnabled() && GuiContainerManager.shouldShowTooltip(gui)) {
final Widget focused = getWidgetUnderMouse(mousex, mousey);
if (focused instanceof IContainerTooltipHandler tip) {
hotkeys = tip.handleHotkeys(gui, mousex, mousey, hotkeys);
if (focused != null) {
hotkeys = focused.handleHotkeys(mousex, mousey, hotkeys);
if (focused instanceof IContainerTooltipHandler tip) {
hotkeys = tip.handleHotkeys(gui, mousex, mousey, hotkeys);
}
}
}
return hotkeys;
@@ -408,6 +406,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
itemZoom = new ItemZoom();
recipeHandlerWidget = new DebugHandlerWidget();
dropDown = new SubsetWidget();
searchField = new SearchField("search");
API.addItemFilter(searchField);
@@ -783,9 +783,11 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
addWidget(itemZoom);
if (visiblity.showSubsetDropdown) {
// Bookmarks or Subset/dropdown
addWidget(dropDown);
}
addWidget(recipeHandlerWidget);
recipeHandlerWidget.setVisible();
}
public static LayoutStyle getLayoutStyle(int id) {
@@ -905,6 +907,9 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
final int ty2 = ty + 20 - h2 - te;
final int tx2 = 200 - w2 - te;
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_TEXTURE_2D);
changeTexture("textures/gui/widgets.png");
drawTexturedModalRect(x, y, tx1, ty1, w1, h1); // top left
drawTexturedModalRect(x, y2, tx1, ty2, w1, h2); // bottom left
@@ -917,6 +922,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
drawTexturedModalRect(x2, y, tx2, ty1, w2, h1); // top right
drawTexturedModalRect(x2, y2, tx2, ty2, w2, h2); // bottom right
if (!is2DTexture) GL11.glDisable(GL11.GL_TEXTURE_2D);
}
public static void drawItemPresenceOverlay(int slotX, int slotY, boolean isPresent, boolean slotHighlight) {
@@ -56,6 +56,7 @@ import codechicken.nei.config.OptionToggleButtonBoubs;
import codechicken.nei.config.OptionUtilities;
import codechicken.nei.config.preset.GuiPresetList;
import codechicken.nei.event.NEIConfigsLoadedEvent;
import codechicken.nei.recipe.DebugHandlerWidget;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.InformationHandler;
@@ -209,6 +210,10 @@ public class NEIClientConfig {
0,
OptionIntegerField.UNSIGNED_INT_MAX));
tag.getTag("inventory.bookmarks.showRecipeHandlerIcon").setComment("Show Recipe Handler Icon")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.bookmarks.showRecipeHandlerIcon", true));
tag.getTag("inventory.bookmarks.recipeChainDir").getIntValue(1);
API.addOption(new OptionCycled("inventory.bookmarks.recipeChainDir", 2, true));
@@ -220,17 +225,17 @@ public class NEIClientConfig {
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.bookmarks.bookmarkItemsWithRecipe", true));
tag.getTag("inventory.bookmarks.bookmarkRecipeWithCount").setComment("Bookmark recipe with count")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.bookmarks.bookmarkRecipeWithCount", true));
tag.getTag("inventory.guirecipe.jeiStyleTabs").setComment("Enable/disable JEI Style Tabs")
.getBooleanValue(true);
API.addOption(new OptionToggleButtonBoubs("inventory.guirecipe.jeiStyleTabs", true));
tag.getTag("inventory.guirecipe.jeiStyleRecipeCatalyst").setComment("Enable/disable JEI Style Recipe Catalysts")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.jeiStyleRecipeCatalyst", true));
tag.getTag("inventory.guirecipe.jeiStyleCycledIngredients").setComment("JEI styled cycled ingredients")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.jeiStyleCycledIngredients", true));
tag.getTag("inventory.guirecipe.jeiStyleRecipeCatalyst")
.setComment("JEI Style Recipe Catalysts (0 - none, 1 - grid, 2 - scroll)").getIntValue(1);
API.addOption(new OptionCycled("inventory.guirecipe.jeiStyleRecipeCatalyst", 3, true));
tag.getTag("inventory.guirecipe.cycledIngredientsTooltip").setComment("Show cycled ingredients tooltip")
.getBooleanValue(true);
@@ -248,6 +253,13 @@ public class NEIClientConfig {
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.slotHighlightPresent", true));
tag.getTag("inventory.guirecipe.infiniteScroll").setComment("Use Infinite Scroll for Handlers")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.infiniteScroll", true));
tag.getTag("inventory.guirecipe.maxHeight").setComment("Recipe GUI Max Height").getIntValue(370);
API.addOption(new OptionIntegerField("inventory.guirecipe.maxHeight", 166, 4000));
tag.getTag("inventory.guirecipe.shiftOverlayRecipe")
.setComment("Require holding shift to move items when overlaying recipe").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.shiftOverlayRecipe", true));
@@ -255,6 +267,10 @@ public class NEIClientConfig {
tag.getTag("inventory.guirecipe.profile").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.profile", true));
tag.getTag("inventory.guirecipe.handlerInfo").setComment("ADVANCED: Handler Info Widget")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.handlerInfo", true));
tag.getTag("inventory.subsets.enabled").setComment("Enable/disable Subsets Dropdown").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.subsets.enabled", true));
@@ -280,6 +296,10 @@ public class NEIClientConfig {
tag.getTag("inventory.craftables.useRows").setComment("Rows used in craftables areas").getIntValue(2);
API.addOption(new OptionIntegerField("inventory.craftables.useRows", 1, 5));
tag.getTag("inventory.craftables.favoritesOnly").setComment("Show Only Favorites Recipes")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.craftables.favoritesOnly", true));
tag.getTag("inventory.collapsibleItems.enabled").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.collapsibleItems.enabled", true) {
@@ -822,6 +842,7 @@ public class NEIClientConfig {
API.addKeyBind("world.creative", 0);
API.addHashBind("gui.copy_name", Keyboard.KEY_C + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.copy_oredict", Keyboard.KEY_D + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.copy_id", Keyboard.KEY_X + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.chat_link_item", Keyboard.KEY_L + NEIClientUtils.CTRL_HASH);
}
@@ -830,24 +851,27 @@ public class NEIClientConfig {
}
public static void loadWorld(String worldPath) {
final File specificDir = new File(CommonUtils.getMinecraftDir(), "saves/NEI/" + worldPath);
final boolean newWorld = !specificDir.exists();
unloadWorld();
setInternalEnabled(true);
if (!worldPath.equals(NEIClientConfig.worldPath)) {
if (!worldPath.equals(NEIClientConfig.worldPath) || newWorld) {
NEIClientConfig.worldPath = worldPath;
logger.debug("Loading " + (Minecraft.getMinecraft().isSingleplayer() ? "Local" : "Remote") + " World");
final File specificDir = new File(CommonUtils.getMinecraftDir(), "saves/NEI/" + worldPath);
final boolean newWorld = !specificDir.exists();
if (newWorld) {
specificDir.mkdirs();
}
world = new ConfigSet(new File(specificDir, "NEI.dat"), new ConfigFile(new File(specificDir, "NEI.cfg")));
if (newWorld && Minecraft.getMinecraft().isSingleplayer()) {
world.config.getTag("inventory.cheatmode")
.setIntValue(NEIClientUtils.mc().playerController.isInCreativeMode() ? 2 : 0);
}
bootNEI();
onWorldLoad(newWorld);
onWorldLoad();
}
}
@@ -855,7 +879,7 @@ public class NEIClientConfig {
return NEIClientConfig.worldPath;
}
private static void onWorldLoad(boolean newWorld) {
private static void onWorldLoad() {
world.config.setComment(
"World based configuration of NEI.\nMost of these options can be changed ingame.\nDeleting any element will restore it to it's default value");
@@ -863,12 +887,6 @@ public class NEIClientConfig {
creativeInv = new ItemStack[54];
LayoutManager.searchField.setText(getSearchExpression());
LayoutManager.quantity.setText(Integer.toString(getItemQuantity()));
if (newWorld && Minecraft.getMinecraft().isSingleplayer()) {
world.config.getTag("inventory.cheatmode")
.setIntValue(NEIClientUtils.mc().playerController.isInCreativeMode() ? 2 : 0);
}
NEIInfo.load(ClientUtils.getWorld());
}
@@ -882,6 +900,10 @@ public class NEIClientConfig {
}
public static void unloadWorld() {
if (world == null) {
return;
}
if (ItemPanels.bookmarkPanel != null) {
ItemPanels.bookmarkPanel.save();
}
@@ -889,10 +911,7 @@ public class NEIClientConfig {
SubsetWidget.saveHidden();
FavoriteRecipes.save();
CollapsibleItems.saveStates();
if (world != null) {
world.saveNBT();
}
world.saveNBT();
}
private static final Map<String, String> keySettings = new HashMap<>();
@@ -967,7 +986,6 @@ public class NEIClientConfig {
try {
IConfigureNEI config = (IConfigureNEI) clazz.getConstructor().newInstance();
config.loadConfig();
NEIModContainer.plugins.add(config);
logger.debug("Loaded {}", clazz.getName());
} catch (Throwable e) {
logger.error("Failed to Load {}", clazz.getName(), e);
@@ -989,6 +1007,7 @@ public class NEIClientConfig {
pluginNEIConfigLoaded = true;
MinecraftForge.EVENT_BUS.post(new NEIConfigsLoadedEvent());
DebugHandlerWidget.loadHandlerInfoPatch();
ItemList.loadItems.restart();
}
}.start();
@@ -1085,8 +1104,8 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.guirecipe.slotHighlightPresent");
}
public static boolean areJEIStyleRecipeCatalystsVisible() {
return getBooleanSetting("inventory.guirecipe.jeiStyleRecipeCatalyst");
public static int getJEIStyleRecipeCatalysts() {
return getIntSetting("inventory.guirecipe.jeiStyleRecipeCatalyst");
}
public static boolean useCreativeTabStyle() {
@@ -1105,10 +1124,6 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.optimize_gui_overlap_computation");
}
public static boolean useJEIStyledCycledIngredients() {
return getBooleanSetting("inventory.guirecipe.jeiStyleCycledIngredients");
}
public static boolean showCycledIngredientsTooltip() {
return getBooleanSetting("inventory.guirecipe.cycledIngredientsTooltip");
}
@@ -528,7 +528,9 @@ public class NEIClientUtils extends NEIServerUtils {
}
public static void drawRect(double left, double top, double width, double height, Color color) {
Tessellator tessellator = Tessellator.instance;
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
final boolean isBlend = GL11.glGetBoolean(GL11.GL_BLEND);
final Tessellator tessellator = Tessellator.instance;
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
@@ -540,8 +542,9 @@ public class NEIClientUtils extends NEIServerUtils {
tessellator.addVertex(left + width, top, 0.0D);
tessellator.addVertex(left, top, 0.0D);
tessellator.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
if (is2DTexture) GL11.glEnable(GL11.GL_TEXTURE_2D);
if (!isBlend) GL11.glDisable(GL11.GL_BLEND);
}
public static void drawNEIOverlayText(String text, Rectangle4i rect, float scale, int color, boolean shadow,
@@ -14,6 +14,7 @@ import net.minecraft.item.ItemStack;
import net.minecraftforge.client.ClientCommandHandler;
import codechicken.core.CommonUtils;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.api.API;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IInfiniteItemHandler;
@@ -156,20 +157,32 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
if (GuiInfo.hasCustomSlots(gui)) return false;
if (slotIndex >= 0 && NEIClientUtils.shiftKey()
&& NEIClientUtils.getHeldItem() != null
&& !slot.getHasStack()) {
ItemStack held = NEIClientUtils.getHeldItem();
manager.handleSlotClick(slot.slotNumber, button, 0);
if (slot.isItemValid(held) && !ItemInfo.fastTransferExemptions.contains(slot.getClass()))
fastTransferManager.performMassTransfer(gui, pickedUpFromSlot, slotIndex, held);
if (NEIClientUtils.shiftKey()) {
// fix small mouse movement while clicking causing slotIndex to be -999
if (slotIndex == -999) {
final Point mouse = GuiDraw.getMousePosition();
slot = gui.getSlotAtPosition(mouse.x, mouse.y);
return true;
}
if (slot != null) {
slotIndex = slot.slotNumber;
}
}
if (slotIndex == -999 && NEIClientUtils.shiftKey() && button == 0) {
fastTransferManager.throwAll(gui, pickedUpFromSlot);
return true;
if (slotIndex >= 0 && NEIClientUtils.getHeldItem() != null && !slot.getHasStack()) {
final ItemStack held = NEIClientUtils.getHeldItem();
manager.handleSlotClick(slot.slotNumber, button, 0);
if (slot.isItemValid(held) && !ItemInfo.fastTransferExemptions.contains(slot.getClass())) {
fastTransferManager.performMassTransfer(gui, pickedUpFromSlot, slotIndex, held);
}
return true;
}
if (slotIndex == -999 && button == 0) {
fastTransferManager.throwAll(gui, pickedUpFromSlot);
return true;
}
}
return false;
@@ -4,18 +4,14 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import net.minecraft.util.EnumChatFormatting;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import codechicken.core.CommonUtils;
import codechicken.core.launch.CodeChickenCorePlugin;
import codechicken.nei.api.IConfigureNEI;
import codechicken.nei.asm.NEICorePlugin;
import codechicken.nei.config.IMCHandler;
import codechicken.nei.recipe.GuiRecipeTab;
@@ -31,14 +27,14 @@ import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.VersionParser;
import cpw.mods.fml.common.versioning.VersionRange;
@SuppressWarnings("UnstableApiUsage")
public class NEIModContainer extends DummyModContainer {
public static LinkedList<IConfigureNEI> plugins = new LinkedList<>();
private static boolean gregTech5Loaded;
private static boolean gtnhLibLoaded;
@@ -46,7 +42,6 @@ public class NEIModContainer extends DummyModContainer {
public NEIModContainer() {
super(getModMetadata());
loadMetadata();
}
private static ModMetadata getModMetadata() {
@@ -85,30 +80,6 @@ public class NEIModContainer extends DummyModContainer {
private String description;
private void loadMetadata() {
description = super.getMetadata().description.replace("Supporters:", EnumChatFormatting.AQUA + "Supporters:");
}
@Override
public ModMetadata getMetadata() {
StringBuilder s_plugins = new StringBuilder();
if (plugins.size() == 0) {
s_plugins.append(EnumChatFormatting.RED).append("No installed plugins.");
} else {
s_plugins.append(EnumChatFormatting.GREEN).append("Installed plugins: ");
for (int i = 0; i < plugins.size(); i++) {
if (i > 0) s_plugins.append(", ");
IConfigureNEI plugin = plugins.get(i);
s_plugins.append(plugin.getName()).append(" ").append(plugin.getVersion());
}
s_plugins.append(".");
}
ModMetadata meta = super.getMetadata();
meta.description = description.replace("<plugins>", s_plugins.toString());
return meta;
}
@Override
public boolean registerBus(EventBus bus, LoadController controller) {
bus.register(this);
@@ -125,8 +96,9 @@ public class NEIModContainer extends DummyModContainer {
@Subscribe
public void init(FMLInitializationEvent event) {
if (CommonUtils.isClient()) ClientHandler.load();
if (CommonUtils.isClient()) {
ClientHandler.load();
}
ServerHandler.load();
}
@@ -147,6 +119,11 @@ public class NEIModContainer extends DummyModContainer {
}
}
@Subscribe
public void onServerAboutToStart(FMLServerAboutToStartEvent event) {
NEIServerConfig.resetFirstLoad();
}
@Subscribe
public void handleIMCMessages(FMLInterModComms.IMCEvent event) {
IMCHandler.processIMC(event.getMessages());
@@ -18,7 +18,6 @@ import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.permission.PermissionLevel;
@@ -37,21 +36,23 @@ import codechicken.lib.packet.PacketCustom;
public class NEIServerConfig {
private static MinecraftServer server;
private static boolean firstLoad;
public static Logger logger = LogManager.getLogger("NotEnoughItems");
public static File saveDir;
public static ConfigFile serverConfig;
public static Map<Integer, NBTTagCompound> dimTags = new HashMap<>();
public static HashMap<String, PlayerSave> playerSaves = new HashMap<>();
public static ItemStackMap<Set<String>> bannedItems = new ItemStackMap<>();
private static boolean doesPermAPIExist = false;
public static void resetFirstLoad() {
firstLoad = true;
}
public static void load(World world) {
if (MinecraftServer.getServer() != server) {
if (firstLoad) {
firstLoad = false;
logger.debug("Loading NEI Server");
server = MinecraftServer.getServer();
saveDir = new File(DimensionManager.getCurrentSaveRootDirectory(), "NEI");
dimTags.clear();
@@ -51,15 +51,18 @@ import cpw.mods.fml.relauncher.ReflectionHelper;
public class NEIServerUtils {
private static Class<?> gtMetaBaseItem;
private static class GTMetaBaseItemHolder {
static {
try {
final ClassLoader loader = NEIServerUtils.class.getClassLoader();
NEIServerUtils.gtMetaBaseItem = ReflectionHelper
.getClass(loader, "gregtech.api.items.MetaBaseItem", "gregtech.api.items.GT_MetaBase_Item");
} catch (Exception ignored) {
/* Do nothing */
private static final Class<?> gtMetaBaseItem = loadMetaBaseItem();
private static Class<?> loadMetaBaseItem() {
try {
final ClassLoader loader = NEIServerUtils.class.getClassLoader();
return ReflectionHelper
.getClass(loader, "gregtech.api.items.MetaBaseItem", "gregtech.api.items.GT_MetaBase_Item");
} catch (Exception ignored) {
return null;
}
}
}
@@ -231,7 +234,8 @@ public class NEIServerUtils {
* @return
*/
public static boolean isItemTool(ItemStack stack) {
return NEIServerUtils.gtMetaBaseItem != null && NEIServerUtils.gtMetaBaseItem.isInstance(stack.getItem());
return GTMetaBaseItemHolder.gtMetaBaseItem != null
&& GTMetaBaseItemHolder.gtMetaBaseItem.isInstance(stack.getItem());
}
/**
+3 -12
View File
@@ -11,14 +11,12 @@ import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ? extends ItemsGrid.MouseContext>>
extends Widget implements IContainerTooltipHandler {
extends Widget {
protected static final int PADDING = 2;
@@ -147,7 +145,6 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
LayoutManager.addWidget(pagePrev);
LayoutManager.addWidget(pageNext);
LayoutManager.addWidget(pageLabel);
this.grid.setVisible();
}
}
@@ -285,13 +282,7 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
if (NEIController.manager.window instanceof GuiRecipe || NEIClientUtils.shiftKey()
|| !NEIClientConfig.canCheatItem(hoverSlot.getItemStack())) {
if (button == 0) {
GuiCraftingRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
} else if (button == 1) {
GuiUsageRecipe.openRecipeGui("item", hoverSlot.getItemStack().copy());
}
ShortcutInputHandler.handleMouseClick(hoverSlot.getItemStack());
} else {
NEIClientUtils.cheatItem(getDraggedStackWithQuantity(hoverSlot.getItemStack()), button, -1);
}
@@ -114,16 +114,25 @@ public class PositionedStack {
return filteredItems.isEmpty() ? items : filteredItems;
}
public boolean setPermutationToRender(ItemStack ingredient) {
public int getPermutationIndex(ItemStack stack) {
for (int index = 0; index < this.items.length; index++) {
if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(this.items[index], ingredient)) {
setPermutationToRender(index);
return true;
if (NEIServerUtils.areStacksSameType(items[index], stack)) {
return index;
}
}
return false;
return -1;
}
public boolean setPermutationToRender(ItemStack ingredient) {
final int stackIndex = getPermutationIndex(ingredient);
if (stackIndex >= 0) {
setPermutationToRender(stackIndex);
}
return stackIndex >= 0;
}
public void setPermutationToRender(int index) {
@@ -136,6 +145,10 @@ public class PositionedStack {
}
}
public boolean contains(int mx, int my) {
return mx >= this.relx - 1 && mx < this.relx + 17 && my >= this.rely - 1 && my < this.rely + 17;
}
public boolean contains(ItemStack ingredient) {
for (ItemStack item : items) if (NEIServerUtils.areStacksSameTypeCrafting(item, ingredient)) return true;
@@ -21,10 +21,8 @@ import cpw.mods.fml.common.gameevent.TickEvent.Phase;
public class ServerHandler {
private static ServerHandler instance;
public static void load() {
instance = new ServerHandler();
ServerHandler instance = new ServerHandler();
PacketCustom.assignHandler(NEICPH.channel, new NEISPH());
FMLCommonHandler.instance().bus().register(instance);
@@ -18,7 +18,6 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
@@ -40,7 +39,6 @@ import codechicken.nei.api.API;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.ICraftingHandler;
@@ -49,7 +47,7 @@ import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
import codechicken.nei.util.NEIMouseUtils;
public class SubsetWidget extends Button implements ItemFilterProvider, IContainerTooltipHandler {
public class SubsetWidget extends Button implements ItemFilterProvider {
protected static final int SLOT_HEIGHT = 18;
protected static final int MARGIN = 2;
@@ -939,7 +937,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, IContain
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
if (SubsetWidget.hoverStack != null) {
+1 -1
View File
@@ -89,7 +89,7 @@ public abstract class TextField extends Widget {
onTextChange(oldText);
}
return handled;
return handled || keyID == Keyboard.KEY_SPACE;
}
public abstract void onTextChange(String oldText);
+14 -2
View File
@@ -1,6 +1,7 @@
package codechicken.nei;
import java.util.List;
import java.util.Map;
import net.minecraft.item.ItemStack;
@@ -14,8 +15,6 @@ public abstract class Widget {
public void postDraw(int mx, int my) {}
public void postDrawTooltips(int mx, int my, List<String> tooltip) {}
public boolean handleClick(int mx, int my, int button) {
return true;
}
@@ -38,6 +37,10 @@ public abstract class Widget {
return false;
}
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
return hotkeys;
}
public void update() {}
public Rectangle4i bounds() {
@@ -58,6 +61,14 @@ public abstract class Widget {
return tooltip;
}
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> tooltip) {
return tooltip;
}
public boolean isFocused() {
return false;
}
public void loseFocus() {}
public void gainFocus() {}
@@ -67,4 +78,5 @@ public abstract class Widget {
public int z;
public int w;
public int h;
}
@@ -0,0 +1,254 @@
package codechicken.nei;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import net.minecraft.item.ItemStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
public class WidgetContainer extends Widget {
protected final List<Widget> widgets = new ArrayList<>();
protected boolean isFocused = false;
public void addWidget(Widget widget) {
this.widgets.add(widget);
}
public void setWidgets(List<Widget> widgets) {
final boolean isFocused = this.isFocused;
clear();
loseFocus();
for (Widget widget : widgets) {
addWidget(widget);
}
this.isFocused = isFocused;
}
public void clear() {
this.widgets.clear();
this.isFocused = false;
}
public List<Widget> getWidgets() {
return Collections.unmodifiableList(this.widgets);
}
public boolean removeIf(Predicate<Widget> filter) {
return this.widgets.removeIf(filter);
}
@Override
public void draw(int mousex, int mousey) {
drawWidgets(mousex, mousey);
}
protected void drawWidgets(int mousex, int mousey) {
final Rectangle4i bounds = bounds();
for (Widget widget : this.widgets) {
if (widget.bounds().intersects(bounds)) {
widget.draw(mousex, mousey);
}
}
}
@Override
public void update() {
for (Widget widget : this.widgets) {
widget.update();
}
Collections.sort(this.widgets, Comparator.comparingInt((Widget widget) -> widget.z));
}
public Widget getWidgetUnderMouse(int mousex, int mousey) {
if (!bounds().contains(mousex, mousey)) {
return null;
}
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (widget.contains(mousex, mousey)) {
return widget;
}
}
return null;
}
@Override
public boolean onMouseWheel(int scroll, int mousex, int mousey) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
return widget != null && widget.onMouseWheel(scroll, mousex, mousey);
}
@Override
public boolean handleClick(int mousex, int mousey, int button) {
if (contains(mousex, mousey)) {
gainFocus();
}
final Widget widget = getWidgetUnderMouse(mousex, mousey);
return widget != null && widget.handleClick(mousex, mousey, button);
}
@Override
public boolean handleClickExt(int mousex, int mousey, int button) {
loseFocus();
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (!widget.contains(mousex, mousey) && widget.handleClickExt(mousex, mousey, button)) {
return true;
}
}
return false;
}
@Override
public void mouseDragged(int mousex, int mousey, int button, long heldTime) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.mouseDragged(mousex, mousey, button, heldTime);
}
}
@Override
public void mouseUp(int mousex, int mousey, int button) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.mouseUp(mousex, mousey, button);
}
}
@Override
public boolean handleKeyPress(int keyCode, char keyChar) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (widget.handleKeyPress(keyCode, keyChar)) {
return true;
}
}
return false;
}
@Override
public void lastKeyTyped(int keyID, char keyChar) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.lastKeyTyped(keyID, keyChar);
}
}
@Override
public boolean isFocused() {
return this.isFocused;
}
@Override
public void loseFocus() {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
if (widget.isFocused()) {
widget.loseFocus();
}
}
this.isFocused = false;
}
@Override
public void gainFocus() {
final Point mouse = GuiDraw.getMousePosition();
final Widget widget = getWidgetUnderMouse(mouse.x, mouse.y);
if (widget != null) {
if (!widget.isFocused()) {
loseFocus();
widget.gainFocus();
}
} else {
loseFocus();
}
this.isFocused = true;
}
@Override
public ItemStack getStackMouseOver(int mousex, int mousey) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
if (widget != null) {
return widget.getStackMouseOver(mousex, mousey);
}
return null;
}
@Override
public void postDraw(int mousex, int mousey) {
for (Widget widget : this.widgets) {
widget.postDraw(mousex, mousey);
}
}
@Override
public void onGuiClick(int mousex, int mousey) {
for (int index = this.widgets.size() - 1; index >= 0; index--) {
final Widget widget = this.widgets.get(index);
widget.onGuiClick(mousex, mousey);
}
}
@Override
public List<String> handleTooltip(int mousex, int mousey, List<String> tooltip) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
if (widget != null) {
return widget.handleTooltip(mousex, mousey, tooltip);
}
return tooltip;
}
@Override
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
final Widget widget = getWidgetUnderMouse(mousex, mousey);
if (widget != null) {
return widget.handleHotkeys(mousex, mousey, hotkeys);
}
return hotkeys;
}
}
@@ -16,7 +16,6 @@ import codechicken.nei.NEIDummySlotHandler;
import codechicken.nei.NEIPotionGuiHandler;
import codechicken.nei.recipe.CheatItemHandler;
import codechicken.nei.recipe.FillFluidContainerHandler;
import codechicken.nei.recipe.GuiRecipeCatalyst;
import codechicken.nei.recipe.SearchInputDropHandler;
public class GuiInfo {
@@ -31,7 +30,6 @@ public class GuiInfo {
API.registerNEIGuiHandler(new NEICreativeGuiHandler());
API.registerNEIGuiHandler(new NEIChestGuiHandler());
API.registerNEIGuiHandler(new NEIDummySlotHandler());
API.registerNEIGuiHandler(new GuiRecipeCatalyst(null));
API.registerNEIGuiHandler(new SearchInputDropHandler());
API.registerNEIGuiHandler(new FillFluidContainerHandler());
API.registerNEIGuiHandler(new CheatItemHandler());
@@ -15,7 +15,7 @@ public interface IBookmarkContainerHandler {
for (int i = 0; i < slots.size() - 4 * 9; i++) {
if (slots.get(i).getHasStack()) {
stacks.add(slots.get(i).getStack());
stacks.add(slots.get(i).getStack().copy());
}
}
@@ -18,6 +18,10 @@ public interface IStackStringifyHandler {
return null;
}
default ItemStack normalizeRecipeQueryStack(ItemStack stack) {
return null;
}
default void pauseItemDamageSound(boolean pause) {}
}
+19 -11
View File
@@ -421,30 +421,38 @@ public class ItemInfo {
Block mouseoverBlock = world.getBlock(x, y, z);
ArrayList<ItemStack> items = new ArrayList<>();
ArrayList<IHighlightHandler> handlers = new ArrayList<>();
if (highlightIdentifiers.containsKey(null)) handlers.addAll(highlightIdentifiers.get(null));
if (highlightIdentifiers.containsKey(mouseoverBlock)) handlers.addAll(highlightIdentifiers.get(mouseoverBlock));
for (IHighlightHandler ident : handlers) {
ItemStack item = ident.identifyHighlight(world, player, hit);
final ItemStack item = ident.identifyHighlight(world, player, hit);
if (item != null) items.add(item);
}
if (items.size() > 0) return items;
if (!items.isEmpty()) return items;
ItemStack pick = mouseoverBlock.getPickBlock(hit, world, x, y, z, player);
if (pick != null) items.add(pick);
try {
final ItemStack pick = mouseoverBlock.getPickBlock(hit, world, x, y, z, player);
if (pick != null) items.add(pick);
} catch (Exception ignored) {}
if (!items.isEmpty()) return items;
if (mouseoverBlock instanceof IShearable shearable) {
if (shearable.isShearable(new ItemStack(Items.shears), world, x, y, z)) {
items.addAll(shearable.onSheared(new ItemStack(Items.shears), world, x, y, z, 0));
}
}
if (!items.isEmpty()) return items;
try {
items.addAll(mouseoverBlock.getDrops(world, x, y, z, world.getBlockMetadata(x, y, z), 0));
} catch (Exception ignored) {}
if (mouseoverBlock instanceof IShearable) {
IShearable shearable = (IShearable) mouseoverBlock;
if (shearable.isShearable(new ItemStack(Items.shears), world, x, y, z))
items.addAll(shearable.onSheared(new ItemStack(Items.shears), world, x, y, z, 0));
}
if (items.size() == 0) items.add(0, new ItemStack(mouseoverBlock, 1, world.getBlockMetadata(x, y, z)));
if (items.isEmpty()) items.add(new ItemStack(mouseoverBlock, 1, world.getBlockMetadata(x, y, z)));
return items;
}
@@ -27,6 +27,7 @@ import codechicken.nei.SearchField;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
@@ -42,6 +43,31 @@ import codechicken.nei.util.NEIMouseUtils;
public abstract class ShortcutInputHandler {
private static class HotkeysCache {
public int mousex;
public int mousey;
public ItemStack stack;
public int groupId;
public Map<String, String> hotkeys = new HashMap<>();
public boolean matches(int mousex, int mousey, ItemStack stack, int groupId) {
return Math.abs(this.mousex - mousex) < 16 && Math.abs(this.mousey - mousey) < 16
&& (this.stack == null ? stack == null && this.groupId == groupId
: stack != null && NEIClientUtils.areStacksSameTypeWithNBT(stack, this.stack));
}
public void update(int mousex, int mousey, ItemStack stack, int groupId, Map<String, String> hotkeys) {
this.mousex = mousex;
this.mousey = mousey;
this.stack = stack != null ? stack.copy() : null;
this.groupId = groupId;
this.hotkeys = hotkeys;
}
}
private static HotkeysCache hotkeysCache = new HotkeysCache();
public static boolean handleKeyEvent(ItemStack stackover) {
if (!NEIClientConfig.isLoaded()) {
@@ -98,6 +124,9 @@ public abstract class ShortcutInputHandler {
if (NEIClientConfig.isKeyHashDown("gui.copy_name")) {
return copyItemStackName(stackover);
}
if (NEIClientConfig.isKeyHashDown("gui.copy_id")) {
return copyItemStackID(stackover);
}
if (NEIClientConfig.isKeyHashDown("gui.copy_oredict")) {
return copyItemStackOreDictionary(stackover);
@@ -145,9 +174,9 @@ public abstract class ShortcutInputHandler {
final int button = Mouse.getEventButton();
if (button == 0) {
return GuiCraftingRecipe.openRecipeGui("item", stackover);
return GuiCraftingRecipe.openRecipeGui("item", stackover.copy());
} else if (button == 1) {
return GuiUsageRecipe.openRecipeGui("item", stackover);
return GuiUsageRecipe.openRecipeGui("item", stackover.copy());
}
}
@@ -159,6 +188,14 @@ public abstract class ShortcutInputHandler {
return true;
}
private static boolean copyItemStackID(ItemStack stackover) {
if (stackover == null || stackover.getItem() == null) return false;
GuiScreen.setClipboardString(
stackover.getItem().delegate.name()
+ (stackover.getItemDamage() != 0 ? "/" + stackover.getItemDamage() : ""));
return true;
}
private static boolean sendItemStackChatLink(ItemStack stackover) {
if (stackover == null) return false;
@@ -197,7 +234,7 @@ public abstract class ShortcutInputHandler {
if (recipe != null) {
math = RecipeChainMath.of(recipe, 1);
}
} else if (slot.getRecipeId() != null && !slot.isIngredient()) {
} else if (slot.getRecipeId() != null && slot.getType() == BookmarkItemType.RESULT) {
if (slot.getGroup().crafting == null) {
final Recipe recipe = Recipe.of(slot.getRecipeId());
@@ -276,11 +313,14 @@ public abstract class ShortcutInputHandler {
private static boolean saveRecipeInBookmark(ItemStack stackover, boolean saveIngredients, boolean saveStackSize) {
final Point mousePos = GuiDraw.getMousePosition();
// If no slot was removed from the bookmark panel on click:
if (!ItemPanels.bookmarkPanel.removeSlot(mousePos.x, mousePos.y, saveIngredients)) {
final Recipe recipe = getFocusedRecipe(stackover, mousePos.x, mousePos.y, saveIngredients);
// --- Case 1: saving a recipe (with ingredients) ---
if (recipe != null && saveIngredients) {
// If the recipe is not already bookmarked, add it
if (!ItemPanels.bookmarkPanel.removeRecipe(recipe.getRecipeId(), BookmarkGrid.DEFAULT_GROUP_ID)) {
final Recipe singleRecipe = Recipe.of(
Arrays.asList(recipe.getResult(stackover)),
@@ -288,27 +328,38 @@ public abstract class ShortcutInputHandler {
recipe.getIngredients());
singleRecipe.setCustomRecipeId(recipe.getRecipeId());
ItemPanels.bookmarkPanel
.addRecipe(singleRecipe, saveStackSize ? 1 : 0, BookmarkGrid.DEFAULT_GROUP_ID);
ItemPanels.bookmarkPanel.addRecipe(
singleRecipe,
// Determine if stack size should be saved
saveStackSize
|| NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkRecipeWithCount")
? 1
: 0,
BookmarkGrid.DEFAULT_GROUP_ID);
}
// --- Case 2: saving an item only ---
} else {
final RecipeId recipeId = recipe != null ? recipe.getRecipeId() : null;
// Determine if the item is associated with a recipe and should be saved with it
final boolean existsRecipe = recipeId != null
&& ItemPanels.bookmarkPanel.existsRecipe(recipeId, BookmarkGrid.DEFAULT_GROUP_ID)
|| NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkItemsWithRecipe");
// If the item was not removed from the bookmarks, add it
if (!ItemPanels.bookmarkPanel
.removeItem(stackover, existsRecipe ? recipeId : null, BookmarkGrid.DEFAULT_GROUP_ID)) {
// Determine whether to preserve the item count
saveStackSize = saveStackSize || saveIngredients
|| ItemPanels.bookmarkPanel.existsRecipe(recipeId, BookmarkGrid.DEFAULT_GROUP_ID);
if (!saveStackSize) {
stackover = StackInfo.withAmount(stackover, 0);
} else if (ItemPanels.itemPanel.contains(mousePos.x, mousePos.y)
|| ItemPanels.itemPanel.historyPanel.contains(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
} else if (ItemPanels.itemPanel.containsWithSubpanels(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
ItemPanels.bookmarkPanel
.addItem(stackover, existsRecipe ? recipeId : null, BookmarkGrid.DEFAULT_GROUP_ID);
@@ -380,8 +431,14 @@ public abstract class ShortcutInputHandler {
return ItemPanels.bookmarkPanel.pullBookmarkItems(math, shift);
}
public static Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, ItemStack stack) {
public static Map<String, String> handleHotkeys(int mousex, int mousey, ItemStack stack) {
final int groupId = ItemPanels.bookmarkPanel.getHoveredGroupId(true);
if (hotkeysCache.matches(mousex, mousey, stack, groupId)) {
return hotkeysCache.hotkeys;
}
final GuiContainer gui = NEIClientUtils.getGuiContainer();
final Map<String, String> hotkeys = new HashMap<>();
if (groupId != -1) {
@@ -408,9 +465,13 @@ public abstract class ShortcutInputHandler {
NEIClientConfig.getKeyName("gui.craft_items", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.craft_all"));
}
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
return hotkeys;
}
if (stack == null) {
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
return hotkeys;
}
@@ -424,7 +485,7 @@ public abstract class ShortcutInputHandler {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
} else if (slot.getRecipeId() == null) {
} else if (slot.getRecipeId() == null || slot.getType() == BookmarkItemType.ITEM) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_item"));
@@ -439,7 +500,7 @@ public abstract class ShortcutInputHandler {
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.remove_recipe"));
if (slot.isIngredient()) {
if (slot.getType() == BookmarkItemType.INGREDIENT) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_item"));
@@ -452,7 +513,8 @@ public abstract class ShortcutInputHandler {
if (ItemPanels.bookmarkPanel.getGrid().createChainItems(groupId).values().stream()
.noneMatch(
m -> !m.isIngredient && !m.equals(item) && item.equalsRecipe(m))) {
m -> m.type == BookmarkItemType.RESULT && !m.equals(item)
&& item.equalsRecipe(m))) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark"),
NEIClientUtils.translate("bookmark.remove_recipe"));
@@ -511,6 +573,7 @@ public abstract class ShortcutInputHandler {
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_name"), NEIClientUtils.translate("itempanel.copy_name"));
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_oredict"), NEIClientUtils.translate("itempanel.copy_oredict"));
hotkeys.put(NEIClientConfig.getKeyName("gui.copy_id"), NEIClientUtils.translate("itempanel.copy_id"));
hotkeys.put(
NEIClientConfig.getKeyName("gui.chat_link_item"),
NEIClientUtils.translate("itempanel.chat_link_item"));
@@ -570,6 +633,8 @@ public abstract class ShortcutInputHandler {
}
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
return hotkeys;
}
@@ -599,7 +664,7 @@ public abstract class ShortcutInputHandler {
BookmarksGridSlot slot) {
if (slot != null) {
return slot.isIngredient() ? null : slot.getRecipeId();
return slot.getType() == BookmarkItemType.INGREDIENT ? null : slot.getRecipeId();
}
ItemsGridSlot itemSlot = ItemPanels.itemPanel.getSlotMouseOver(mousex, mousey);
@@ -30,6 +30,7 @@ import codechicken.nei.ItemsGrid.MouseContext;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
@@ -367,19 +368,26 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
for (BookmarkItem item : this.bookmarkItems) {
if (item.groupId == groupId && item.recipeId != null) {
if (item.recipeId == null && item.type != BookmarkItemType.ITEM) {
item.type = BookmarkItemType.ITEM;
} else if (item.groupId == groupId && item.recipeId != null && item.type != BookmarkItemType.ITEM) {
recipeState.put(
item.recipeId,
recipeState.getOrDefault(item.recipeId, 0) | (item.isIngredient ? 1 : 2));
recipeState.getOrDefault(item.recipeId, 0)
| (item.type == BookmarkItemType.INGREDIENT ? 1 : 2));
}
}
for (BookmarkItem item : this.bookmarkItems) {
if (item.groupId == groupId && item.isIngredient
&& (item.recipeId == null || recipeState.getOrDefault(item.recipeId, 1) == 1)) {
if (item.groupId == groupId && item.type != BookmarkItemType.ITEM
&& recipeState.getOrDefault(item.recipeId, 0) != 3) {
if (item.type == BookmarkItemType.INGREDIENT) {
item.recipeId = null;
}
recipeState.remove(item.recipeId);
item.isIngredient = false;
item.recipeId = null;
item.type = BookmarkItemType.ITEM;
}
}
@@ -405,7 +413,8 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (int index = itemIndex; index < size; index++) {
if (item.equalsRecipe(this.bookmarkItems.get(index))) {
sortingRank.put(index, this.bookmarkItems.get(index).isIngredient ? 1 : -1);
sortingRank
.put(index, this.bookmarkItems.get(index).type == BookmarkItemType.INGREDIENT ? 1 : -1);
items.add(index);
}
}
@@ -632,6 +641,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
if (group.crafting == null) {
for (BookmarkItem item : chainItems) {
item.type = BookmarkItemType.ITEM;
item.recipeId = null;
}
}
@@ -820,7 +830,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (int itemIndex = 0; itemIndex < this.bookmarkItems.size(); itemIndex++) {
final BookmarkItem item = this.bookmarkItems.get(itemIndex);
if (item.groupId == groupId && item.isIngredient == ingredient
if (item.groupId == groupId && ingredient == (item.type == BookmarkItemType.INGREDIENT)
&& (recipeId == item.recipeId || recipeId != null && recipeId.equals(item.recipeId))
&& StackInfo.equalItemAndNBT(stackA, item.itemStack, true)) {
return itemIndex;
@@ -876,7 +886,12 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
for (ItemStack stack : ItemStackAmount.of(results).values()) {
long factor = StackInfo.getAmount(stack);
this.addItem(
BookmarkItem.of(groupId, StackInfo.withAmount(stack, factor * multiplier), factor, recipeId, false),
BookmarkItem.of(
groupId,
StackInfo.withAmount(stack, factor * multiplier),
factor,
recipeId,
BookmarkItemType.RESULT),
true);
}
@@ -888,7 +903,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
StackInfo.withAmount(stack, factor * multiplier),
factor,
recipeId,
true,
BookmarkItemType.INGREDIENT,
BookmarkItem.generatePermutations(stack, recipe)),
true);
}
@@ -901,12 +916,12 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
return;
}
if (!removeFullRecipe && item.recipeId != null && !item.isIngredient) {
if (!removeFullRecipe && item.recipeId != null && item.type == BookmarkItemType.RESULT) {
removeFullRecipe = this.bookmarkItems.stream()
.noneMatch(m -> !m.isIngredient && !m.equals(item) && item.equalsRecipe(m));
.noneMatch(m -> m.type == BookmarkItemType.RESULT && !m.equals(item) && item.equalsRecipe(m));
}
if (item.recipeId != null && removeFullRecipe) {
if (item.recipeId != null && item.type != BookmarkItemType.ITEM && removeFullRecipe) {
removeRecipe(item.recipeId, item.groupId);
} else if (itemIndex >= 0) {
this.bookmarkItems.remove(itemIndex);
@@ -925,7 +940,8 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
public boolean existsRecipe(RecipeId recipeId, int groupId) {
return this.bookmarkItems.stream().anyMatch(item -> item.equalsRecipe(recipeId, groupId));
return this.bookmarkItems.stream()
.anyMatch(item -> item.type != BookmarkItemType.ITEM && item.equalsRecipe(recipeId, groupId));
}
public RecipeId getRecipeId(int itemIndex) {
@@ -1028,8 +1044,14 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
}
if (bookmarkItem != null && (group.crafting != null && group.viewMode == BookmarkViewMode.DEFAULT
|| group.viewMode == BookmarkViewMode.TODO_LIST && !sortableItem.bookmarkItem.isIngredient)) {
while (sortIndex > 0 && bookmarkItem.equalsRecipe(getCalculatedItem(sortedIndexes.get(sortIndex - 1)))) {
|| group.viewMode == BookmarkViewMode.TODO_LIST
&& sortableItem.bookmarkItem.type == BookmarkItemType.RESULT)) {
BookmarkItem prevBookmarkItem = sortIndex > 1 ? getCalculatedItem(sortedIndexes.get(sortIndex - 1)) : null;
while (sortIndex > 0 && prevBookmarkItem != null
&& prevBookmarkItem.type != BookmarkItemType.ITEM
&& bookmarkItem.equalsRecipe(prevBookmarkItem)) {
prevBookmarkItem = sortIndex > 1 ? getCalculatedItem(sortedIndexes.get(sortIndex - 1)) : null;
sortIndex--;
}
@@ -1058,7 +1080,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
if (nextSortIndex < sortedIndexes.size()) {
final int nextItemIndex = sortedIndexes.get(nextSortIndex);
if (group.viewMode == BookmarkViewMode.TODO_LIST && !target.isIngredient
if (group.viewMode == BookmarkViewMode.TODO_LIST && target.type == BookmarkItemType.RESULT
&& target.equalsRecipe(getCalculatedItem(nextItemIndex))) {
return -1;
}
@@ -1149,7 +1171,7 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
if (group.collapsed) {
shiftGroupAmount(targetItem.groupId, shift);
} else if (targetItem.recipeId != null) {
} else if (targetItem.recipeId != null && targetItem.type != BookmarkItemType.ITEM) {
final RecipeId recipeId = this.gridGenerator.itemToRecipe
.getOrDefault(targetItemIndex, targetItem.recipeId);
final boolean recipeInMiddle = group.crafting != null && group.crafting.recipeInMiddle.contains(recipeId);
@@ -11,6 +11,7 @@ import java.util.stream.Collectors;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemSorter;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.RecipeChainDetails.BookmarkChainItem;
import codechicken.nei.bookmark.RecipeChainDetails.CalculatedType;
import codechicken.nei.recipe.Recipe.RecipeId;
@@ -165,7 +166,7 @@ public class BookmarkGridGenerator {
break;
}
if (!bookmarkItem.isIngredient
if (bookmarkItem.type != BookmarkItemType.INGREDIENT
&& (group.crafting == null || group.crafting.calculatedItems.containsKey(itemIndex))) {
results.add(itemIndex);
}
@@ -193,7 +194,7 @@ public class BookmarkGridGenerator {
bookmarkItem.itemStack,
1,
bookmarkItem.recipeId,
isIngredient,
isIngredient ? BookmarkItemType.INGREDIENT : BookmarkItemType.RESULT,
Collections.emptyMap());
if ((absoluteSlotIndex = nextSlotIndex(
@@ -238,17 +239,21 @@ public class BookmarkGridGenerator {
return index;
} else if (isFirstColumn && (meta.recipeId == null || previousMeta == null
|| previousMeta.groupId != meta.groupId
|| meta.type == BookmarkItemType.ITEM
|| !meta.recipeId.equals(previousMeta.recipeId)
|| index + 1 < maxIndex && this.grid.isInvalidSlot((index + 1) % maxIndex))) {
// In first column must be an item without recipe, a recipe result, or an ingredient
// if the second column is occupied
return index;
} else
if (!isFirstColumn && meta.recipeId != null && meta.recipeId.equals(previousMeta.recipeId)) {
return index;
} else {
index++;
}
if (!isFirstColumn && meta.type != BookmarkItemType.ITEM
&& previousMeta.type != BookmarkItemType.ITEM
&& meta.recipeId != null
&& meta.recipeId.equals(previousMeta.recipeId)) {
return index;
} else {
index++;
}
}
@@ -17,6 +17,21 @@ import codechicken.nei.recipe.StackInfo;
public class BookmarkItem {
public enum BookmarkItemType {
INGREDIENT,
RESULT,
ITEM;
public static BookmarkItemType fromInt(int type) {
return type == 0 ? ITEM : type == 1 ? RESULT : INGREDIENT;
}
public int toInt() {
return this == ITEM ? 0 : this == RESULT ? 1 : 2;
}
}
private static Map<ItemStack, String> fuzzyPermutations = new HashMap<>();
public int groupId;
@@ -28,10 +43,10 @@ public class BookmarkItem {
public long factor;
public RecipeId recipeId;
public boolean isIngredient = false;
public BookmarkItemType type = BookmarkItemType.ITEM;
protected BookmarkItem(int groupId, long amount, int fluidCellAmount, ItemStack itemStack,
Map<String, ItemStack> permutations, long factor, RecipeId recipeId, boolean isIngredient) {
Map<String, ItemStack> permutations, long factor, RecipeId recipeId, BookmarkItemType type) {
this.groupId = groupId;
this.amount = amount;
@@ -41,10 +56,10 @@ public class BookmarkItem {
this.factor = factor;
this.recipeId = recipeId;
this.isIngredient = isIngredient;
this.type = type == null ? BookmarkItemType.ITEM : type;
}
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, boolean isIngredient,
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, BookmarkItemType type,
Map<String, ItemStack> permutations) {
final FluidStack fluidStack = StackInfo.getFluid(stack);
int fluidCellAmount = 1;
@@ -65,18 +80,29 @@ public class BookmarkItem {
permutations,
factor * fluidCellAmount,
recipeId,
isIngredient);
type);
}
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, boolean isIngredient) {
return of(groupId, stack, factor, recipeId, isIngredient, generatePermutations(stack, recipeId, isIngredient));
public static BookmarkItem of(int groupId, ItemStack stack, long factor, RecipeId recipeId, BookmarkItemType type) {
return of(
groupId,
stack,
factor,
recipeId,
type,
generatePermutations(stack, recipeId, type == BookmarkItemType.INGREDIENT));
}
public static BookmarkItem of(int groupId, ItemStack stack) {
final NBTTagCompound nbTag = StackInfo.itemStackToNBT(stack);
final long factor = nbTag.hasKey("gtFluidName") ? Math.min(144, nbTag.getInteger("Count")) : 1;
return BookmarkItem
.of(groupId, stack, factor, null, false, Collections.singletonMap(getItemGUID(stack), stack));
return BookmarkItem.of(
groupId,
stack,
factor,
null,
BookmarkItemType.ITEM,
Collections.singletonMap(getItemGUID(stack), stack));
}
public BookmarkItem copyWithAmount(long amount) {
@@ -88,7 +114,7 @@ public class BookmarkItem {
this.permutations,
this.factor,
this.recipeId,
this.isIngredient);
this.type);
}
public BookmarkItem copy() {
@@ -186,14 +212,14 @@ public class BookmarkItem {
@Override
public int hashCode() {
return Objects.hash(this.groupId, this.fluidCellAmount, this.isIngredient, this.recipeId);
return Objects.hash(this.groupId, this.fluidCellAmount, this.type.toInt(), this.recipeId);
}
@Override
public boolean equals(Object object) {
if (object instanceof BookmarkItem item) {
return this.groupId == item.groupId && this.isIngredient == item.isIngredient
return this.groupId == item.groupId && this.type == item.type
&& this.fluidCellAmount == item.fluidCellAmount
&& StackInfo.equalItemAndNBT(this.itemStack, item.itemStack, true)
&& (this.recipeId == item.recipeId || this.recipeId != null && this.recipeId.equals(item.recipeId));
@@ -7,7 +7,6 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -16,6 +15,7 @@ import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.io.IOUtils;
import com.google.common.io.Files;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@@ -25,6 +25,7 @@ import com.google.gson.JsonSyntaxException;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
@@ -136,6 +137,7 @@ public class BookmarkStorage {
NBTTagCompound navigation = new NBTTagCompound();
namespaces.add(new BookmarkGrid());
BookmarkGrid grid = namespaces.get(0);
boolean wasError = false;
if (NEIClientConfig.world.nbt.hasKey("bookmark")) {
navigation = NEIClientConfig.world.nbt.getCompoundTag("bookmark");
@@ -150,17 +152,19 @@ public class BookmarkStorage {
}
if (itemStr.startsWith("; ")) {
JsonObject settings = parser.parse(itemStr.substring(2)).getAsJsonObject();
if (grid.size() > 0) {
// do not create empty namespaces
grid = new BookmarkGrid();
if (navigation.hasKey("namespacePage." + namespaces.size())) {
grid.setPage(navigation.getInteger("namespacePage." + namespaces.size()));
}
namespaces.add(grid);
}
if (navigation.hasKey("namespacePage." + (namespaces.size() - 1))) {
grid.setPage(navigation.getInteger("namespacePage." + (namespaces.size() - 1)));;
}
final JsonObject settings = parser.parse(itemStr.substring(2)).getAsJsonObject();
if (settings.get("viewmode") != null) {
grid.groups.get(BookmarkGrid.DEFAULT_GROUP_ID).viewMode = BookmarkViewMode
@@ -195,17 +199,28 @@ public class BookmarkStorage {
}
if (!addItemToGrid(grid, parser.parse(itemStr).getAsJsonObject())) {
wasError = true;
NEIClientConfig.logger.warn(
"Failed to load bookmarked ItemStack from json string, the item no longer exists:\n{}",
itemStr);
}
} catch (IllegalArgumentException | JsonSyntaxException | IllegalStateException e) {
} catch (Exception e) {
wasError = true;
NEIClientConfig.logger.error("Failed to load bookmarked ItemStack from json string:\n{}", itemStr);
}
}
prepareOldRecipeFormat(namespaces);
if (wasError) {
try {
Files.copy(
bookmarkFile,
new File(bookmarkFile.getAbsolutePath() + ".backup-" + System.currentTimeMillis()));
NEIClientConfig.logger.info("Backed up invalid bookmark file to {}", bookmarkFile);
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to backup invalid bookmark file to {}", bookmarkFile, e);
}
}
for (BookmarkGrid gr : namespaces) {
gr.onItemsChanged();
@@ -239,7 +254,15 @@ public class BookmarkStorage {
int groupId = jsonObject.has("groupId") ? jsonObject.get("groupId").getAsInt()
: BookmarkGrid.DEFAULT_GROUP_ID;
int factor = jsonObject.has("factor") ? Math.abs(jsonObject.get("factor").getAsInt()) : (isFluid ? 144 : 1);
boolean isIngredient = jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean();
BookmarkItemType type = jsonObject.has("type") ? BookmarkItemType.fromInt(jsonObject.get("type").getAsInt())
: null;
if (type == null) {
// old format
type = jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean()
? BookmarkItemType.INGREDIENT
: BookmarkItemType.RESULT;
}
if (jsonObject.get("recipeId") instanceof JsonObject recipeJson) {
recipeId = RecipeId.of(recipeJson);
@@ -249,51 +272,12 @@ public class BookmarkStorage {
groupId = BookmarkGrid.DEFAULT_GROUP_ID;
}
grid.addItem(BookmarkItem.of(groupId, itemStack, factor, recipeId, isIngredient), false);
grid.addItem(BookmarkItem.of(groupId, itemStack, factor, recipeId, type), false);
}
return itemStack != null;
}
private void prepareOldRecipeFormat(List<BookmarkGrid> namespaces) {
for (BookmarkGrid grid : namespaces) {
if (grid.bookmarkItems.stream()
.noneMatch(item -> item.recipeId != null && item.recipeId.getResult() == null)) {
continue;
}
final Map<String, RecipeId> recipes = new HashMap<>();
for (BookmarkItem item : grid.bookmarkItems) {
if (item.recipeId != null && !item.isIngredient && item.recipeId.getResult() == null) {
final JsonObject recipeJson = item.recipeId.toJsonObject();
final String recipeGUID = item.groupId + ":" + NBTJson.toJson(recipeJson);
if (!recipes.containsKey(recipeGUID)) {
recipeJson.add("result", NBTJson.toJsonObject(StackInfo.itemStackToNBT(item.itemStack)));
recipes.put(recipeGUID, item.recipeId = RecipeId.of(recipeJson));
}
}
}
for (BookmarkItem item : grid.bookmarkItems) {
if (item.recipeId != null && item.recipeId.getResult() == null) {
final JsonObject recipeJson = item.recipeId.toJsonObject();
final String recipeGUID = item.groupId + ":" + NBTJson.toJson(recipeJson);
if (recipes.containsKey(recipeGUID)) {
item.recipeId = recipes.get(recipeGUID).copy();
item.permutations = BookmarkItem
.generatePermutations(item.itemStack, item.recipeId, item.isIngredient);
} else {
item.recipeId = null;
}
}
}
}
}
public void save() {
if (this.bookmarkFile == null) {
@@ -338,7 +322,7 @@ public class BookmarkStorage {
row.add("item", NBTJson.toJsonObject(StackInfo.itemStackToNBT(item.getItemStack())));
row.add("factor", new JsonPrimitive(item.getFactor()));
row.add("ingredient", new JsonPrimitive(item.isIngredient));
row.add("type", new JsonPrimitive(item.type.toInt()));
if (item.groupId != BookmarkGrid.DEFAULT_GROUP_ID) {
row.add("groupId", new JsonPrimitive(item.groupId));
@@ -4,6 +4,8 @@ import java.awt.Color;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemPanels;
@@ -13,7 +15,11 @@ import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIClientUtils.Alignment;
import codechicken.nei.bookmark.BookmarkGrid.BookmarkMouseContext;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.RecipeChainDetails.CalculatedType;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.HandlerInfo;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.ReadableNumberConverter;
@@ -51,6 +57,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
protected final CalculatedType calculatedType;
protected final CalculatedType realType;
protected final BookmarkItem bookmarkItem;
protected HandlerInfo handlerInfo = null;
protected final boolean isOutputRecipe;
protected final boolean isFirstOutput;
@@ -83,7 +90,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
this.realType = this.group.crafting.calculatedItems.get(this.itemIndex).calculatedType
== CalculatedType.INGREDIENT ? CalculatedType.INGREDIENT : CalculatedType.RESULT;
} else {
this.realType = this.bookmarkItem.isIngredient
this.realType = this.bookmarkItem.type == BookmarkItemType.INGREDIENT
|| this.group.crafting != null && this.bookmarkItem.recipeId == null ? CalculatedType.INGREDIENT
: CalculatedType.RESULT;
}
@@ -91,9 +98,10 @@ public class BookmarksGridSlot extends ItemsGridSlot {
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
final BookmarkItem prevItem = grid.getCalculatedItem(
grid.gridGenerator.slotToItem.getOrDefault(grid.gridGenerator.itemToSlot.get(this.itemIndex) - 1, -1));
this.isFirstOutput = this.itemIndex >= 0 && !this.bookmarkItem.isIngredient
this.isFirstOutput = this.itemIndex >= 0 && this.bookmarkItem.type == BookmarkItemType.RESULT
&& ((this.slotIndex % grid.getColumns()) == 0 || group.viewMode == BookmarkViewMode.DEFAULT)
&& (prevItem == null || prevItem.isIngredient || !this.bookmarkItem.equalsRecipe(prevItem));
&& (prevItem == null || prevItem.type == BookmarkItemType.INGREDIENT
|| !this.bookmarkItem.equalsRecipe(prevItem));
this.rowIndex = this.slotIndex / grid.getColumns();
}
@@ -110,8 +118,8 @@ public class BookmarksGridSlot extends ItemsGridSlot {
return this.bookmarkItem.recipeId;
}
public boolean isIngredient() {
return this.bookmarkItem.isIngredient;
public BookmarkItemType getType() {
return this.bookmarkItem.type;
}
public BookmarkGroup getGroup() {
@@ -145,11 +153,17 @@ public class BookmarksGridSlot extends ItemsGridSlot {
return false;
}
if (this.group.crafting != null) {
if (this.slotIndex == mouseContext.slotIndex || this.group.crafting != null) {
return true;
}
return this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId);
if (this.bookmarkItem.type == BookmarkItemType.ITEM && this.group.viewMode == BookmarkViewMode.TODO_LIST
&& mouseContext.rowIndex == this.rowIndex) {
return true;
}
return this.bookmarkItem.type != BookmarkItemType.ITEM
&& this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId);
}
protected boolean showRealItem(BookmarkMouseContext mouseContext) {
@@ -167,7 +181,8 @@ public class BookmarksGridSlot extends ItemsGridSlot {
return true;
}
if (this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId)) {
if (this.bookmarkItem.type != BookmarkItemType.ITEM
&& this.bookmarkItem.equalsRecipe(mouseContext.recipeId, mouseContext.groupId)) {
return true;
}
@@ -175,6 +190,13 @@ public class BookmarksGridSlot extends ItemsGridSlot {
&& mouseContext.recipeId.equals(this.group.crafting.itemToRecipe.get(this.itemIndex));
}
protected HandlerInfo getHandlerInfo() {
if (this.bookmarkItem.recipeId != null && this.handlerInfo == null) {
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.bookmarkItem.recipeId.getHandleName(), null);
}
return this.handlerInfo;
}
@Override
public void drawItem(Rectangle4i rect) {
super.drawItem(this.emptyItemStack, rect);
@@ -199,7 +221,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
}
if (!this.bookmarkItem.isIngredient && this.bookmarkItem.recipeId != null
if (this.bookmarkItem.type != BookmarkItemType.INGREDIENT && this.bookmarkItem.recipeId != null
&& calculatedType == null
&& showMarker
&& (mouseContext == null || mouseContext.slotIndex != this.slotIndex)) {
@@ -246,7 +268,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
drawStackSize(rect, shownItemType);
if (this.bookmarkItem.isIngredient || this.bookmarkItem.recipeId == null) {
if (this.bookmarkItem.type == BookmarkItemType.INGREDIENT || this.bookmarkItem.recipeId == null) {
return;
}
@@ -255,27 +277,65 @@ public class BookmarksGridSlot extends ItemsGridSlot {
drawMarker(
rect,
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(this.realMultiplier),
0xFFFFFF);
0xFFFFFF,
Alignment.TopLeft);
} else if (shownItemType == ShownItemType.SHIFT) {
drawMarker(rect, "x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(getMultiplier()), 0xFFFFFF);
drawMarker(
rect,
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(getMultiplier()),
0xFFFFFF,
Alignment.TopLeft);
} else if (this.isOutputRecipe || this.realMultiplier > 1) {
drawMarker(
rect,
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(this.realMultiplier),
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue());
} else if (NEIClientConfig.showRecipeMarkerMode() == 1) {
drawMarker(
rect,
"R",
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue());
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue(),
Alignment.TopLeft);
}
} else if (NEIClientConfig.showRecipeMarkerMode() == 1) {
drawMarker(rect, "R", NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue());
}
if (this.isFirstOutput || NEIClientConfig.showRecipeMarkerMode() == 1) {
drawRecipeMarker(rect);
}
}
protected void drawMarker(Rectangle4i rect, String text, int color) {
protected void drawRecipeMarker(Rectangle4i rect) {
if (NEIClientConfig.getBooleanSetting("inventory.bookmarks.showRecipeHandlerIcon")
&& getHandlerInfo() != null) {
drawHandlerIcon(rect);
} else if (NEIClientConfig.showRecipeMarkerMode() == 1) {
drawMarker(
rect,
"R",
NEIClientConfig.getSetting("inventory.bookmarks.recipeMarkerColor").getHexValue(),
Alignment.TopRight);
}
}
protected void drawHandlerIcon(Rectangle4i rect) {
float panelFactor = 1;
if (rect.w != DEFAULT_SLOT_SIZE) {
panelFactor = (rect.w - 2) / (DEFAULT_SLOT_SIZE - 2);
}
panelFactor *= 0.4f;
float x = rect.x + 2 + 16 - 16 * panelFactor;
GL11.glTranslatef(x, rect.y, 0);
GL11.glScaled(panelFactor, panelFactor, 1.5f);
if (this.handlerInfo.getImage() != null) {
this.handlerInfo.getImage().draw(0, 0);
} else {
GuiContainerManager.drawItem(0, 0, this.handlerInfo.getItemStack(), true, "");
}
GL11.glScaled(1f / panelFactor, 1f / panelFactor, 1f / 1.5f);
GL11.glTranslatef(-1 * x, -1 * rect.y, 0);
}
protected void drawMarker(Rectangle4i rect, String text, int color, Alignment alignment) {
final float panelFactor = (rect.w - 2) / (DEFAULT_SLOT_SIZE - 2);
NEIClientUtils.drawNEIOverlayText(
text,
@@ -283,7 +343,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
panelFactor,
color,
true,
Alignment.TopLeft);
alignment);
}
protected void drawStackSize(Rectangle4i rect, ShownItemType shownItemType) {
@@ -7,6 +7,7 @@ import java.util.Map;
import java.util.Set;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
public class GroupingItem {
@@ -124,7 +125,7 @@ public class GroupingItem {
final BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
if (item.recipeId != null) {
if (item.recipeId != null && item.type != BookmarkItemType.ITEM) {
final List<Integer> sortedItems = this.grid.getSortedItems();
final BookmarkGroup group = this.grid.getGroup(item.groupId);
final boolean isCollapsedGroup = group.collapsed
@@ -139,7 +140,8 @@ public class GroupingItem {
for (Integer rItemIndex : sortedItems) {
final BookmarkItem rItem = this.grid.getCalculatedItem(rItemIndex);
if (rItem.groupId == item.groupId && (isCollapsedGroup || recipeRelations.contains(rItem.recipeId))) {
if (rItem.groupId == item.groupId && (isCollapsedGroup
|| rItem.type != BookmarkItemType.ITEM && recipeRelations.contains(rItem.recipeId))) {
return this.grid.getAbsoluteSlotIndex(rItemIndex) / this.grid.getColumns();
}
}
@@ -160,7 +162,7 @@ public class GroupingItem {
final BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
if (item.recipeId != null) {
if (item.recipeId != null && item.type != BookmarkItemType.ITEM) {
final List<Integer> sortedItems = this.grid.getSortedItems();
final BookmarkGroup group = this.grid.getGroup(item.groupId);
final boolean isCollapsedGroup = group.collapsed
@@ -176,7 +178,8 @@ public class GroupingItem {
final int rItemIndex = sortedItems.get(index);
final BookmarkItem rItem = this.grid.getCalculatedItem(rItemIndex);
if (rItem.groupId == item.groupId && (isCollapsedGroup || recipeRelations.contains(rItem.recipeId))) {
if (rItem.groupId == item.groupId && (isCollapsedGroup
|| rItem.type != BookmarkItemType.ITEM && recipeRelations.contains(rItem.recipeId))) {
return this.grid.getAbsoluteSlotIndex(rItemIndex) / this.grid.getColumns();
}
}
@@ -12,6 +12,7 @@ import java.util.stream.Collectors;
import net.minecraft.item.ItemStack;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.chain.RecipeChainMath;
@@ -69,7 +70,7 @@ public class RecipeChainDetails {
item,
item.amount,
item.amount,
item.isIngredient ? CalculatedType.INGREDIENT : CalculatedType.RESULT);
item.type == BookmarkItemType.INGREDIENT ? CalculatedType.INGREDIENT : CalculatedType.RESULT);
}
public ItemStack getItemStack(long amount) {
@@ -217,11 +218,12 @@ public class RecipeChainDetails {
for (BookmarkChainItem value : items) {
int itemIndex = sortingChainItems.get(value.getItem());
if (value.getItem().isIngredient || !recipeId.equals(value.getItem().recipeId)) {
if (value.getItem().type == BookmarkItemType.INGREDIENT || !recipeId.equals(value.getItem().recipeId)) {
itemIndex *= -1;
}
if (!value.getItem().isIngredient && !math.outputRecipes.containsKey(value.getItem().recipeId)) {
if (value.getItem().type == BookmarkItemType.RESULT
&& !math.outputRecipes.containsKey(value.getItem().recipeId)) {
value.calculatedType = CalculatedType.REMAINDER;
}
@@ -251,7 +253,7 @@ public class RecipeChainDetails {
for (BookmarkChainItem value : items) {
int itemIndex = sortingChainItems.get(value.getItem());
if (value.getItem().isIngredient || !recipeId.equals(value.getItem().recipeId)) {
if (value.getItem().type == BookmarkItemType.INGREDIENT || !recipeId.equals(value.getItem().recipeId)) {
itemIndex *= -1;
}
@@ -348,22 +350,20 @@ public class RecipeChainDetails {
private Set<RecipeId> getRecipeParents(RecipeChainMath math, RecipeId recipeId, Set<RecipeId> parents,
Set<RecipeId> visited) {
final Set<RecipeId> recipeIds = math.preferredItems.entrySet().stream()
.filter(
entry -> entry.getValue() != null && recipeId.equals(entry.getValue().recipeId)
&& !visited.contains(entry.getKey().recipeId))
.filter(entry -> entry.getValue() != null && recipeId.equals(entry.getValue().recipeId))
.map(entry -> entry.getKey().recipeId).collect(Collectors.toSet());
visited.addAll(recipeIds);
if (recipeIds.isEmpty()) {
parents.add(recipeId);
} else {
for (RecipeId ingrRecipeId : recipeIds) {
if (math.outputRecipes.containsKey(ingrRecipeId)) {
parents.add(ingrRecipeId);
} else {
getRecipeParents(math, ingrRecipeId, parents, visited);
if (visited.add(ingrRecipeId)) {
if (math.outputRecipes.containsKey(ingrRecipeId)) {
parents.add(ingrRecipeId);
} else {
getRecipeParents(math, ingrRecipeId, parents, visited);
}
}
}
@@ -9,6 +9,7 @@ import java.util.Map;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemsGrid;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.RecipeChainDetails.BookmarkChainItem;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Recipe.RecipeId;
@@ -30,10 +31,10 @@ public class SortableItem {
this.grid = grid;
this.bookmarkItem = bookmarkItem.copy();
this.moveRecipe = bookmarkItem.recipeId != null && !bookmarkItem.isIngredient
this.moveRecipe = bookmarkItem.recipeId != null && bookmarkItem.type == BookmarkItemType.RESULT
&& (group.viewMode == BookmarkViewMode.TODO_LIST || group.crafting != null);
this.crossGroup = !group.collapsed && group.viewMode == BookmarkViewMode.TODO_LIST
&& !this.bookmarkItem.isIngredient;
&& bookmarkItem.type != BookmarkItemType.INGREDIENT;
this.isCollapsedRecipe = group.crafting != null && group.crafting.itemToRecipe.values().stream()
.anyMatch(recipeId -> this.bookmarkItem.equalsRecipe(recipeId, this.bookmarkItem.groupId));
@@ -86,18 +86,20 @@ public class IMCHandler {
info.setYShift(yShift);
try {
final int imageHeight = tag.hasKey("handlerHeight") ? tag.getInteger("handlerHeight")
final int handlerHeight = tag.hasKey("handlerHeight") ? tag.getInteger("handlerHeight")
: HandlerInfo.DEFAULT_HEIGHT;
final int imageWidth = tag.hasKey("handlerWidth") ? tag.getInteger("handlerWidth")
final int handlerWidth = tag.hasKey("handlerWidth") ? tag.getInteger("handlerWidth")
: HandlerInfo.DEFAULT_WIDTH;
final int maxRecipesPerPage = tag.hasKey("maxRecipesPerPage") ? tag.getInteger("maxRecipesPerPage")
: HandlerInfo.DEFAULT_MAX_PER_PAGE;
info.setHandlerDimensions(imageHeight, imageWidth, maxRecipesPerPage);
final boolean multipleWidgetsAllowed = tag.hasKey("multipleWidgetsAllowed")
? tag.getBoolean("multipleWidgetsAllowed")
: tag.hasKey("maxRecipesPerPage") && tag.getInteger("maxRecipesPerPage") > 1;
info.setHandlerDimensions(handlerWidth, handlerHeight, multipleWidgetsAllowed);
} catch (NumberFormatException ignored) {
NEIClientConfig.logger.info("Error setting handler dimensions for {}", handler);
}
// true if not set to false
info.setUseCustomScroll(tag.hasKey("useCustomScroll") && tag.getBoolean("useCustomScroll"));
info.setShowFavoritesButton(!tag.hasKey("showFavoritesButton") || tag.getBoolean("showFavoritesButton"));
info.setShowOverlayButton(!tag.hasKey("showOverlayButton") || tag.getBoolean("showOverlayButton"));
@@ -4,6 +4,8 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import codechicken.nei.Image;
public class DrawableResource extends Image {
@@ -43,15 +45,160 @@ public class DrawableResource extends Image {
}
public void draw(int xOffset, int yOffset, int maskTop, int maskBottom, int maskLeft, int maskRight) {
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
final int x = xOffset + this.paddingLeft + maskLeft;
final int y = yOffset + this.paddingTop + maskTop;
final int textureX = this.x + maskLeft;
final int textureY = this.y + maskTop;
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
final int width = this.width - maskRight - maskLeft;
final int height = this.height - maskBottom - maskTop;
// drawModalRectWithCustomSizedTexture
Gui.func_146110_a(x, y, textureX, textureY, width, height, textureWidth, textureHeight);
GL11.glEnable(GL11.GL_TEXTURE_2D);
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
drawModalRectWithCustomSizedTexture(xOffset + maskLeft, yOffset + maskTop, maskLeft, maskTop, width, height);
if (!is2DTexture) GL11.glDisable(GL11.GL_TEXTURE_2D);
}
public void draw(int xOffset, int yOffset, int width, int height, int sliceLeft, int sliceRight, int sliceTop,
int sliceBottom) {
final int textureWidth = getWidth();
final int textureHeight = getHeight();
final int middleWidth = textureWidth - sliceLeft - sliceRight;
final int middleHeight = textureHeight - sliceTop - sliceBottom;
final int tileWidth = width - sliceLeft - sliceRight;
final int tileHeight = height - sliceTop - sliceBottom;
if (middleWidth > 0 && middleHeight > 0 && tileWidth > 0 && tileHeight > 0) {
final boolean is2DTexture = GL11.glGetBoolean(GL11.GL_TEXTURE_2D);
final int tileWidthCount = tileWidth / middleWidth;
final int remainderWidth = tileWidth - (tileWidthCount * middleWidth);
final int tileHeightCount = tileHeight / middleHeight;
final int remainderHeight = tileHeight - (tileHeightCount * middleHeight);
GL11.glEnable(GL11.GL_TEXTURE_2D);
Minecraft.getMinecraft().getTextureManager().bindTexture(this.resourceLocation);
// middle parts
for (int tileW = 0; tileW <= tileWidthCount; tileW++) {
final int tileWidthSize = (tileW == tileWidthCount) ? remainderWidth : middleWidth;
final int x = xOffset + sliceLeft + tileW * middleWidth;
for (int tileH = 0; tileH <= tileHeightCount; tileH++) {
final int tileHeightSize = (tileH == tileHeightCount) ? remainderHeight : middleHeight;
drawModalRectWithCustomSizedTexture(
x,
yOffset + sliceTop + tileH * middleHeight,
sliceLeft,
sliceTop,
tileWidthSize,
tileHeightSize);
}
}
// border top
if (sliceTop > 0) {
for (int tileW = 0; tileW <= tileWidthCount; tileW++) {
final int tileWidthSize = (tileW == tileWidthCount) ? remainderWidth : middleWidth;
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileW * middleWidth,
yOffset,
sliceLeft,
0,
tileWidthSize,
sliceTop);
}
}
// border bottom
if (sliceBottom > 0) {
for (int tileW = 0; tileW <= tileWidthCount; tileW++) {
final int tileWidthSize = (tileW == tileWidthCount) ? remainderWidth : middleWidth;
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileW * middleWidth,
yOffset + sliceTop + tileHeight,
sliceLeft,
sliceTop + middleHeight,
tileWidthSize,
sliceBottom);
}
}
// border left
if (sliceLeft > 0) {
for (int tileH = 0; tileH <= tileHeightCount; tileH++) {
final int tileHeightSize = (tileH == tileHeightCount) ? remainderHeight : middleHeight;
drawModalRectWithCustomSizedTexture(
xOffset,
yOffset + sliceTop + tileH * middleHeight,
0,
sliceTop,
sliceLeft,
tileHeightSize);
}
}
// border right
if (sliceRight > 0) {
for (int tileH = 0; tileH <= tileHeightCount; tileH++) {
final int tileHeightSize = (tileH == tileHeightCount) ? remainderHeight : middleHeight;
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileWidth,
yOffset + sliceTop + tileH * middleHeight,
sliceLeft + middleWidth,
sliceTop,
sliceRight,
tileHeightSize);
}
}
// angle left-top
if (sliceLeft > 0 && sliceTop > 0) {
drawModalRectWithCustomSizedTexture(xOffset, yOffset, 0, 0, sliceLeft, sliceTop);
}
// angle right-top
if (sliceRight > 0 && sliceTop > 0) {
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileWidth,
yOffset,
sliceLeft + middleWidth,
0,
sliceRight,
sliceTop);
}
// angle left-bottom
if (sliceLeft > 0 && sliceBottom > 0) {
drawModalRectWithCustomSizedTexture(
xOffset,
yOffset + sliceTop + tileHeight,
0,
sliceTop + middleHeight,
sliceLeft,
sliceBottom);
}
// angle right-bottom
if (sliceRight > 0 && sliceBottom > 0) {
drawModalRectWithCustomSizedTexture(
xOffset + sliceLeft + tileWidth,
yOffset + sliceTop + tileHeight,
sliceLeft + middleWidth,
sliceTop + middleHeight,
sliceRight,
sliceBottom);
}
if (!is2DTexture) GL11.glDisable(GL11.GL_TEXTURE_2D);
}
}
private void drawModalRectWithCustomSizedTexture(int xOffset, int yOffset, int u, int v, int width, int height) {
Gui.func_146110_a(
xOffset + this.paddingLeft,
yOffset + this.paddingTop,
this.x + u,
this.y + v,
width,
height,
this.textureWidth,
this.textureHeight);
}
}
@@ -1,93 +0,0 @@
package codechicken.nei.drawable;
import net.minecraft.client.gui.GuiScreen;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/*
* Taken from Mantle 1.12-1.3.3.49 under the MIT License The MIT License (MIT) Copyright (c) 2013-2014 Slime Knights
* (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions: The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
@SideOnly(Side.CLIENT)
public class GuiElementDuex {
// this is totally completely ugly but it's a simple solution that doesn't clutter everything too much >_>
public static int defaultTexW = 256;
public static int defaultTexH = 256;
public final int x;
public final int y;
public final int w;
public final int h;
public int texW;
public int texH;
public GuiElementDuex(int x, int y, int w, int h, int texW, int texH) {
this(x, y, w, h);
setTextureSize(texW, texH);
defaultTexW = texW;
defaultTexH = texH;
}
public GuiElementDuex(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
setTextureSize(defaultTexW, defaultTexH);
}
public GuiElementDuex setTextureSize(int w, int h) {
texW = w;
texH = h;
return this;
}
public GuiElementDuex shift(int xd, int yd) {
return new GuiElementDuex(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH);
}
/**
* Draws the element at the given x/y coordinates
*
* @param xPos X-Coordinate on the screen
* @param yPos Y-Coordinate on the screen
*/
public int draw(int xPos, int yPos) {
// drawModalRectWithCustomSizedTexture
GL11.glColor4f(1, 1, 1, 1);
GuiScreen.func_146110_a(xPos, yPos, x, y, w, h, texW, texH);
return w;
}
public static class Builder {
public int w;
public int h;
public Builder(int w, int h) {
this.w = w;
this.h = h;
}
public GuiElementDuex get(int x, int y, int w, int h) {
return new GuiElementDuex(x, y, w, h, this.w, this.h);
}
}
}
@@ -1,91 +0,0 @@
package codechicken.nei.drawable;
import net.minecraft.client.gui.GuiScreen;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/*
* Taken from Mantle 1.12-1.3.3.49 under the MIT License The MIT License (MIT) Copyright (c) 2013-2014 Slime Knights
* (mDiyo, fuj1n, Sunstrike, progwml6, pillbox, alexbegt) Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions: The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
@SideOnly(Side.CLIENT)
public class GuiElementScalable extends GuiElementDuex {
public GuiElementScalable(int x, int y, int w, int h, int texW, int texH) {
super(x, y, w, h, texW, texH);
}
public GuiElementScalable(int x, int y, int w, int h) {
super(x, y, w, h);
}
public int drawScaledX(int xPos, int yPos, int width) {
for (int i = 0; i < width / w; i++) {
draw(xPos + i * w, yPos);
}
// remainder that doesn't fit total width
int remainder = width % w;
if (remainder > 0) {
GuiScreen.func_146110_a(xPos + width - remainder, yPos, x, y, remainder, h, texW, texH);
}
return width;
}
public int drawScaledY(int xPos, int yPos, int height) {
for (int i = 0; i < height / h; i++) {
draw(xPos, yPos + i * h);
}
// remainder that doesn't fit total width
int remainder = height % h;
if (remainder > 0) {
// drawModalRectWithCustomSizedTexture
GuiScreen.func_146110_a(xPos, yPos + height - remainder, x, y, w, remainder, texW, texH);
}
return w;
}
public int drawScaled(int xPos, int yPos, int width, int height) {
// we draw full height row-wise
int full = height / this.h;
for (int i = 0; i < full; i++) {
drawScaledX(xPos, yPos + i * this.h, width);
}
yPos += full * this.h;
// and the remainder is drawn manually
int yRest = height % this.h;
// the same as drawScaledX but with the remaining height
for (int i = 0; i < width / w; i++) {
drawScaledY(xPos + i * w, yPos, yRest);
}
// remainder that doesn't fit total width
int remainder = width % w;
if (remainder > 0) {
// drawModalRectWithCustomSizedTexture
GuiScreen.func_146110_a(xPos + width - remainder, yPos, x, y, remainder, yRest, texW, texH);
}
return width;
}
@Override
public GuiElementScalable shift(int xd, int yd) {
GuiElementScalable element = new GuiElementScalable(this.x + xd, this.y + yd, this.w, this.h);
element.setTextureSize(texW, texH);
return element;
}
}
@@ -82,6 +82,9 @@ public class GuiContainerManager {
public static final LinkedList<IContainerSlotClickHandler> slotClickHandlers = new HideousLinkedList<>(
new CopyOnWriteArrayList<>());
// Any item rendered with this z offset should render it on top of every other gui element
public static final int TOOLTIP_Z_OFFSET = 400;
static {
addSlotClickHandler(new DefaultSlotClickHandler());
}
@@ -648,9 +651,6 @@ public class GuiContainerManager {
drawPagedTooltip(font, mousex + 12, mousey - 12, tooltip);
}
for (IContainerDrawHandler drawHandler : drawHandlers) {
drawHandler.postRenderTooltips(window, mousex, mousey, tooltip);
}
}
private List<String> collectHotkeyTips(int mousex, int mousey) {
@@ -664,12 +664,12 @@ public class GuiContainerManager {
}
}
hotkeys.remove(null);
hotkeys.remove("");
if (!hotkeys.isEmpty()) {
List<String> hotkeystips = new ArrayList<>();
Map<String, List<String>> messages = new HashMap<>();
hotkeys.remove(null);
hotkeys.remove("");
for (Map.Entry<String, String> entry : hotkeys.entrySet()) {
messages.computeIfAbsent(entry.getValue(), m -> new ArrayList<>()).add(entry.getKey());
@@ -704,13 +704,19 @@ public class GuiContainerManager {
}
} else if (NEIClientConfig.getBooleanSetting("inventory.hotkeysHelpText")) {
Map<String, String> hotkeys = new HashMap<>();
boolean existsHotkeys = false;
synchronized (instanceTooltipHandlers) {
for (IContainerTooltipHandler handler : instanceTooltipHandlers) {
if (!handler.handleHotkeys(window, mousex, mousey, new HashMap<>()).isEmpty()) {
existsHotkeys = true;
break;
if (!(hotkeys = handler.handleHotkeys(window, mousex, mousey, hotkeys)).isEmpty()) {
hotkeys.remove("");
hotkeys.remove(null);
if (!hotkeys.isEmpty()) {
existsHotkeys = true;
break;
}
}
}
}
@@ -1,7 +1,5 @@
package codechicken.nei.guihook;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
@@ -9,14 +7,14 @@ public interface IContainerDrawHandler {
/**
* Initialize your objects and the gui for drawing.
*
*
* @param gui An instance of the currentscreen
*/
public void onPreDraw(GuiContainer gui);
/**
* Draw your objects. Called after all normal gui rendering has been performed.
*
*
* @param gui An instance of the currentscreen
* @param mousex The x position of the mouse in pixels from left
* @param mousey The y position of the mouse in pixels from top
@@ -25,27 +23,16 @@ public interface IContainerDrawHandler {
/**
* Use this to draw things that should always be on top, for example objects being held by the mouse.
*
*
* @param gui An instance of the currentscreen
* @param mousex The x position of the mouse in pixels from left
* @param mousey The y position of the mouse in pixels from top
*/
public void postRenderObjects(GuiContainer gui, int mousex, int mousey);
/**
* Use this to draw things that should be drawn just after vanilla slot tooltips, on top of buttons and other
* usually always-on-top widgets.
*
* @param gui An instance of the currentscreen
* @param mousex The x position of the mouse in pixels from left
* @param mousey The y position of the mouse in pixels from top
* @param tooltip The contents of the tooltip that has previously been drawn
*/
default void postRenderTooltips(GuiContainer gui, int mousex, int mousey, List<String> tooltip) {}
/**
* Render something over a slot before the item in the slot.
*
*
* @param gui An instance of the currentscreen
* @param slot The slot being rendered.
*/
@@ -53,7 +40,7 @@ public interface IContainerDrawHandler {
/**
* Render something over a slot after the item in the slot.
*
*
* @param gui An instance of the currentscreen
* @param slot The slot being rendered.
*/
@@ -11,7 +11,7 @@ import codechicken.nei.NEIClientUtils;
public class AcceptsFollowingTooltipLineHandler extends ItemsTooltipLineHandler {
protected static final int DEFAULT_MAX_ROWS = 5;
protected static final int DEFAULT_MAX_ROWS = 4;
public Object tooltipGUID;
@@ -2,122 +2,29 @@ package codechicken.nei.recipe;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.ShortcutInputHandler;
public class ContainerRecipe extends Container {
private class RecipeInventory implements IInventory {
private ItemStack activeStack = null;
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return true;
}
@Override
public int getSizeInventory() {
return inventorySlots.size();
}
@Override
public ItemStack getStackInSlot(int i) {
if (i < 0 || i > inventoryItemStacks.size()) return null;
return (ItemStack) inventoryItemStacks.get(i);
}
@Override
public ItemStack decrStackSize(int i, int j) {
return null;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
if (slot < 0 || slot >= inventoryItemStacks.size()) return;
inventoryItemStacks.set(slot, itemstack);
}
@Override
public String getInventoryName() {
return null;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public void markDirty() {}
@Override
public void openInventory() {}
@Override
public void closeInventory() {}
@Override
public ItemStack getStackInSlotOnClosing(int var1) {
return null;
}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
return false;
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
}
private final RecipeInventory recipeInventory = new RecipeInventory();
public void clearInventory() {
inventoryItemStacks.clear();
inventorySlots.clear();
}
public ItemStack slotClick(int slot, int button, boolean flag, EntityPlayer entityplayer) {
if (slot < 0) return null;
ItemStack stack = recipeInventory.getStackInSlot(slot);
if (stack != null) {
if (button == 0) {
GuiCraftingRecipe.openRecipeGui("item", stack);
} else if (button == 1) {
GuiUsageRecipe.openRecipeGui("item", stack);
}
}
@Override
public ItemStack slotClick(int slotId, int clickedButton, int mode, EntityPlayer player) {
ShortcutInputHandler.handleMouseClick(this.activeStack);
return null;
}
public void addSlot(PositionedStack stack, int recipex, int recipey) {
int slot = inventorySlots.size();
addSlotToContainer(new Slot(recipeInventory, slot, recipex + stack.relx, recipey + stack.rely) {
@Override
public boolean isItemValid(ItemStack par1ItemStack) {
return false;
}
});
recipeInventory.setInventorySlotContents(slot, stack.item);
}
public Slot getSlotWithStack(PositionedStack stack, int recipex, int recipey) {
for (Object inventorySlot : inventorySlots) {
Slot slot = (Slot) inventorySlot;
if (slot.xDisplayPosition == (stack.relx + recipex) && slot.yDisplayPosition == (stack.rely + recipey))
return slot;
}
return null;
public void setActiveStack(ItemStack activeStack) {
this.inventorySlots.clear();
this.inventoryItemStacks.clear();
this.activeStack = activeStack;
}
@Override
public boolean canInteractWith(EntityPlayer entityplayer) {
return true;
}
@@ -131,4 +38,9 @@ public class ContainerRecipe extends Container {
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2) {
return null; // no shift clicking (scrolling...)
}
@Deprecated
public Slot getSlotWithStack(PositionedStack stack, int recipex, int recipey) {
return null;
}
}
@@ -0,0 +1,662 @@
package codechicken.nei.recipe;
import java.awt.Point;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import org.apache.commons.io.IOUtils;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.Button;
import codechicken.nei.ClientHandler;
import codechicken.nei.FormattedTextField;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.TextField;
import codechicken.nei.Widget;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.recipe.TemplateRecipeHandler.RecipeTransferRect;
public class DebugHandlerWidget extends Widget implements IContainerInputHandler {
private static abstract class IntegerField extends TextField {
protected int defaultValue = 0;
public IntegerField(String ident, int defaultValue) {
super(ident);
this.defaultValue = defaultValue;
this.h = LINE_HEIGHT;
this.z = 2;
((FormattedTextField) field).setPlaceholder(Integer.toString(this.defaultValue));
}
@Override
protected void initInternalTextField() {
field = new FormattedTextField(Minecraft.getMinecraft().fontRenderer, 0, 0, 0, 0) {
@Override
public String getText() {
String text = super.getText();
return !isFocused() && this.placeholder.equals(text) ? "" : text;
}
@Override
protected boolean beforeWrite(String text) {
if (text == null || text.isEmpty()) return true;
try {
return Integer.parseInt(text) >= 0;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public boolean textboxKeyTyped(char keyChar, int keyID) {
if (!isFocused()) return false;
if (super.textboxKeyTyped(keyChar, keyID)) {
return true;
} else if (keyID == Keyboard.KEY_DOWN) {
setText(Integer.toString(getInteger() - 1));
return true;
} else if (keyID == Keyboard.KEY_UP) {
setText(Integer.toString(getInteger() + 1));
return true;
}
return false;
}
};
field.setMaxStringLength(maxSearchLength);
field.setCursorPositionZero();
}
protected int getInteger() {
try {
return Integer.parseInt(text());
} catch (NumberFormatException nfe) {
return this.defaultValue;
}
}
@Override
public boolean onMouseWheel(int i, int mx, int my) {
if (!contains(mx, my)) return false;
setText(Integer.toString(getInteger() + i));
return true;
}
}
private final int[] COLORS = new int[] { 0x2200FF00, 0x22FF0000, 0x220000FF, 0x2200FFFF, 0x22FF00FF, 0x22FFFF00 };
private IRecipeHandler handler;
private HandlerInfo handlerInfo;
private static final int WINDOW_WIDTH = 176;
private static final int LINE_HEIGHT = 16;
private static final int INLINE_PADDING = 6;
private static final int LABEL_WIDTH = 50;
private IntegerField order;
private IntegerField yShift;
private IntegerField handlerHeight;
private IntegerField handlerWidth;
private Button multipleWidgetsAllowed;
private Button useCustomScroll;
private Point dragPoint = null;
public boolean showWidget = false;
private static final int BORDER_PADDING = 6;
private final DrawableResource BG_TEXTURE = new DrawableBuilder("nei:textures/gui/recipebg.png", 0, 0, 176, 166)
.build();
public DebugHandlerWidget() {
GuiContainerManager.addInputHandler(this);
this.order = new IntegerField("order", 0) {
@Override
public void onTextChange(String oldText) {
if (NEIClientConfig.handlerOrdering.get(handler.getOverlayIdentifier()) != null) {
if (getInteger() != NEIClientConfig.handlerOrdering.get(handler.getOverlayIdentifier())) {
updatePatch(5, getInteger(), this.defaultValue);
}
} else if (NEIClientConfig.handlerOrdering.get(handler.getHandlerId()) != null) {
if (getInteger() != NEIClientConfig.handlerOrdering.get(handler.getHandlerId())) {
updatePatch(5, getInteger(), this.defaultValue);
}
}
}
};
this.yShift = new IntegerField("yShift", 0) {
@Override
public void onTextChange(String oldText) {
if (getInteger() != handlerInfo.getYShift()) {
handlerInfo.setYShift(getInteger());
updatePatch(1, getInteger(), this.defaultValue);
}
}
};
this.multipleWidgetsAllowed = new Button() {
{
this.h = LINE_HEIGHT;
this.z = 2;
}
public String getRenderLabel() {
return handlerInfo.isMultipleWidgetsAllowed() ? "On" : "Off";
}
@Override
public boolean onButtonPress(boolean rightclick) {
handlerInfo.setHandlerDimensions(
handlerInfo.getWidth(),
handlerInfo.getHeight(),
!handlerInfo.isMultipleWidgetsAllowed());
updatePatch(4, handlerInfo.isMultipleWidgetsAllowed() ? 1 : 0, 1);
return true;
}
};
this.handlerHeight = new IntegerField("handlerHeight", HandlerInfo.DEFAULT_HEIGHT) {
@Override
public void draw(int mx, int my) {
this.field.setEnabled(handler.getRecipeHeight(0) <= 0);
super.draw(mx, my);
}
@Override
public void onTextChange(String oldText) {
if (getInteger() != handlerInfo.getHeight()) {
handlerInfo.setHandlerDimensions(
handlerInfo.getWidth(),
getInteger(),
handlerInfo.isMultipleWidgetsAllowed());
updatePatch(2, getInteger(), this.defaultValue);
}
}
};
this.handlerWidth = new IntegerField("handlerWidth", HandlerInfo.DEFAULT_WIDTH) {
@Override
public void onTextChange(String oldText) {
if (getInteger() != handlerInfo.getWidth()) {
handlerInfo.setHandlerDimensions(
getInteger(),
handlerInfo.getHeight(),
handlerInfo.isMultipleWidgetsAllowed());
updatePatch(3, getInteger(), this.defaultValue);
}
}
};
this.useCustomScroll = new Button() {
{
this.h = LINE_HEIGHT;
this.z = 2;
}
public String getRenderLabel() {
return handlerInfo.getUseCustomScroll() ? "On" : "Off";
}
@Override
public boolean onButtonPress(boolean rightclick) {
handlerInfo.setUseCustomScroll(!handlerInfo.getUseCustomScroll());
updatePatch(6, handlerInfo.getUseCustomScroll() ? 1 : 0, 0);
return true;
}
};
this.w = WINDOW_WIDTH;
this.h = 10 + 13 * LINE_HEIGHT;
this.x = 10;
this.y = 50;
this.z = 1;
}
private void updatePatch(int key, int value, int defaultValue) {
final String handlerKey = getHandlerID(handler);
if (!patches.containsKey(handlerKey)) {
patches.put(handlerKey, new String[] { handlerKey, null, null, null, null, null, null });
}
if (value == defaultValue) {
patches.get(handlerKey)[key] = null;
} else {
patches.get(handlerKey)[key] = String.valueOf(value);
}
saveHandlerInfoPatch();
if (NEIClientUtils.getGuiContainer() instanceof GuiRecipe<?>recipe) {
recipe.forceRefreshPage();
}
}
private void drawKeyLabel(String keyLabel, int topShift) {
GuiDraw.drawString(
NEIClientUtils.cropText(GuiDraw.fontRenderer, keyLabel, LABEL_WIDTH),
this.x + INLINE_PADDING,
topShift,
0x66555555,
false);
GuiDraw.drawString(":", this.x + INLINE_PADDING + LABEL_WIDTH, topShift, 0x66555555, false);
}
private void drawDetail(String keyLabel, String valueLabel, int topShift, int spaceWidth) {
drawKeyLabel(keyLabel, topShift);
GuiDraw.drawString(
NEIClientUtils.cropText(
GuiDraw.fontRenderer,
valueLabel,
this.w - INLINE_PADDING * 2 - LABEL_WIDTH - spaceWidth),
this.x + INLINE_PADDING + LABEL_WIDTH + spaceWidth,
topShift,
0xffffff);
}
private void drawControl(String keyLabel, Widget field, int topShift, int spaceWidth) {
drawKeyLabel(keyLabel, topShift);
field.x = this.x + INLINE_PADDING + LABEL_WIDTH + spaceWidth;
field.y = topShift - 4;
field.w = this.w - INLINE_PADDING * 2 - LABEL_WIDTH - spaceWidth;
}
@Override
public void draw(int mx, int my) {
if (this.handler != null) {
final int spaceWidth = GuiDraw.fontRenderer.getStringWidth(": ");
int topShift = this.y + BORDER_PADDING + 12 + 6;
GL11.glColor4f(1F, 1F, 1F, 1F);
GL11.glScaled(1, 1, 2f);
GL11.glDisable(GL11.GL_DEPTH_TEST);
BG_TEXTURE.draw(
this.x,
this.y,
this.w,
this.h,
BORDER_PADDING,
BORDER_PADDING,
BORDER_PADDING,
BORDER_PADDING);
GuiDraw.drawRect(
this.x + INLINE_PADDING,
this.y + BORDER_PADDING,
this.w - INLINE_PADDING * 2,
12,
0x30000000);
GuiDraw.drawStringC("Debug Recipe Handler", this.x + this.w / 2, this.y + BORDER_PADDING + 2, 0xffffff);
for (Map.Entry<String, String> entry : getDetailsInfo().entrySet()) {
drawDetail(entry.getKey(), entry.getValue(), topShift, spaceWidth);
topShift += LINE_HEIGHT;
}
drawControl("Order", this.order, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("yShift", this.yShift, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Multi Widgets", this.multipleWidgetsAllowed, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Height", this.handlerHeight, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Width", this.handlerWidth, topShift, spaceWidth);
topShift += LINE_HEIGHT;
drawControl("Use Custom Scroll", this.useCustomScroll, topShift, spaceWidth);
topShift += LINE_HEIGHT;
GL11.glScaled(1, 1, 1 / 2f);
}
}
private Map<String, String> getDetailsInfo() {
final Map<String, String> lines = new LinkedHashMap<>();
final boolean isHeightHackApplied = NEIClientConfig.heightHackHandlerRegex.stream()
.map(pattern -> pattern.matcher(this.handler.getHandlerId())).anyMatch(Matcher::matches);
lines.put("Name", this.handler.getRecipeName());
lines.put("ID", this.handler.getOverlayIdentifier());
lines.put("Key", this.handler.getHandlerId());
lines.put("H.Hack", String.valueOf(isHeightHackApplied));
lines.put("Mod Name", this.handlerInfo.getModName());
lines.put("Mod ID", this.handlerInfo.getModId());
return lines;
}
public void setVisible() {
if (showWidget && this.handler != null) {
LayoutManager.addWidget(this.order);
LayoutManager.addWidget(this.yShift);
LayoutManager.addWidget(this.handlerHeight);
LayoutManager.addWidget(this.handlerWidth);
LayoutManager.addWidget(this.multipleWidgetsAllowed);
LayoutManager.addWidget(this.useCustomScroll);
}
}
@Override
public void update() {
final GuiContainer gui = NEIClientUtils.getGuiContainer();
if (showWidget && gui instanceof GuiRecipe recipe) {
if (this.handler != recipe.getHandler()) {
this.handler = recipe.getHandler();
this.handlerInfo = GuiRecipeTab.getHandlerInfo(handler);
this.order.setText(String.valueOf(NEIClientConfig.getHandlerOrder(this.handler)));
this.yShift.setText(String.valueOf(this.handlerInfo.getYShift()));
this.handlerHeight.setText(String.valueOf(this.handlerInfo.getHeight()));
this.handlerWidth.setText(String.valueOf(this.handlerInfo.getWidth()));
}
} else {
this.handler = null;
this.handlerInfo = null;
showWidget = false;
}
}
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (this.handler != null) {
final int spaceWidth = GuiDraw.fontRenderer.getStringWidth(": ");
final int leftShift = this.x + INLINE_PADDING;
if (mx >= leftShift && mx < this.x + WINDOW_WIDTH - INLINE_PADDING) {
int topShift = this.y + BORDER_PADDING + 12 + 6;
for (Map.Entry<String, String> entry : getDetailsInfo().entrySet()) {
if (my >= topShift && my < topShift + LINE_HEIGHT) {
if (mx < leftShift + LABEL_WIDTH + spaceWidth) {
tooltip.add(String.valueOf(entry.getKey()));
} else {
tooltip.add(String.valueOf(entry.getValue()));
}
break;
}
topShift += LINE_HEIGHT;
}
}
}
return tooltip;
}
@Override
public boolean keyTyped(GuiContainer gui, char keyChar, int keyCode) {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && showWidget
&& keyCode == Keyboard.KEY_C
&& NEIClientUtils.controlKey()) {
final int spaceWidth = GuiDraw.fontRenderer.getStringWidth(": ");
final Point mouse = GuiDraw.getMousePosition();
if (mouse.x >= this.x + INLINE_PADDING + LABEL_WIDTH + spaceWidth
&& mouse.x < this.x + WINDOW_WIDTH - INLINE_PADDING) {
int topShift = this.y + BORDER_PADDING + 12 + 6;
for (Map.Entry<String, String> entry : getDetailsInfo().entrySet()) {
if (mouse.y >= topShift && mouse.y < topShift + LINE_HEIGHT) {
GuiScreen.setClipboardString(entry.getValue());
return true;
}
topShift += LINE_HEIGHT;
}
}
}
return false;
}
@Override
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
return false;
}
@Override
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID) {}
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && keyID == Keyboard.KEY_D
&& NEIClientUtils.shiftKey()) {
showWidget = !showWidget;
return true;
} else if (this.handler != null) {
return this.order.focused() || this.yShift.focused()
|| this.handlerHeight.focused()
|| this.handlerWidth.focused();
}
return false;
}
@Override
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
if (this.handler != null
&& new Rectangle4i(this.x + INLINE_PADDING, this.y + BORDER_PADDING, this.w - INLINE_PADDING * 2, 12)
.contains(mousex, mousey)) {
this.dragPoint = new Point(mousex, mousey);
}
}
@Override
public boolean contains(int px, int py) {
return this.handler != null && super.contains(px, py);
}
@Override
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button) {
this.dragPoint = null;
}
@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 boolean handleClickExt(int mx, int my, int button) {
return false;
}
@Override
public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime) {
if (this.dragPoint != null) {
this.x -= this.dragPoint.x - mousex;
this.y -= this.dragPoint.y - mousey;
this.dragPoint.move(mousex, mousey);
}
}
public void drawGuiPlaceholder(NEIRecipeWidget widget) {
if (!showWidget) return;
NEIClientUtils.gl2DRenderContext(() -> {
// background
GuiDraw.drawRect(
widget.x,
widget.y,
widget.w,
widget.h,
COLORS[widget.handlerRef.recipeIndex % COLORS.length]);
// center cross
GuiDraw.drawRect(widget.x + widget.w / 2 - 1, widget.y, 1, widget.h, 0x88ffffff);
GuiDraw.drawRect(widget.x, widget.y + widget.h / 2 - 1, widget.w, 1, 0x88ffffff);
// blue-line-top (grid-top)
GuiDraw.drawRect(widget.x + 14, widget.y + 5, widget.w - 38, 1, 0xff0000aa);
// blue-line-bottom {grid-bottom}
GuiDraw.drawRect(widget.x + 14, widget.y + widget.h - 7, widget.w - 38, 1, 0xff0000aa);
// blue-left (grid start)
GuiDraw.drawRect(widget.x + 24, widget.y + (widget.h - 16) / 2, 1, 16, 0xffaa00aa);
// purple (before favorite)
GuiDraw.drawRect(
widget.x + Math.min(168, widget.w) - 27,
widget.y + widget.h - 6 - GuiRecipeButton.BUTTON_HEIGHT * 2 - 4,
GuiRecipeButton.BUTTON_WIDTH,
1,
0xffaa00aa);
// green ()
GuiDraw.drawRect(
widget.x + Math.min(168, widget.w) - 35,
widget.y + widget.h - 6 - GuiRecipeButton.BUTTON_HEIGHT - 3,
20,
1,
0xff00aa00);
// purple space before bottom grid
GuiDraw.drawRect(
widget.x + 14,
widget.y + widget.h - 7 - GuiRecipeButton.BUTTON_WIDTH / 2,
38,
1,
0xffaa00aa);
if (widget.handlerRef.handler instanceof TemplateRecipeHandler handler) {
int yShift = widget.getHandlerInfo().getYShift();
for (RecipeTransferRect rect : handler.transferRects) {
GuiDraw.drawRect(
widget.x + rect.rect.x,
widget.y + yShift + rect.rect.y,
rect.rect.width,
rect.rect.height,
0x40ff0000);
}
}
});
}
private static Map<String, String[]> patches = new HashMap<>();
public static void loadHandlerInfoPatch() {
ClientHandler.loadSettingsFile("handlers.patch", lines -> {
for (String line : lines.collect(Collectors.toCollection(HashSet::new))) {
final String[] parts = line.split(",");
final String handler = parts[0];
if (GuiRecipeTab.handlerMap.containsKey(handler)) {
final HandlerInfo info = GuiRecipeTab.handlerMap.get(handler);
final int yShift = intOrDefault(parts[1], info.getYShift());
final int height = intOrDefault(parts[2], info.getHeight());
final int width = intOrDefault(parts[3], info.getWidth());
final boolean isMultipleWidgetsAllowed = intOrDefault(
parts[4],
info.isMultipleWidgetsAllowed() ? 1 : 0) == 1;
final int order = intOrDefault(parts[5], NEIClientConfig.handlerOrdering.getOrDefault(handler, 0));
final boolean useCustomScroll = intOrDefault(parts[6], info.getUseCustomScroll() ? 1 : 0) == 1;
info.setYShift(yShift);
info.setHandlerDimensions(width, height, isMultipleWidgetsAllowed);
info.setUseCustomScroll(useCustomScroll);
NEIClientConfig.handlerOrdering.put(handler, order);
}
patches.put(handler, parts);
}
});
}
private static void saveHandlerInfoPatch() {
final List<String> lines = new ArrayList<>();
for (String[] line : patches.values()) {
lines.add(String.join(",", line));
}
final File path = new File(NEIClientConfig.configDir, "handlers.patch");
try (FileOutputStream output = new FileOutputStream(path)) {
IOUtils.writeLines(lines, "\n", output, StandardCharsets.UTF_8);
} catch (IOException e) {}
}
private static int intOrDefault(String str, int defaultValue) {
if (str == null || str.equals("")) return defaultValue;
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return defaultValue;
}
}
private static String getHandlerID(IRecipeHandler handler) {
if (GuiRecipeTab.handlerMap.containsKey(handler.getHandlerId())) {
return handler.getHandlerId();
} else if (handler instanceof TemplateRecipeHandler) {
return handler.getOverlayIdentifier();
}
return null;
}
}
@@ -6,10 +6,10 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
@@ -50,17 +50,17 @@ public class DefaultOverlayHandler implements IOverlayHandler {
public Slot[] slots;
}
public DefaultOverlayHandler(int x, int y) {
offsetx = x;
offsety = y;
}
public int offsetx;
public int offsety;
public DefaultOverlayHandler() {
this(5, 11);
}
public int offsetx;
public int offsety;
public DefaultOverlayHandler(int x, int y) {
this.offsetx = x;
this.offsety = y;
}
@Override
public void overlayRecipe(GuiContainer gui, IRecipeHandler handler, int recipeIndex, boolean maxTransfer) {
@@ -72,7 +72,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
final List<PositionedStack> ingredients = handler.getIngredientStacks(recipeIndex);
final List<DistributedIngred> ingredStacks = getPermutationIngredients(ingredients);
if (!clearIngredients(gui)) return 0;
if (!clearIngredients(gui, handler)) return 0;
findInventoryQuantities(gui, ingredStacks);
@@ -99,12 +99,17 @@ public class DefaultOverlayHandler implements IOverlayHandler {
}
@Override
public boolean craft(GuiContainer firstGui, IRecipeHandler recipe, int recipeIndex, int multiplier) {
final EntityClientPlayerMP thePlayer = NEIClientUtils.mc().thePlayer;
boolean craft = false;
public boolean craft(GuiContainer firstGui, IRecipeHandler handler, int recipeIndex, int multiplier) {
final Slot craftingSlot = firstGui.inventorySlots.inventorySlots.stream()
.filter(slot -> slot instanceof SlotCrafting).findFirst().orElse(null);
if (craftingSlot == null) {
return false;
}
boolean craft = false;
while (multiplier > 0) {
final int transfer = transferRecipe(firstGui, recipe, recipeIndex, multiplier);
final int transfer = transferRecipe(firstGui, handler, recipeIndex, multiplier);
if (transfer <= 0) {
break;
@@ -112,43 +117,88 @@ public class DefaultOverlayHandler implements IOverlayHandler {
multiplier -= transfer;
for (Slot slot : firstGui.inventorySlots.inventorySlots) {
if (slot.getHasStack() && slot instanceof SlotCrafting && slot.canTakeStack(thePlayer)) {
FastTransferManager.clickSlot(firstGui, slot.slotNumber, 0, 1);
craft = true;
break;
}
if (craftingSlot.getHasStack() && craftingSlot.canTakeStack(firstGui.mc.thePlayer)) {
FastTransferManager.clickSlot(firstGui, craftingSlot.slotNumber, 0, 1);
craft = true;
}
}
clearIngredients(firstGui);
clearIngredients(firstGui, handler);
return craft;
}
private boolean clearIngredients(GuiContainer gui) {
final EntityClientPlayerMP thePlayer = NEIClientUtils.mc().thePlayer;
protected boolean clearIngredients(GuiContainer gui, IRecipeHandler handler) {
for (Slot slot : gui.inventorySlots.inventorySlots) {
if (slot.getHasStack() && !canMoveFrom(slot, gui)
&& !(slot instanceof SlotCrafting)
&& slot.canTakeStack(thePlayer)) {
for (Slot slot : getCraftMatrixSlots(gui, handler)) {
if (slot.canTakeStack(gui.mc.thePlayer)) {
FastTransferManager.clickSlot(gui, slot.slotNumber, 0, 1);
if (slot.getHasStack()) return false;
}
}
return dropOffMouseStack(thePlayer, gui);
FastTransferManager.dropHeldItem(gui);
return gui.mc.thePlayer.inventory.getItemStack() == null;
}
/**
* Gets the slots in the crafting matrix for the given GUI and recipe handler.
*
* @param gui
* @param handler
* @return
*/
protected Set<Slot> getCraftMatrixSlots(GuiContainer gui, IRecipeHandler handler) {
final PositionedStack firstIngr = handler.getIngredientStacks(0).get(0);
final Map<Integer, Slot> grid = new HashMap<>();
final Set<Slot> ingredSlots = new HashSet<>();
for (Slot slot : gui.inventorySlots.inventorySlots) {
final int key = (slot.xDisplayPosition - this.offsetx) * 10_000 + (slot.yDisplayPosition - this.offsety);
grid.put(key, slot);
}
int left = firstIngr.relx;
int top = firstIngr.rely;
int right = left;
int bottom = top;
while (grid.containsKey((left - 18) * 10_000 + firstIngr.rely)) {
left -= 18;
}
while (grid.containsKey((right + 18) * 10_000 + firstIngr.rely)) {
right += 18;
}
while (grid.containsKey(firstIngr.relx * 10_000 + (top - 18))) {
top -= 18;
}
while (grid.containsKey(firstIngr.relx * 10_000 + (bottom + 18))) {
bottom += 18;
}
for (int x = left; x <= right; x += 18) {
for (int y = top; y <= bottom; y += 18) {
final Slot slot = grid.get(x * 10_000 + y);
if (slot != null && !(slot.inventory instanceof InventoryPlayer)) {
ingredSlots.add(slot);
}
}
}
return ingredSlots;
}
private void moveIngredients(GuiContainer gui, List<IngredientDistribution> assignedIngredients, int multiplier) {
final EntityClientPlayerMP thePlayer = NEIClientUtils.mc().thePlayer;
for (Slot slot : gui.inventorySlots.inventorySlots) {
if (slot instanceof SlotCrafting || !slot.getHasStack()
|| !canMoveFrom(slot, gui)
|| !slot.canTakeStack(thePlayer))
|| !slot.canTakeStack(gui.mc.thePlayer))
continue;
ItemStack stack = slot.getStack();
int slotTransferCap = stack.getMaxStackSize();
@@ -186,7 +236,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
}
if (thePlayer.inventory.getItemStack() != null) {
if (gui.mc.thePlayer.inventory.getItemStack() != null) {
FastTransferManager.clickSlot(gui, slot.slotNumber);
}
}
@@ -194,33 +244,6 @@ public class DefaultOverlayHandler implements IOverlayHandler {
}
}
protected boolean dropOffMouseStack(EntityPlayer entityPlayer, GuiContainer gui) {
if (entityPlayer.inventory.getItemStack() == null) {
return true;
}
for (int i = 0; i < gui.inventorySlots.inventorySlots.size(); i++) {
Slot slot = gui.inventorySlots.inventorySlots.get(i);
if (slot.inventory == entityPlayer.inventory) {
ItemStack mouseItem = entityPlayer.inventory.getItemStack();
ItemStack slotStack = slot.getStack();
if (slotStack == null || NEIClientUtils.areStacksSameType(mouseItem, slotStack)) {
FastTransferManager.clickSlot(gui, i, 0, 0);
}
if (entityPlayer.inventory.getItemStack() == null) {
return true;
}
}
}
return entityPlayer.inventory.getItemStack() == null;
}
private int calculateRecipeQuantity(List<IngredientDistribution> assignedIngredients) {
int quantity = Integer.MAX_VALUE;
@@ -27,7 +27,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
}
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 48, Collections.singletonList(ingred));
return Collections.singletonList(ingred);
}
public PositionedStack getResult() {
@@ -18,9 +18,9 @@ import codechicken.nei.ItemPanels;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.stackinfo.GTFluidStackStringifyHandler;
public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
@@ -36,10 +36,13 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
final Minecraft mc = NEIClientUtils.mc();
final RecipeId recipeId;
if ("item".equals(outputId)) {
for (int i = 0; i < results.length; i++) {
results[i] = normalizeItemStack((ItemStack) results[i]);
for (int i = 0; i < results.length; i++) {
if (results[i] instanceof ItemStack stack) {
results[i] = StackInfo.normalizeRecipeQueryStack(stack.copy());
}
}
if ("item".equals(outputId)) {
recipeId = getRecipeId(mc.currentScreen, (ItemStack) results[0]);
} else if ("recipeId".equals(outputId)) {
recipeId = (RecipeId) results[1];
@@ -50,7 +53,7 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
final ArrayList<ICraftingHandler> handlers = getCraftingHandlers(outputId, results);
if (!handlers.isEmpty()) {
final GuiCraftingRecipe gui = new GuiCraftingRecipe(handlers, "recipeId".equals(outputId));
final GuiCraftingRecipe gui = new GuiCraftingRecipe(handlers);
if (open) {
@@ -105,13 +108,6 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
return GuiRecipeTab.getHandlerInfo(handler).getHandlerName();
}
private static ItemStack normalizeItemStack(ItemStack stack) {
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = true;
stack = StackInfo.loadFromNBT(StackInfo.itemStackToNBT(stack));
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = false;
return stack;
}
public static RecipeId getRecipeId(GuiScreen gui, ItemStack stackover) {
if (gui instanceof GuiRecipe guiRecipe) {
@@ -126,7 +122,8 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
final BookmarksGridSlot panelSlot = ItemPanels.bookmarkPanel.getSlotMouseOver(mouseover.x, mouseover.y);
if (panelSlot != null) {
return panelSlot.isIngredient() || panelSlot.getRecipeId() == null ? FavoriteRecipes.getFavorite(stackover)
return panelSlot.getType() == BookmarkItemType.INGREDIENT || panelSlot.getRecipeId() == null
? FavoriteRecipes.getFavorite(stackover)
: panelSlot.getRecipeId();
}
@@ -147,9 +144,8 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
return null;
}
private GuiCraftingRecipe(ArrayList<ICraftingHandler> handlers, boolean limitToOneRecipe) {
private GuiCraftingRecipe(ArrayList<ICraftingHandler> handlers) {
super(NEIClientUtils.mc().currentScreen);
this.limitToOneRecipe = limitToOneRecipe;
this.currenthandlers = handlers;
}
@@ -9,7 +9,6 @@ import java.util.Map;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
@@ -73,7 +72,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
public boolean isFavorite() {
return favorite;
return this.favorite;
}
public void toggleFavorite() {
@@ -87,6 +86,11 @@ public class GuiFavoriteButton extends GuiRecipeButton {
.setFavorite(this.favoriteResult.getItemStack(), this.favorite ? this.recipe.getRecipeId() : null);
}
@Override
public void update() {
this.favorite = this.favorite && FavoriteRecipes.getFavorite(this.recipe.getRecipeId()) != null;
}
@Override
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
final DrawableResource icon = isFavorite() ? ICON_STATE_ON : ICON_STATE_OFF;
@@ -116,7 +120,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
return Recipe.of(this.handlerRef);
}
public void lastKeyTyped(GuiRecipe<?> gui, char keyChar, int keyID) {
public void lastKeyTyped(char keyChar, int keyID) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark") && NEIClientUtils.shiftKey()) {
saveRecipeInBookmark();
@@ -125,7 +129,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
hotkeys.put(
NEIClientConfig.getKeyName("gui.bookmark", NEIClientUtils.SHIFT_HASH),
translate("recipe.favorite.bookmark_recipe"));
@@ -140,7 +144,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip) {
public List<String> handleTooltip(List<String> currenttip) {
currenttip.add(translate("recipe.favorite"));
return currenttip;
@@ -161,7 +165,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
public boolean mouseScrolled(GuiRecipe<?> gui, int scroll) {
public boolean mouseScrolled(int scroll) {
if (this.selectedResult == null) return true;
final List<RecipeIngredient> results = new ArrayList<>(this.recipe.getResults());
@@ -106,17 +106,17 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip) {
public List<String> handleTooltip(List<String> currenttip) {
currenttip.add(NEIClientUtils.translate("recipe.overlay"));
if (!this.enabled && this.requireShiftForOverlayRecipe && this.canFillCraftingGrid) {
if (!this.enabled && requireShiftForOverlayRecipe() && canFillCraftingGrid()) {
currenttip.set(currenttip.size() - 1, currenttip.get(currenttip.size() - 1) + GuiDraw.TOOLTIP_LINESPACE);
currenttip.add(
EnumChatFormatting.RED + NEIClientUtils.translate("recipe.overlay.mismatch")
+ EnumChatFormatting.RESET);
} else if (this.missedMaterialsTooltipLineHandler != null) {
if ((!this.requireShiftForOverlayRecipe || NEIClientUtils.shiftKey()) && this.canFillCraftingGrid) {
if ((!requireShiftForOverlayRecipe() || NEIClientUtils.shiftKey()) && canFillCraftingGrid()) {
this.missedMaterialsTooltipLineHandler.setLabelColor(EnumChatFormatting.RED);
} else {
this.missedMaterialsTooltipLineHandler.setLabelColor(EnumChatFormatting.GRAY);
@@ -129,7 +129,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
public Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys) {
if (requireShiftForOverlayRecipe()) {
@@ -174,7 +174,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
DrawableResource icon = ICON_OVERLAY;
if (this.hasOverlay && (!this.requireShiftForOverlayRecipe || NEIClientUtils.shiftKey())) {
if (hasOverlay() && (!requireShiftForOverlayRecipe() || NEIClientUtils.shiftKey())) {
icon = this.missedMaterialsTooltipLineHandler == null ? ICON_FILL : ICON_FILL_ERROR;
}
@@ -206,18 +206,19 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
protected List<ItemOverlayState> ingredientsOverlay() {
List<PositionedStack> ingredients = this.handlerRef.handler.getIngredientStacks(this.handlerRef.recipeIndex);
final List<PositionedStack> ingredients = this.handlerRef.handler
.getIngredientStacks(this.handlerRef.recipeIndex);
if (this.itemPresenceCache.size() != ingredients.size()) {
this.itemPresenceCache.clear();
if (this.canFillCraftingGrid) {
if (canFillCraftingGrid()) {
this.itemPresenceCache.addAll(this.handlerRef.getPresenceOverlay(this.firstGui));
} else if (this.firstGui != null) {
this.itemPresenceCache.addAll(presenceOverlay(ingredients));
}
List<ItemStack> items = this.itemPresenceCache.stream().filter(state -> !state.isPresent())
final List<ItemStack> items = this.itemPresenceCache.stream().filter(state -> !state.isPresent())
.map(state -> state.getSlot().item).collect(Collectors.toList());
if (!items.isEmpty()) {
@@ -236,7 +237,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
public void setRequireShiftForOverlayRecipe(boolean require) {
this.requireShiftForOverlayRecipe = require;
this.enabled = this.hasOverlay && (this.requireShiftForOverlayRecipe || this.canFillCraftingGrid);
this.enabled = hasOverlay() && (this.requireShiftForOverlayRecipe || canFillCraftingGrid());
}
public void setCanUseOverlayRenderer(boolean use) {
@@ -263,7 +264,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
return Recipe.of(this.handlerRef);
}
private List<ItemOverlayState> presenceOverlay(List<PositionedStack> ingredients) {
protected List<ItemOverlayState> presenceOverlay(List<PositionedStack> ingredients) {
final List<ItemOverlayState> itemPresenceSlots = new ArrayList<>();
final List<ItemStack> invStacks = this.firstGui.inventorySlots.inventorySlots.stream()
.filter(
@@ -289,9 +290,9 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
public void overlayRecipe(boolean shift) {
if (!this.hasOverlay) return;
if (!hasOverlay()) return;
if (!this.requireShiftForOverlayRecipe || shift) {
if (!requireShiftForOverlayRecipe() || shift) {
if (canFillCraftingGrid()) {
this.handlerRef.fillCraftingGrid(this.firstGui, 0);
}
@@ -302,8 +303,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
public void lastKeyTyped(GuiRecipe<?> gui, char keyChar, int keyID) {
public void lastKeyTyped(char keyChar, int keyID) {
if (NEIClientConfig.isKeyHashDown("gui.bookmark") && NEIClientUtils.shiftKey()) {
saveRecipeInBookmark();
}
@@ -313,8 +313,11 @@ public class GuiOverlayButton extends GuiRecipeButton {
final Recipe recipe = getRecipe();
if (!ItemPanels.bookmarkPanel.removeRecipe(recipe.getRecipeId(), BookmarkGrid.DEFAULT_GROUP_ID)) {
ItemPanels.bookmarkPanel
.addRecipe(recipe, NEIClientUtils.controlKey() ? 1 : 0, BookmarkGrid.DEFAULT_GROUP_ID);
ItemPanels.bookmarkPanel.addRecipe(
recipe,
NEIClientUtils.controlKey()
|| NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkRecipeWithCount") ? 1 : 0,
BookmarkGrid.DEFAULT_GROUP_ID);
}
}
File diff suppressed because it is too large. Load diff
@@ -4,7 +4,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.client.event.GuiScreenEvent;
import codechicken.lib.vec.Rectangle4i;
@@ -16,33 +15,30 @@ public abstract class GuiRecipeButton extends GuiNEIButton {
public static class UpdateRecipeButtonsEvent extends GuiScreenEvent {
public List<GuiRecipeButton> buttonList;
public NEIRecipeWidget recipeWidget;
public UpdateRecipeButtonsEvent(GuiRecipe<?> gui, List<GuiRecipeButton> buttonList) {
public UpdateRecipeButtonsEvent(GuiRecipe<?> gui, NEIRecipeWidget recipeWidget,
List<GuiRecipeButton> buttonList) {
super(gui);
this.recipeWidget = recipeWidget;
this.buttonList = new ArrayList<>(buttonList);
}
@Cancelable
public static class Pre extends UpdateRecipeButtonsEvent {
public int xOffset;
public int yOffset;
public int height;
public HandlerInfo handlerInfo;
public Pre(GuiRecipe<?> gui, int xOffset, int yOffset, int height, HandlerInfo handlerInfo) {
super(gui, new ArrayList<>());
this.xOffset = xOffset;
this.yOffset = yOffset;
this.height = height;
public Pre(GuiRecipe<?> gui, NEIRecipeWidget recipeWidget, HandlerInfo handlerInfo) {
super(gui, recipeWidget, new ArrayList<>());
this.handlerInfo = handlerInfo;
}
}
public static class Post extends UpdateRecipeButtonsEvent {
public Post(GuiRecipe<?> gui, List<GuiRecipeButton> buttonList) {
super(gui, buttonList);
public Post(GuiRecipe<?> gui, NEIRecipeWidget recipeWidget, List<GuiRecipeButton> buttonList) {
super(gui, recipeWidget, buttonList);
}
}
}
@@ -57,15 +53,19 @@ public abstract class GuiRecipeButton extends GuiNEIButton {
this.handlerRef = point;
}
abstract List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip);
public abstract List<String> handleTooltip(List<String> currenttip);
abstract Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys);
public abstract Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys);
abstract void lastKeyTyped(GuiRecipe<?> gui, char keyChar, int keyID);
public abstract void lastKeyTyped(char keyChar, int keyID);
abstract void drawItemOverlay();
public abstract void drawItemOverlay();
public boolean mouseScrolled(GuiRecipe<?> gui, int scroll) {
public void update() {
}
public boolean mouseScrolled(int scroll) {
return false;
}
@@ -1,159 +1,185 @@
package codechicken.nei.recipe;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.util.ResourceLocation;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.util.Rectangle;
import org.lwjgl.opengl.GL11;
import codechicken.nei.api.INEIGuiAdapter;
import codechicken.nei.drawable.GuiElementDuex;
import codechicken.nei.drawable.GuiElementScalable;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.Widget;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.scroll.ScrollBar;
import codechicken.nei.scroll.ScrollContainer;
public class GuiRecipeCatalyst extends INEIGuiAdapter {
public class GuiRecipeCatalyst extends ScrollContainer {
private GuiRecipe<?> guiRecipe;
public static final int ingredientSize = 16;
public static final int ingredientBorder = 1;
public static final int tabBorder = 5;
public static final int fullBorder = ingredientBorder + tabBorder;
protected static class ItemStackWidget extends Widget {
private static final Rectangle catalystRect = new Rectangle();
private static final Rectangle targetRect = new Rectangle();
private final PositionedStack pStack;
public GuiRecipeCatalyst(GuiRecipe<?> guiRecipe) {
this.guiRecipe = guiRecipe;
public ItemStackWidget(PositionedStack pStack) {
this.pStack = pStack;
this.x = pStack.relx;
this.y = pStack.rely;
this.w = SLOT_SIZE;
this.h = SLOT_SIZE;
}
@Override
public void draw(int mx, int my) {
GuiContainerManager.drawItem(this.x, this.y, this.pStack.item);
if (contains(mx, my)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(this.x, this.y, this.w, this.h, 0x80FFFFFF));
}
}
@Override
public boolean handleClick(int mx, int my, int button) {
return ShortcutInputHandler.handleMouseClick(this.pStack.item);
}
}
public void draw() {
if (guiRecipe == null) return;
int catalystsSize = RecipeCatalysts.getRecipeCatalysts(guiRecipe.getHandler()).size();
if (catalystsSize == 0) return;
private static final int SLOT_SIZE = 16;
private static final int BORDER_PADDING = 6;
private static final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/catalyst_tab.png",
0,
0,
28,
28).setTextureSize(28, 28).build();
int availableHeight = RecipeCatalysts.getHeight();
int columnCount = RecipeCatalysts.getColumnCount(availableHeight, catalystsSize);
int rowCount = RecipeCatalysts.getRowCount(availableHeight, catalystsSize);
int width, height, xPos, yPos;
private static final DrawableResource FG_TEXTURE = new DrawableBuilder("nei:textures/slot.png", 0, 0, 18, 18)
.setTextureSize(18, 18).build();
width = (ingredientBorder * 2) + (tabBorder * 2) + (columnCount * ingredientSize);
height = (ingredientBorder * 2) + (tabBorder * 2) + (rowCount * ingredientSize);
xPos = guiRecipe.guiLeft - width + tabBorder + 1;
yPos = guiRecipe.guiTop;
drawBordered("nei:textures/catalyst_tab.png", xPos, yPos, width, height, 28, 28, 6, 6, 6, 6);
private static final ScrollBar VERTICAL_SCROLLBAR = ScrollBar.defaultVerticalBar()
.setOverflowType(ScrollBar.OverflowType.AUTO).setTrackPadding(0, BORDER_PADDING, -13, BORDER_PADDING)
.setScrollPlace(ScrollBar.ScrollPlace.START);
width = (ingredientBorder * 2) + (columnCount * ingredientSize);
height = (ingredientBorder * 2) + (rowCount * ingredientSize);
xPos = guiRecipe.guiLeft - width + ingredientBorder + 1;
yPos = guiRecipe.guiTop + fullBorder - ingredientBorder;
drawBordered("nei:textures/slot.png", xPos, yPos, width, height, 18, 18, 1, 1, 1, 1);
private PositionedStack[] items = new PositionedStack[0];
private boolean showWidget = false;
private int availableHeight = 0;
public GuiRecipeCatalyst() {
setPaddingBlock(BORDER_PADDING + 1, BORDER_PADDING + 1);
}
public void setCatalysts(List<PositionedStack> items) {
this.items = items.toArray(new PositionedStack[0]);
createWidgets();
}
public void setAvailableHeight(int height) {
if (this.availableHeight != height) {
this.availableHeight = height;
createWidgets();
}
}
public int getAvailableHeight() {
return this.availableHeight;
}
public boolean isShowWidget() {
return this.showWidget;
}
public int getColumnCount() {
if (NEIClientConfig.getJEIStyleRecipeCatalysts() == 1) {
final int maxItemsPerColumn = Math.max(0, this.availableHeight - 2 - BORDER_PADDING * 2) / SLOT_SIZE;
return maxItemsPerColumn > 0 ? NEIServerUtils.divideCeil(this.items.length, maxItemsPerColumn) : 0;
}
return 1;
}
public int getRowCount() {
final int columnCount = getColumnCount();
return columnCount > 0 ? NEIServerUtils.divideCeil(this.items.length, columnCount) : 0;
}
protected void createWidgets() {
final int columns = getColumnCount();
final int rows = getRowCount();
setVerticalScroll(null);
setPaddingInline(BORDER_PADDING + 1, BORDER_PADDING - 3);
this.h = rows * SLOT_SIZE + this.paddingBlockStart + this.paddingBlockEnd;
this.w = columns * SLOT_SIZE + this.paddingInlineStart + this.paddingInlineEnd;
if (NEIClientConfig.getJEIStyleRecipeCatalysts() == 2
&& rows * SLOT_SIZE + this.paddingBlockStart + this.paddingBlockEnd > this.availableHeight) {
this.h = Math.min(this.h, this.availableHeight);
this.w += VERTICAL_SCROLLBAR.getTrackWidth();
setVerticalScroll(VERTICAL_SCROLLBAR);
setPaddingInline(BORDER_PADDING + 1 + VERTICAL_SCROLLBAR.getTrackWidth(), this.paddingInlineEnd);
}
this.showWidget = rows * columns > 0;
if (rows == 0 || columns == 0) {
return;
}
final int visibleWidth = getVisibleWidth();
final List<Widget> widgets = new ArrayList<>();
int index = 0;
for (PositionedStack pStack : this.items) {
pStack.relx = visibleWidth - SLOT_SIZE - (index / rows) * SLOT_SIZE;
pStack.rely = (index % rows) * SLOT_SIZE;
index++;
widgets.add(new ItemStackWidget(pStack));
}
setWidgets(widgets);
}
@Override
public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) {
if (!(gui instanceof GuiRecipe)) return false;
guiRecipe = (GuiRecipe<?>) gui;
int catalystsSize = RecipeCatalysts.getRecipeCatalysts(guiRecipe.getHandler()).size();
if (catalystsSize == 0) return false;
public void draw(int mx, int my) {
if (!this.showWidget) return;
int availableHeight = RecipeCatalysts.getHeight();
int columnCount = RecipeCatalysts.getColumnCount(availableHeight, catalystsSize);
int rowCount = RecipeCatalysts.getRowCount(availableHeight, catalystsSize);
int margin = 4;
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(this.x, this.y, this.w, this.h, BORDER_PADDING, BORDER_PADDING, BORDER_PADDING, BORDER_PADDING);
FG_TEXTURE.draw(
this.x + this.paddingInlineStart - 1,
this.y + this.paddingBlockStart - 1,
this.w - this.paddingInlineStart - this.paddingInlineEnd + 2,
this.h - this.paddingBlockStart - this.paddingBlockEnd + 2,
1,
1,
1,
1);
int width = (ingredientBorder * 2) + (tabBorder * 2) + (columnCount * ingredientSize) + margin;
int height = (ingredientBorder * 2) + (tabBorder * 2) + (rowCount * ingredientSize) + margin;
int xOffset = guiRecipe.guiLeft - width + tabBorder;
int yOffset = guiRecipe.guiTop;
catalystRect.setBounds(xOffset, yOffset, width, height);
targetRect.setBounds(x, y, w, h);
return targetRect.intersects(catalystRect);
super.draw(mx, my);
}
private void drawBordered(String location, int xPos, int yPos, int width, int height, int texWidth, int texHeight,
int sliceLeft, int sliceRight, int sliceTop, int sliceBottom) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(location));
public PositionedStack getPositionedStackMouseOver(int mx, int my) {
final Widget widget = getWidgetUnderMouse(mx, my);
GuiElementDuex cornerTopLeft = new GuiElementDuex(0, 0, sliceLeft, sliceTop, texWidth, texHeight);
GuiElementDuex cornerTopRight = new GuiElementDuex(
texWidth - sliceRight,
0,
sliceRight,
sliceTop,
texWidth,
texHeight);
GuiElementDuex cornerBottomLeft = new GuiElementDuex(
0,
texHeight - sliceBottom,
sliceLeft,
sliceBottom,
texWidth,
texHeight);
GuiElementDuex cornerBottomRight = new GuiElementDuex(
texWidth - sliceRight,
texHeight - sliceBottom,
sliceRight,
sliceBottom,
texWidth,
texHeight);
if (widget instanceof ItemStackWidget stackWidget) {
return stackWidget.pStack;
}
GuiElementScalable borderTop = new GuiElementScalable(
sliceLeft,
0,
texWidth - sliceLeft - sliceRight,
sliceTop,
texWidth,
texHeight);
GuiElementScalable borderBottom = new GuiElementScalable(
sliceLeft,
texHeight - sliceBottom,
texWidth - sliceLeft - sliceRight,
sliceBottom,
texWidth,
texHeight);
GuiElementScalable borderLeft = new GuiElementScalable(
0,
sliceTop,
sliceLeft,
texHeight - sliceTop - sliceBottom,
texWidth,
texHeight);
GuiElementScalable borderRight = new GuiElementScalable(
texWidth - sliceRight,
sliceTop,
sliceRight,
texHeight - sliceTop - sliceBottom,
texWidth,
texHeight);
GuiElementScalable center = new GuiElementScalable(
sliceLeft,
sliceTop,
texWidth - sliceLeft - sliceRight,
texHeight - sliceTop - sliceBottom,
texWidth,
texHeight);
int midW = width - borderLeft.w - borderRight.w;
int midH = height - borderTop.h - borderBottom.h;
// top row
int x = xPos;
int y = yPos;
x += cornerTopLeft.draw(x, y);
x += borderTop.drawScaledX(x, y, midW);
cornerTopRight.draw(x, y);
// center row
x = xPos;
y += borderTop.h;
x += borderLeft.drawScaledY(x, y, midH);
x += center.drawScaled(x, y, midW, midH);
borderRight.drawScaledY(x, y, midH);
// bottom row
x = xPos;
y += midH;
x += cornerBottomLeft.draw(x, y);
x += borderBottom.drawScaledX(x, y, midW);
cornerBottomRight.draw(x, y);
return null;
}
@Deprecated
public static final int ingredientSize = 16;
@Deprecated
public static final int ingredientBorder = 1;
@Deprecated
public static final int tabBorder = 5;
@Deprecated
public static final int fullBorder = ingredientBorder + tabBorder;
}
@@ -42,10 +42,9 @@ public abstract class GuiRecipeTab extends Widget {
public static HashMap<String, HandlerInfo> handlerAdderFromIMC = new HashMap<>();
public static Set<String> handlerRemoverFromIMC = new HashSet<>();
private final GuiRecipe<?> guiRecipe;
private final IRecipeHandler handler;
private final String handlerName;
private final String handlerID;
protected final IRecipeHandler handler;
protected final String handlerName;
protected final String handlerID;
private boolean selected;
@@ -61,7 +60,7 @@ public abstract class GuiRecipeTab extends Widget {
protected abstract int getForegroundIconY();
public GuiRecipeTab(GuiRecipe<?> guiRecipe, IRecipeHandler handler, int x, int y) {
public GuiRecipeTab(IRecipeHandler handler, int x, int y) {
super();
this.x = x;
this.y = y;
@@ -69,7 +68,6 @@ public abstract class GuiRecipeTab extends Widget {
this.h = getHeight();
this.handler = handler;
this.handlerName = handler.getHandlerId();
this.guiRecipe = guiRecipe;
this.selected = false;
if (handler instanceof TemplateRecipeHandler) {
@@ -154,16 +152,10 @@ public abstract class GuiRecipeTab extends Widget {
}
}
public boolean onButtonPress(boolean rightclick) {
int newIdx = guiRecipe.currenthandlers.indexOf(handler);
if (newIdx == -1) return false;
public abstract boolean onButtonPress(boolean rightclick);
guiRecipe.setRecipePage(newIdx);
return true;
}
public void setSelected(IRecipeHandler current) {
selected = handler == current;
public void setSelected(boolean selected) {
this.selected = selected;
}
public static HandlerInfo getHandlerInfo(IRecipeHandler handler) {
@@ -263,16 +255,16 @@ public abstract class GuiRecipeTab extends Widget {
if (yShift != null && !yShift.equals("")) info.setYShift(Integer.parseInt(yShift));
try {
final int imageHeight = intOrDefault(record.get("handlerHeight"), HandlerInfo.DEFAULT_HEIGHT);
final int imageWidth = intOrDefault(record.get("handlerWidth"), HandlerInfo.DEFAULT_WIDTH);
final int maxRecipesPerPage = intOrDefault(
record.get("maxRecipesPerPage"),
HandlerInfo.DEFAULT_MAX_PER_PAGE);
info.setHandlerDimensions(imageHeight, imageWidth, maxRecipesPerPage);
final int handlerHeight = intOrDefault(record.get("handlerHeight"), HandlerInfo.DEFAULT_HEIGHT);
final int handlerWidth = intOrDefault(record.get("handlerWidth"), HandlerInfo.DEFAULT_WIDTH);
final boolean multipleWidgetsAllowed = intOrDefault(record.get("maxRecipesPerPage"), 1) > 1;
info.setHandlerDimensions(handlerWidth, handlerHeight, multipleWidgetsAllowed);
} catch (NumberFormatException ignored) {
NEIClientConfig.logger.info("Error setting handler dimensions for " + handler);
}
info.setUseCustomScroll(
record.isSet("useCustomScroll") ? Boolean.parseBoolean(record.get("useCustomScroll")) : false);
handlerMap.put(handler, info);
NEIClientConfig.logger.info("Loaded " + handler);
}
@@ -304,10 +296,7 @@ public abstract class GuiRecipeTab extends Widget {
private static HandlerInfo getDefaultHandlerInfo() {
final HandlerInfo info = new HandlerInfo("Unknown", "Unknown", "Unknown", false, "");
info.setHandlerDimensions(
HandlerInfo.DEFAULT_HEIGHT,
HandlerInfo.DEFAULT_WIDTH,
HandlerInfo.DEFAULT_MAX_PER_PAGE);
info.setHandlerDimensions(HandlerInfo.DEFAULT_WIDTH, HandlerInfo.DEFAULT_HEIGHT, false);
return info;
}
@@ -3,7 +3,7 @@ package codechicken.nei.recipe;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
public class GuiRecipeTabCreative extends GuiRecipeTab {
public abstract class GuiRecipeTabCreative extends GuiRecipeTab {
public static final int TAB_WIDTH = 28;
public static final int TAB_HEIGHT = 31;
@@ -20,8 +20,8 @@ public class GuiRecipeTabCreative extends GuiRecipeTab {
28,
30).build();
public GuiRecipeTabCreative(GuiRecipe<?> guiRecipe, IRecipeHandler handler, int x, int y) {
super(guiRecipe, handler, x, y);
public GuiRecipeTabCreative(IRecipeHandler handler, int x, int y) {
super(handler, x, y);
}
@Override
@@ -3,7 +3,7 @@ package codechicken.nei.recipe;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
public class GuiRecipeTabJEI extends GuiRecipeTab {
public abstract class GuiRecipeTabJEI extends GuiRecipeTab {
public static final int TAB_WIDTH = 24;
public static final int TAB_HEIGHT = 24;
@@ -20,8 +20,8 @@ public class GuiRecipeTabJEI extends GuiRecipeTab {
24,
24).build();
public GuiRecipeTabJEI(GuiRecipe<?> guiRecipe, IRecipeHandler handler, int x, int y) {
super(guiRecipe, handler, x, y);
public GuiRecipeTabJEI(IRecipeHandler handler, int x, int y) {
super(handler, x, y);
}
@Override
@@ -1,168 +1,154 @@
package codechicken.nei.recipe;
import static codechicken.lib.gui.GuiDraw.getMousePosition;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.Button;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
public class GuiRecipeTabs {
private final GuiRecipe<?> guiRecipe;
private final List<GuiRecipeTab> tabs = new ArrayList<>();
private final List<Button> buttons = new ArrayList<>();
private final Rectangle area = new Rectangle();
private List<? extends IRecipeHandler> currenthandlers;
private int pageCount = 1;
private int pageNumber = 0;
private int categoriesPerPage = 1;
private int numHandlers = 1;
private int tabWidth;
private int tabHeight;
private int recipetype;
public GuiRecipeTabs(GuiRecipe<?> guiRecipe) {
this.guiRecipe = guiRecipe;
}
private final Button prevTab = new Button("<") {
public void initLayout() {
if (NEIClientConfig.useCreativeTabStyle()) {
tabWidth = GuiRecipeTabCreative.TAB_WIDTH;
tabHeight = GuiRecipeTabCreative.TAB_HEIGHT;
} else {
tabWidth = GuiRecipeTabJEI.TAB_WIDTH;
tabHeight = GuiRecipeTabJEI.TAB_HEIGHT;
@Override
public boolean onButtonPress(boolean rightClick) {
if (!rightClick) {
NEIClientUtils.playClickSound();
return previousPage();
} else return false;
}
int totalWidth = 0;
categoriesPerPage = 0;
numHandlers = guiRecipe.currenthandlers.size();
};
for (int i = 0; i < numHandlers; i++) {
if (totalWidth + tabWidth < (guiRecipe.xSize - 4)) {
totalWidth += tabWidth;
categoriesPerPage++;
} else {
break;
}
private final Button nextTab = new Button(">") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
NEIClientUtils.playClickSound();
return nextPage();
} else return false;
}
area.width = totalWidth;
area.height = tabHeight;
area.x = guiRecipe.guiLeft + 4;
area.y = guiRecipe.guiTop - tabHeight + 3;
};
pageCount = (int) Math.ceil((float) numHandlers / categoriesPerPage);
calcPageNumber();
Rectangle navigationArea = new Rectangle(area);
navigationArea.height = 20;
navigationArea.translate(0, -(2 + navigationArea.height));
public static int getTabWidth() {
return NEIClientConfig.useCreativeTabStyle() ? GuiRecipeTabCreative.TAB_WIDTH : GuiRecipeTabJEI.TAB_WIDTH;
}
public void calcPageNumber() {
pageNumber = guiRecipe.recipetype / Math.max(categoriesPerPage, 1);
public static int getTabHeight() {
return NEIClientConfig.useCreativeTabStyle() ? GuiRecipeTabCreative.TAB_HEIGHT : GuiRecipeTabJEI.TAB_HEIGHT;
}
public void update(GuiRecipe<?> guiRecipe) {
final int tabWidth = getTabWidth();
final int tabHeight = getTabHeight();
this.recipetype = guiRecipe.recipetype;
this.currenthandlers = guiRecipe.currenthandlers;
this.numHandlers = this.currenthandlers.size();
this.categoriesPerPage = (guiRecipe.xSize - 4) / tabWidth;
this.pageNumber = this.recipetype / Math.max(this.categoriesPerPage, 1);
this.pageCount = (int) Math.ceil((float) this.numHandlers / this.categoriesPerPage);
this.area.width = this.categoriesPerPage * tabWidth;
this.area.height = tabHeight;
this.area.x = guiRecipe.guiLeft + 4;
this.area.y = guiRecipe.guiTop - tabHeight + 3;
refreshPage();
updateArrows(tabHeight);
}
public void refreshPage() {
tabs.clear();
buttons.clear();
final int startIndex = this.pageNumber * this.categoriesPerPage;
final int tabWidth = getTabWidth();
final int startIndex = pageNumber * categoriesPerPage;
for (int i = 0; i < categoriesPerPage; i++) {
this.tabs.clear();
for (int i = 0; i < this.categoriesPerPage && i + startIndex < numHandlers; i++) {
final int index = i + startIndex;
if (index >= numHandlers) break;
IRecipeHandler handler = guiRecipe.currenthandlers.get(index);
int tabX = area.x + (i * tabWidth);
final IRecipeHandler handler = this.currenthandlers.get(index);
final int tabX = this.area.x + (i * tabWidth);
if (NEIClientConfig.useCreativeTabStyle()) {
tabs.add(new GuiRecipeTabCreative(guiRecipe, handler, tabX, area.y));
tabs.add(new GuiRecipeTabCreative(handler, tabX, this.area.y) {
@Override
public boolean onButtonPress(boolean rightclick) {
setRecipePage(index);
return true;
}
});
} else {
tabs.add(new GuiRecipeTabJEI(guiRecipe, handler, tabX, area.y));
tabs.add(new GuiRecipeTabJEI(handler, tabX, this.area.y) {
@Override
public boolean onButtonPress(boolean rightclick) {
setRecipePage(index);
return true;
}
});
}
}
}
// Maybe add buttons
if (numHandlers > categoriesPerPage) {
Button prevTab = new Button("prevTab") {
private void updateArrows(int tabHeight) {
this.buttons.clear();
@Override
public boolean onButtonPress(boolean rightClick) {
if (!rightClick) {
NEIClientUtils.playClickSound();
return previousPage();
} else return false;
}
if (this.numHandlers > this.categoriesPerPage) {
this.prevTab.w = this.nextTab.w = 8;
this.prevTab.h = this.nextTab.h = tabHeight - 4;
this.prevTab.y = this.nextTab.y = this.area.y + 2;
@Override
public String getRenderLabel() {
return "<";
}
};
prevTab.w = 8;
prevTab.h = tabHeight - 4;
prevTab.x = area.x - prevTab.w + 1;
prevTab.y = area.y + 2;
buttons.add(prevTab);
this.prevTab.x = this.area.x - this.prevTab.w + 1;
this.nextTab.x = this.area.x + this.area.width - 1;
Button nextTab = new Button("nextTab") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
NEIClientUtils.playClickSound();
return nextPage();
} else return false;
}
@Override
public String getRenderLabel() {
return ">";
}
};
nextTab.w = prevTab.w;
nextTab.h = prevTab.h;
nextTab.x = area.x + area.width - 1;
nextTab.y = prevTab.y;
buttons.add(nextTab);
this.buttons.add(this.prevTab);
this.buttons.add(this.nextTab);
}
}
public boolean nextPage() {
if (hasNext()) pageNumber++;
else pageNumber = 0;
protected void setRecipePage(int recipetype) {}
public boolean nextPage() {
this.pageNumber = (this.pageNumber + 1) % this.pageCount;
refreshPage();
return true;
}
public boolean hasNext() {
return pageNumber + 1 < pageCount;
}
public boolean previousPage() {
if (hasPrevious()) pageNumber--;
else pageNumber = pageCount - 1;
this.pageNumber = (this.pageCount + this.pageNumber - 1) % this.pageCount;
refreshPage();
return true;
}
public boolean hasPrevious() {
return pageNumber > 0;
}
public void draw(int mouseX, int mouseY) {
IRecipeHandler current = guiRecipe.currenthandlers.get(guiRecipe.recipetype);
for (GuiRecipeTab tab : tabs) {
tab.setSelected(current);
final int indexShift = this.pageNumber * this.categoriesPerPage;
for (int index = 0; index < this.tabs.size(); index++) {
final GuiRecipeTab tab = this.tabs.get(index);
tab.setSelected(indexShift + index == this.recipetype);
tab.draw(mouseX, mouseY);
}
for (Button button : buttons) {
for (Button button : this.buttons) {
button.draw(mouseX, mouseY);
}
}
@@ -170,12 +156,12 @@ public class GuiRecipeTabs {
public void handleTooltip(int mousex, int mousey, List<String> tooltips) {
if (!NEIClientConfig.areJEIStyleTabsVisible()) return;
for (GuiRecipeTab tab : tabs) {
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(mousex, mousey)) {
tab.addTooltips(tooltips);
}
}
for (Button button : buttons) {
for (Button button : this.buttons) {
if (button.contains(mousex, mousey)) {
button.addTooltips(tooltips);
}
@@ -185,27 +171,26 @@ public class GuiRecipeTabs {
protected boolean mouseClicked(int x, int y, int mouseButton) {
if (!NEIClientConfig.areJEIStyleTabsVisible()) return false;
for (Button button : buttons) {
for (Button button : this.buttons) {
if (button.contains(x, y)) {
return button.onButtonPress(mouseButton == 1);
}
}
for (GuiRecipeTab tab : tabs) {
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(x, y)) {
return tab.onButtonPress(mouseButton == 1);
}
}
return false;
}
protected boolean mouseScrolled(int i) {
Point mousePosition = getMousePosition();
protected boolean mouseScrolled(int scroll) {
// Switch between recipe handlers if the cursor is over the tabbar.
if (NEIClientConfig.areJEIStyleTabsVisible() && area.contains(mousePosition)) {
if (i < 0) guiRecipe.nextType();
else guiRecipe.prevType();
if (NEIClientConfig.areJEIStyleTabsVisible() && this.area.contains(GuiDraw.getMousePosition())) {
setRecipePage(this.recipetype - scroll);
return true;
}
@@ -12,7 +12,6 @@ import codechicken.nei.ItemPanels;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.stackinfo.GTFluidStackStringifyHandler;
public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
@@ -22,9 +21,9 @@ public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
public static boolean openRecipeGui(String inputId, Object... ingredients) {
if ("item".equals(inputId)) {
for (int i = 0; i < ingredients.length; i++) {
ingredients[i] = normalizeItemStack((ItemStack) ingredients[i]);
for (int i = 0; i < ingredients.length; i++) {
if (ingredients[i] instanceof ItemStack stack) {
ingredients[i] = StackInfo.normalizeRecipeQueryStack(stack.copy());
}
}
@@ -66,13 +65,6 @@ public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
return recipeQuery.runWithProfiling(NEIClientUtils.translate("recipe.concurrent.usage"));
}
private static ItemStack normalizeItemStack(ItemStack stack) {
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = true;
stack = StackInfo.loadFromNBT(StackInfo.itemStackToNBT(stack));
GTFluidStackStringifyHandler.replaceAE2FCFluidDrop = false;
return stack;
}
public static void registerUsageHandler(IUsageHandler handler) {
final String handlerId = handler.getHandlerId();
@@ -99,7 +91,7 @@ public class GuiUsageRecipe extends GuiRecipe<IUsageHandler> {
private static IUsageHandler getUsageOrCatalystHandler(IUsageHandler handler, String inputId,
Object... ingredients) {
boolean skipCatalyst = NEIClientUtils.controlKey();
if (NEIClientConfig.areJEIStyleRecipeCatalystsVisible() && !skipCatalyst) {
if (NEIClientConfig.getJEIStyleRecipeCatalysts() != 0 && !skipCatalyst) {
return handler.getUsageAndCatalystHandler(inputId, ingredients);
} else {
return handler.getUsageHandler(inputId, ingredients);
@@ -12,6 +12,8 @@ public class HandlerInfo {
public static int DEFAULT_HEIGHT = 65;
public static int DEFAULT_WIDTH = 166;
@Deprecated
public static int DEFAULT_MAX_PER_PAGE = 1;
private String handlerName;
@@ -21,15 +23,14 @@ public class HandlerInfo {
private boolean requiresMod;
private String excludedModId;
private String itemId;
private String nbtString;
private int yShift = 0;
private int height = DEFAULT_HEIGHT;
private int width = DEFAULT_WIDTH;
private int maxRecipesPerPage = DEFAULT_MAX_PER_PAGE;
private boolean multipleWidgetsAllowed = false;
private boolean showFavoritesButton = true;
private boolean showOverlayButton = true;
private boolean useCustomScroll = false;
private ItemStack itemStack = null;
private DrawableResource image = null;
@@ -42,22 +43,27 @@ public class HandlerInfo {
this.excludedModId = excludedModId;
}
@Deprecated
public void setHandlerDimensions(int height, int width, int maxRecipesPerPage) {
setHandlerDimensions(width, height, maxRecipesPerPage > 1);
}
public void setHandlerDimensions(int width, int height, boolean multipleWidgetsAllowed) {
this.height = height;
this.width = width;
this.maxRecipesPerPage = maxRecipesPerPage;
this.multipleWidgetsAllowed = multipleWidgetsAllowed;
}
public boolean setItem(String itemId, String nbtString) {
if (hasImageOrItem()) return false;
itemStack = NEIServerUtils.getModdedItem(itemId, nbtString);
if (itemStack == null) NEIClientConfig.logger.info("Couldn't find " + modName + " - " + itemId);
else {
this.itemId = itemId;
this.nbtString = nbtString;
this.itemStack = NEIServerUtils.getModdedItem(itemId, nbtString);
if (this.itemStack == null) {
NEIClientConfig.logger.info("Couldn't find " + this.modName + " - " + itemId);
}
return (itemStack != null);
return this.itemStack != null;
}
public boolean setImage(String resourceLocation, int imageX, int imageY, int imageWidth, int imageHeight) {
@@ -68,46 +74,48 @@ public class HandlerInfo {
}
public DrawableResource getImage() {
return image;
return this.image;
}
public ItemStack getItemStack() {
return itemStack;
return this.itemStack;
}
public String getModName() {
return modName;
return this.modName;
}
public String getModId() {
return modId;
return this.modId;
}
public int getHeight() {
return height;
return this.height;
}
public int getWidth() {
return width;
return this.width;
}
@Deprecated
public int getMaxRecipesPerPage() {
return Math.max(maxRecipesPerPage, 1);
return this.multipleWidgetsAllowed ? Integer.MAX_VALUE : 1;
}
public boolean isMultipleWidgetsAllowed() {
return this.multipleWidgetsAllowed;
}
public int getYShift() {
return yShift;
return this.yShift;
}
public String getHandlerName() {
return handlerName;
return this.handlerName;
}
public boolean hasImageOrItem() {
if (image != null) return true;
if (itemStack != null) return true;
return false;
return this.image != null || this.itemStack != null;
}
public void setYShift(int yShift) {
@@ -130,6 +138,14 @@ public class HandlerInfo {
this.showOverlayButton = showOverlayButton;
}
public boolean getUseCustomScroll() {
return this.useCustomScroll;
}
public void setUseCustomScroll(boolean useCustomScroll) {
this.useCustomScroll = useCustomScroll;
}
public static class Builder {
private final HandlerInfo info;
@@ -143,47 +159,72 @@ public class HandlerInfo {
this(handlerClazz.getName(), modName, modId);
}
public Builder setDisplayStack(String itemId, String nbtString) {
return setDisplayStack(NEIServerUtils.getModdedItem(itemId, nbtString));
}
public Builder setDisplayStack(ItemStack stack) {
info.image = null;
info.itemStack = stack;
this.info.image = null;
this.info.itemStack = stack;
return this;
}
public Builder setDisplayImage(DrawableResource drawable) {
info.itemStack = null;
info.image = drawable;
this.info.itemStack = null;
this.info.image = drawable;
return this;
}
public Builder setDisplayImage(ResourceLocation location, int imageX, int imageY, int imageWidth,
int imageHeight) {
info.itemStack = null;
info.setImage(location.toString(), imageX, imageY, imageWidth, imageHeight);
this.info.itemStack = null;
this.info.setImage(location.toString(), imageX, imageY, imageWidth, imageHeight);
return this;
}
public Builder setUseCustomScroll(boolean useCustomScroll) {
this.info.setUseCustomScroll(useCustomScroll);
return this;
}
public Builder setShiftY(int shiftY) {
info.setYShift(shiftY);
this.info.setYShift(shiftY);
return this;
}
public Builder setWidth(int width) {
info.setHandlerDimensions(info.height, width, info.maxRecipesPerPage);
this.info.width = width;
return this;
}
public Builder setHeight(int height) {
info.setHandlerDimensions(height, info.width, info.maxRecipesPerPage);
this.info.height = height;
return this;
}
public Builder setShowOverlayButton(boolean showOverlayButton) {
this.info.showOverlayButton = showOverlayButton;
return this;
}
public Builder setShowFavoritesButton(boolean showFavoritesButton) {
this.info.showFavoritesButton = showFavoritesButton;
return this;
}
@Deprecated
public Builder setMaxRecipesPerPage(int maxRecipesPerPage) {
info.setHandlerDimensions(info.height, info.width, maxRecipesPerPage);
this.info.multipleWidgetsAllowed = maxRecipesPerPage > 1;
return this;
}
public Builder setMultipleWidgetsAllowed(boolean multipleWidgetsAllowed) {
this.info.multipleWidgetsAllowed = multipleWidgetsAllowed;
return this;
}
public HandlerInfo build() {
return info;
return this.info;
}
}
}
@@ -44,6 +44,10 @@ public interface IRecipeHandler {
return getRecipeName();
}
default int getRecipeHeight(int recipe) {
return 0;
}
/**
*
* @return The number of recipes that this handler contains.
@@ -126,12 +130,6 @@ public interface IRecipeHandler {
return null;
}
/**
*
* @return The number of recipes that can fit on a page in the viewer (1 or 2)
*/
int recipiesPerPage();
/**
*
* @param gui An instance of the currentscreen
@@ -178,4 +176,12 @@ public interface IRecipeHandler {
default boolean mouseScrolled(GuiRecipe<?> gui, int scroll, int recipe) {
return false;
}
/**
* @deprecated
* @return The number of recipes that can fit on a page in the viewer (1 or 2)
*/
default int recipiesPerPage() {
return 2;
}
}
@@ -34,13 +34,12 @@ public class InformationHandler extends TemplateRecipeHandler {
@Override
public void drawExtras(int recipe) {
CachedInfoPage page = (CachedInfoPage) this.arecipes.get(recipe);
drawWrappedText(StatCollector.translateToLocal(page.getPage().info).replace("\\n", "\n"), 4, 24);
final CachedInfoPage page = (CachedInfoPage) this.arecipes.get(recipe);
drawWrappedText(page.getLines(), 4, 24);
}
private void drawWrappedText(String text, int x, int y) {
FontRenderer font = Minecraft.getMinecraft().fontRenderer;
List<String> lines = font.listFormattedStringToWidth(text, 156);
private void drawWrappedText(List<String> lines, int x, int y) {
final FontRenderer font = Minecraft.getMinecraft().fontRenderer;
for (String line : lines) {
font.drawString(line, x, y, 0);
y += 10;
@@ -82,14 +81,23 @@ public class InformationHandler extends TemplateRecipeHandler {
return "nei:textures/gui/recipebg.png";
}
@Override
public int getRecipeHeight(int recipe) {
final CachedInfoPage page = (CachedInfoPage) this.arecipes.get(recipe);
return 24 + page.getLines().size() * 10;
}
private class CachedInfoPage extends CachedRecipe {
private final InformationPage page;
private final PositionedStack stack;
private final List<String> lines;
public CachedInfoPage(InformationPage page) {
this.page = page;
stack = new PositionedStack(page.items, 75, 2);
final FontRenderer font = Minecraft.getMinecraft().fontRenderer;
final String info = StatCollector.translateToLocal(page.info).replace("\\n", "\n");
this.lines = font.listFormattedStringToWidth(info, 156);
this.stack = new PositionedStack(page.items, 75, 2);
}
@Override
@@ -99,11 +107,11 @@ public class InformationHandler extends TemplateRecipeHandler {
@Override
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 20, Collections.singletonList(this.stack));
return Collections.singletonList(this.stack);
}
public InformationPage getPage() {
return page;
public List<String> getLines() {
return lines;
}
}
@@ -0,0 +1,549 @@
package codechicken.nei.recipe;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.function.Function;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.Widget;
import codechicken.nei.api.IGuiContainerOverlay;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiRecipeButton.UpdateRecipeButtonsEvent;
import codechicken.nei.util.NEIMouseUtils;
public class NEIRecipeWidget extends Widget {
protected AcceptsFollowingTooltipLineHandler acceptsFollowingTooltipLineHandler;
protected final WeakHashMap<PositionedStack, List<ItemStack>> permutations = new WeakHashMap<>();
protected boolean update = true;
protected int cycleticks = 0;
protected int lastcycle = -1;
protected final RecipeHandlerRef handlerRef;
protected final HandlerInfo handlerInfo;
protected boolean showAsWidget = false;
protected List<GuiRecipeButton> recipeButtons = null;
public NEIRecipeWidget(RecipeHandlerRef handlerRef) {
this.handlerRef = handlerRef;
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.handlerRef.handler);
update();
}
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
public void update() {
if (this.showAsWidget || !this.handlerInfo.getUseCustomScroll()) {
final int recipeHeight = this.handlerRef.handler.getRecipeHeight(this.handlerRef.recipeIndex);
this.w = Math.max(166, this.handlerInfo.getWidth());
this.h = recipeHeight > 0 ? recipeHeight : this.handlerInfo.getHeight();
this.h += this.handlerInfo.getYShift();
}
this.update = true;
}
public List<GuiRecipeButton> getRecipeButtons() {
if (this.recipeButtons == null) {
if (!getOutputs().isEmpty()) {
this.recipeButtons = initButtons();
} else {
this.recipeButtons = Collections.emptyList();
}
}
return Collections.unmodifiableList(this.recipeButtons);
}
protected List<GuiRecipeButton> getRecipeButtonsIfInit() {
if (this.recipeButtons == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(this.recipeButtons);
}
public RecipeHandlerRef getRecipeHandlerRef() {
return this.handlerRef;
}
public Recipe getRecipe() {
return Recipe.of(this.handlerRef);
}
public HandlerInfo getHandlerInfo() {
return this.handlerInfo;
}
public void showAsWidget(boolean show) {
this.showAsWidget = show;
}
protected List<GuiRecipeButton> initButtons() {
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe != null) {
final UpdateRecipeButtonsEvent.Pre preEvent = new UpdateRecipeButtonsEvent.Pre(
guiRecipe,
this,
this.handlerInfo);
if (MinecraftForge.EVENT_BUS.post(preEvent)) {
return preEvent.buttonList;
} else {
final UpdateRecipeButtonsEvent.Post postEvent = new UpdateRecipeButtonsEvent.Post(
guiRecipe,
this,
getDefatulButtons());
MinecraftForge.EVENT_BUS.post(postEvent);
return postEvent.buttonList;
}
} else {
return getDefatulButtons();
}
}
protected List<GuiRecipeButton> getDefatulButtons() {
GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final List<GuiRecipeButton> buttons = new ArrayList<>();
final boolean showFavorites = NEIClientConfig.favoritesEnabled() && handlerInfo.getShowFavoritesButton();
final boolean showOverlay = handlerInfo.getShowOverlayButton();
final int x = Math.min(168, this.w) - GuiRecipeButton.BUTTON_WIDTH;
int y = this.h - GuiRecipeButton.BUTTON_HEIGHT - 6;
if (guiContainer instanceof IGuiContainerOverlay overlay) {
guiContainer = overlay.getFirstScreen();
}
if (showOverlay) {
buttons.add(new GuiOverlayButton(guiContainer, this.handlerRef, x, y));
y -= GuiRecipeButton.BUTTON_HEIGHT + 1;
}
if (showFavorites) {
buttons.add(new GuiFavoriteButton(handlerRef, x, y));
}
return buttons;
}
@Override
public void draw(int mouseX, int mouseY) {
final int yShift = this.handlerInfo.getYShift();
if (this.update) {
this.update = false;
if (!NEIClientUtils.shiftKey() && (this.cycleticks++) / 20 != this.lastcycle || this.lastcycle == -1) {
this.lastcycle = this.cycleticks / 20;
updatePermutations();
}
for (GuiRecipeButton button : getRecipeButtons()) {
button.update();
}
}
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glTranslatef(this.x, this.y + yShift, 0);
this.handlerRef.handler.drawBackground(this.handlerRef.recipeIndex);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glColor4f(1, 1, 1, 1);
GuiContainerManager.enableMatrixStackLogging();
for (PositionedStack pStack : getInputs()) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(pStack.relx, pStack.rely, 16, 16, 0x80FFFFFF));
}
}
for (PositionedStack pStack : getCatalysts()) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(pStack.relx, pStack.rely, 16, 16, 0x80FFFFFF));
}
}
for (PositionedStack pStack : getOutputs()) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(pStack.relx, pStack.rely, 16, 16, 0x80FFFFFF));
}
}
GuiContainerManager.disableMatrixStackLogging();
this.handlerRef.handler.drawForeground(this.handlerRef.recipeIndex);
final GuiRecipeButton overlayButton = getRecipeButtons().stream()
.filter(
b -> this.showAsWidget ? b instanceof GuiOverlayButton
: b.contains(mouseX - this.x, mouseY - this.y - yShift))
.findAny().orElse(null);
if (overlayButton != null && overlayButton.enabled) {
NEIClientUtils.gl2DRenderContext(() -> overlayButton.drawItemOverlay());
}
GL11.glTranslatef(-this.x, -this.y - yShift, 0);
GL11.glPopAttrib();
if (!this.showAsWidget) {
final Minecraft mc = NEIClientUtils.mc();
for (GuiRecipeButton button : getRecipeButtons()) {
button.xPosition += this.x;
button.yPosition += this.y;
button.drawButton(mc, mouseX, mouseY);
button.xPosition -= this.x;
button.yPosition -= this.y;
}
}
LayoutManager.recipeHandlerWidget.drawGuiPlaceholder(this);
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
return false;
}
@Override
public void lastKeyTyped(int keyID, char keyChar) {
final Point mouse = GuiDraw.getMousePosition();
forEachButtons(button -> {
if (button.contains(mouse.x, mouse.y)) {
button.lastKeyTyped(keyChar, keyID);
}
return null;
}, null);
}
@Override
public boolean handleClick(int mouseX, int mouseY, int button) {
if (ShortcutInputHandler.handleMouseClick(getStackMouseOver(mouseX, mouseY))) {
return true;
}
if (button == 0) {
final Minecraft mc = NEIClientUtils.mc();
if (forEachButtons(guibutton -> {
if (guibutton.mousePressed(mc, mouseX, mouseY)) {
NEIClientUtils.playClickSound();
guibutton.mouseReleased(mouseX, mouseY);
return true;
}
return null;
}, false)) {
return true;
}
}
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe == null) {
return false;
}
return this.handlerRef.handler.mouseClicked(guiRecipe, button, this.handlerRef.recipeIndex);
}
@Override
public List<String> handleTooltip(int mouseX, int mouseY, List<String> tooltip) {
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe == null) {
return tooltip;
}
final List<String> localTooltip = this.handlerRef.handler
.handleTooltip(guiRecipe, tooltip, this.handlerRef.recipeIndex);
return forEachButtons(
button -> button.contains(mouseX, mouseY) ? button.handleTooltip(localTooltip) : null,
localTooltip);
}
@Override
public List<String> handleItemTooltip(ItemStack itemstack, int mousex, int mousey, List<String> tooltip) {
final GuiRecipe<?> guiRecipe = getGuiRecipe();
if (guiRecipe == null) {
return tooltip;
}
tooltip = this.handlerRef.handler.handleItemTooltip(guiRecipe, itemstack, tooltip, this.handlerRef.recipeIndex);
if (NEIClientConfig.showCycledIngredientsTooltip() && itemstack != null) {
final int yShift = this.handlerInfo.getYShift();
PositionedStack hovered = null;
for (PositionedStack pStack : getInputs()) {
if (pStack.contains(mousex - this.x, mousey - this.y - yShift)) {
hovered = pStack;
break;
}
}
if (hovered == null) {
for (PositionedStack pStack : getCatalysts()) {
if (pStack.contains(mousex - this.x, mousey - this.y - yShift)) {
hovered = pStack;
}
}
}
if (hovered == null || hovered.items.length <= 1) {
this.acceptsFollowingTooltipLineHandler = null;
} else if (this.acceptsFollowingTooltipLineHandler == null
|| this.acceptsFollowingTooltipLineHandler.tooltipGUID != hovered) {
this.acceptsFollowingTooltipLineHandler = AcceptsFollowingTooltipLineHandler
.of(hovered, hovered.getFilteredPermutations(), hovered.item);
}
} else if (this.acceptsFollowingTooltipLineHandler != null) {
this.acceptsFollowingTooltipLineHandler = null;
}
if (this.acceptsFollowingTooltipLineHandler != null) {
tooltip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.acceptsFollowingTooltipLineHandler));
}
return tooltip;
}
@Override
public Map<String, String> handleHotkeys(int mouseX, int mouseY, Map<String, String> hotkeys) {
final Map<String, String> buttonHotkeys = forEachButtons(
button -> button.contains(mouseX, mouseY) ? button.handleHotkeys(mouseX, mouseY, hotkeys) : null,
hotkeys);
if (this.acceptsFollowingTooltipLineHandler != null) {
buttonHotkeys.put(
NEIClientUtils.getKeyName(
NEIClientUtils.SHIFT_HASH,
NEIMouseUtils.MOUSE_BTN_NONE + NEIMouseUtils.MOUSE_SCROLL),
NEIClientUtils.translate("recipe.accepts.scroll"));
}
return buttonHotkeys;
}
@Override
public boolean onMouseWheel(int scroll, int mx, int my) {
if (forEachButtons(button -> button.contains(mx, my) ? button.mouseScrolled(scroll) : null, false)) {
return true;
}
if (scrollPermutations(scroll, mx, my)) {
return true;
}
final GuiRecipe<?> guiRecipe = getGuiRecipe();
return guiRecipe != null
&& this.handlerRef.handler.mouseScrolled(guiRecipe, scroll, this.handlerRef.recipeIndex);
}
protected boolean scrollPermutations(int scroll, int mx, int my) {
if (!NEIClientUtils.shiftKey()) return false;
final PositionedStack overStack = getPositionedStackMouseOver(mx, my);
if (overStack != null && overStack.items.length > 1) {
final List<ItemStack> items = overStack.getFilteredPermutations();
final int stackIndex = indexOf(items, overStack.item);
final ItemStack stack = items.get((items.size() - scroll + stackIndex) % items.size());
Stream.concat(getInputs().stream(), getCatalysts().stream()).filter(pStack -> pStack.containsWithNBT(stack))
.forEach(pStack -> pStack.setPermutationToRender(stack));
if (this.acceptsFollowingTooltipLineHandler != null) {
this.acceptsFollowingTooltipLineHandler
.setActiveStack(((PositionedStack) this.acceptsFollowingTooltipLineHandler.tooltipGUID).item);
}
return true;
}
return false;
}
protected int indexOf(List<ItemStack> list, ItemStack stack) {
for (int i = 0; i < list.size(); i++) {
if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(list.get(i), stack)) {
return i;
}
}
return -1;
}
protected <R> R forEachButtons(Function<GuiRecipeButton, R> callback, R defaultValue) {
for (GuiRecipeButton button : getRecipeButtonsIfInit()) {
button.xPosition += this.x;
button.yPosition += this.y;
final R result = callback.apply(button);
button.xPosition -= this.x;
button.yPosition -= this.y;
if (result != null) {
return result;
}
}
return defaultValue;
}
public boolean isFocusedRecipe(int mx, int my) {
final int yShift = this.handlerInfo.getYShift();
for (PositionedStack pStackOver : getOutputs()) {
if (pStackOver.contains(mx - this.x, my - this.y - yShift)) {
return true;
}
}
return false;
}
public PositionedStack getPositionedStackMouseOver(int mx, int my) {
final int yShift = this.handlerInfo.getYShift();
for (PositionedStack pStack : getInputs()) {
if (pStack.contains(mx - this.x, my - this.y - yShift)) {
return pStack;
}
}
for (PositionedStack pStack : getCatalysts()) {
if (pStack.contains(mx - this.x, my - this.y - yShift)) {
return pStack;
}
}
for (PositionedStack pStack : getOutputs()) {
if (pStack.contains(mx - this.x, my - this.y - yShift)) {
return pStack;
}
}
return null;
}
@Override
public ItemStack getStackMouseOver(int mx, int my) {
final PositionedStack pStack = getPositionedStackMouseOver(mx, my);
return pStack != null ? pStack.item : null;
}
protected GuiRecipe<?> getGuiRecipe() {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
if (guiContainer instanceof GuiRecipe<?>guiRecipe) {
return guiRecipe;
}
return null;
}
protected GuiContainer getFirstGui() {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
if (guiContainer instanceof GuiRecipe<?>guiRecipe) {
return guiRecipe.firstGui;
}
return guiContainer;
}
protected void updatePermutations() {
for (PositionedStack pStack : getInputs()) {
if (pStack.items.length > 1) {
final List<ItemStack> permutations = this.permutations
.computeIfAbsent(pStack, stack -> stack.getFilteredPermutations(FavoriteRecipes::contains));
pStack.setPermutationToRender(permutations.get(this.lastcycle % permutations.size()));
}
}
for (PositionedStack pStack : getCatalysts()) {
if (pStack.items.length > 1) {
final List<ItemStack> permutations = this.permutations
.computeIfAbsent(pStack, stack -> stack.getFilteredPermutations(FavoriteRecipes::contains));
pStack.setPermutationToRender(permutations.get(this.lastcycle % permutations.size()));
}
}
if (this.acceptsFollowingTooltipLineHandler != null) {
this.acceptsFollowingTooltipLineHandler
.setActiveStack(((PositionedStack) this.acceptsFollowingTooltipLineHandler.tooltipGUID).item);
}
}
protected List<PositionedStack> getInputs() {
return this.handlerRef.handler.getIngredientStacks(this.handlerRef.recipeIndex);
}
protected List<PositionedStack> getOutputs() {
final PositionedStack pStackResult = this.handlerRef.handler.getResultStack(this.handlerRef.recipeIndex);
return pStackResult != null ? Arrays.asList(pStackResult)
: this.handlerRef.handler.getOtherStacks(this.handlerRef.recipeIndex);
}
protected List<PositionedStack> getCatalysts() {
if (this.handlerRef.handler.getResultStack(this.handlerRef.recipeIndex) == null) {
return Collections.emptyList();
}
return this.handlerRef.handler.getOtherStacks(this.handlerRef.recipeIndex);
}
}
@@ -102,11 +102,6 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
return null;
}
@Override
public int recipiesPerPage() {
return 1;
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip, int recipe) {
return currenttip;
@@ -18,6 +18,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.ItemInfo;
@@ -235,7 +236,8 @@ public class Recipe {
return false;
}
if (this.result != null && anRecipeId.result != null
if (isShapedRecipe() && this.result != null
&& anRecipeId.result != null
&& !StackInfo.equalItemAndNBT(this.result, anRecipeId.result, true)) {
return false;
}
@@ -311,7 +313,8 @@ public class Recipe {
}
public boolean contains(ItemStack stackA) {
return getPermutations().stream().anyMatch(stackB -> StackInfo.equalItemAndNBT(stackA, stackB, true));
return getPermutations().stream()
.anyMatch(stackB -> NEIClientUtils.areStacksSameTypeWithNBT(stackB, stackA));
}
public List<ItemStack> getPermutations() {
@@ -17,6 +17,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraft.item.ItemStack;
@@ -37,10 +38,8 @@ public class RecipeCatalysts {
private static final Map<String, List<ItemStack>> catalystsRemoverFromAPI = new HashMap<>();
public static final Map<String, CatalystInfoList> catalystsAdderFromIMC = new HashMap<>();
public static final Map<String, List<ItemStack>> catalystsRemoverFromIMC = new HashMap<>();
private static final Map<String, CatalystInfoList> recipeCatalystMap = new HashMap<>();
private static Map<String, List<PositionedStack>> positionedRecipeCatalystMap = new HashMap<>();
private static final Map<String, List<PositionedStack>> recipeCatalystMap = new HashMap<>();
private static final List<String> forceClassNameList = new ArrayList<>();
private static int heightCache;
public static void addRecipeCatalyst(String handlerID, CatalystInfo catalystInfo) {
if (handlerID == null || handlerID.isEmpty() || catalystInfo.getStack() == null) return;
@@ -49,6 +48,7 @@ public class RecipeCatalysts {
public static void removeRecipeCatalyst(String handlerID, ItemStack stack) {
if (handlerID == null || handlerID.isEmpty() || stack == null) return;
if (catalystsRemoverFromAPI.containsKey(handlerID)) {
catalystsRemoverFromAPI.get(handlerID).add(stack);
} else {
@@ -56,8 +56,23 @@ public class RecipeCatalysts {
}
}
public static Map<String, List<PositionedStack>> getPositionedRecipeCatalystMap() {
return positionedRecipeCatalystMap;
public static void putRecipeCatalysts(String handlerID, List<ItemStack> items) {
if (handlerID == null || handlerID.isEmpty()) return;
final CatalystInfoList catalystInfoList = new CatalystInfoList(handlerID);
int stackIndex = 0;
for (ItemStack stack : items) {
catalystInfoList.add(new CatalystInfo(stack, stackIndex++));
}
putRecipeCatalysts(handlerID, catalystInfoList);
}
public static void putRecipeCatalysts(String handlerID, CatalystInfoList catalystInfoList) {
if (handlerID == null || handlerID.isEmpty()) return;
catalystsAdderFromAPI.put(handlerID, catalystInfoList);
recipeCatalystMap.put(handlerID, convertToPositionedStackList(catalystInfoList));
}
public static List<PositionedStack> getRecipeCatalysts(IRecipeHandler handler) {
@@ -65,10 +80,7 @@ public class RecipeCatalysts {
}
public static List<PositionedStack> getRecipeCatalysts(String handlerID) {
if (!NEIClientConfig.areJEIStyleTabsVisible() || !NEIClientConfig.areJEIStyleRecipeCatalystsVisible()) {
return Collections.emptyList();
}
return positionedRecipeCatalystMap.getOrDefault(handlerID, Collections.emptyList());
return recipeCatalystMap.getOrDefault(handlerID, Collections.emptyList());
}
public static boolean containsCatalyst(IRecipeHandler handler, ItemStack candidate) {
@@ -76,63 +88,21 @@ public class RecipeCatalysts {
}
public static boolean containsCatalyst(String handlerID, ItemStack candidate) {
if (recipeCatalystMap.containsKey(handlerID)) {
return recipeCatalystMap.get(handlerID).contains(candidate);
return recipeCatalystMap.get(handlerID).stream().anyMatch(pStack -> pStack.contains(candidate));
}
return false;
}
public static void updatePosition(int availableHeight, boolean force) {
if (availableHeight == heightCache && !force) return;
Map<String, List<PositionedStack>> newMap = new HashMap<>();
for (Map.Entry<String, CatalystInfoList> entry : recipeCatalystMap.entrySet()) {
CatalystInfoList catalysts = entry.getValue();
catalysts.sort();
List<PositionedStack> newStacks = new ArrayList<>();
int rowCount = getRowCount(availableHeight, catalysts.size());
for (int index = 0; index < catalysts.size(); index++) {
ItemStack catalyst = catalysts.get(index).getStack();
int column = index / rowCount;
int row = index % rowCount;
newStacks.add(
new PositionedStack(
catalyst,
-column * GuiRecipeCatalyst.ingredientSize,
row * GuiRecipeCatalyst.ingredientSize));
}
newMap.put(entry.getKey(), newStacks);
}
positionedRecipeCatalystMap = newMap;
heightCache = availableHeight;
}
public static void updatePosition(int availableHeight) {
updatePosition(availableHeight, false);
}
public static int getHeight() {
return heightCache;
}
public static int getColumnCount(int availableHeight, int catalystsSize) {
int maxItemsPerColumn = availableHeight / GuiRecipeCatalyst.ingredientSize;
return NEIServerUtils.divideCeil(catalystsSize, maxItemsPerColumn);
}
public static int getRowCount(int availableHeight, int catalystsSize) {
int columnCount = getColumnCount(availableHeight, catalystsSize);
return NEIServerUtils.divideCeil(catalystsSize, columnCount);
}
public static void loadCatalystInfo() {
final boolean fromJar = NEIClientConfig.loadCatalystsFromJar();
final URL handlerUrl = RecipeCatalysts.class.getResource("/assets/nei/csv/catalysts.csv");
final Map<String, CatalystInfoList> calculatedCatalysts = new HashMap<>();
NEIClientConfig.logger.info("Loading catalyst info from " + (fromJar ? "JAR" : "Config"));
recipeCatalystMap.clear();
URL handlerUrl = RecipeCatalysts.class.getResource("/assets/nei/csv/catalysts.csv");
resolveAdderQueue();
resolveAdderQueue(calculatedCatalysts);
URL url;
if (fromJar) {
@@ -211,7 +181,7 @@ public class RecipeCatalysts {
// Prefer info added by API if we're using default jar config.
// If not, user config overwrites it.
addOrPut(recipeCatalystMap, handlerID, catalystInfo, !fromJar);
addOrPut(calculatedCatalysts, handlerID, catalystInfo, !fromJar);
}
} catch (Exception e) {
NEIClientConfig.logger.warn("Error parsing CSV");
@@ -219,13 +189,17 @@ public class RecipeCatalysts {
}
if (fromJar) {
resolveRemoverQueue();
resolveRemoverQueue(calculatedCatalysts);
}
recipeCatalystMap.clear();
for (Map.Entry<String, CatalystInfoList> entry : calculatedCatalysts.entrySet()) {
recipeCatalystMap.put(entry.getKey(), convertToPositionedStackList(entry.getValue()));
}
updatePosition(getHeight(), true);
}
private static void resolveAdderQueue() {
private static void resolveAdderQueue(Map<String, CatalystInfoList> recipeCatalystMap) {
for (Map.Entry<String, CatalystInfoList> entry : catalystsAdderFromAPI.entrySet()) {
String handlerID = entry.getKey();
for (CatalystInfo catalyst : entry.getValue()) {
@@ -256,7 +230,7 @@ public class RecipeCatalysts {
}
}
private static void resolveRemoverQueue() {
private static void resolveRemoverQueue(Map<String, CatalystInfoList> recipeCatalystMap) {
for (Map.Entry<String, List<ItemStack>> entry : catalystsRemoverFromAPI.entrySet()) {
String handlerID = entry.getKey();
if (recipeCatalystMap.containsKey(handlerID)) {
@@ -308,16 +282,49 @@ public class RecipeCatalysts {
}
}
private static List<PositionedStack> convertToPositionedStackList(CatalystInfoList catalystInfoList) {
catalystInfoList.sort();
return catalystInfoList.stream().filter(catalyst -> catalyst.getStack() != null)
.map(catalyst -> new PositionedStack(catalyst.getStack(), 0, 0, false)).collect(Collectors.toList());
}
@Deprecated
public static void addRecipeCatalyst(List<ItemStack> stacks, Class<? extends IRecipeHandler> handler) {}
@Deprecated
public static List<PositionedStack> getRecipeCatalysts(Class<? extends IRecipeHandler> handler) {
return Collections.emptyList();
return new ArrayList<>();
}
@Deprecated
public static boolean containsCatalyst(Class<? extends IRecipeHandler> handler, ItemStack candidate) {
return false;
}
@Deprecated
public static Map<String, List<PositionedStack>> getPositionedRecipeCatalystMap() {
return new HashMap<>();
}
@Deprecated
public static void updatePosition(int availableHeight, boolean force) {}
@Deprecated
public static void updatePosition(int availableHeight) {}
@Deprecated
public static int getHeight() {
return 1;
}
@Deprecated
public static int getColumnCount(int availableHeight, int catalystsSize) {
return 1;
}
@Deprecated
public static int getRowCount(int availableHeight, int catalystsSize) {
return 1;
}
}
@@ -61,6 +61,10 @@ public class RecipeHandlerRef {
return firstGui != null && firstGui.inventorySlots != null ? firstGui : null;
}
public NEIRecipeWidget getRecipeWidget() {
return new NEIRecipeWidget(this);
}
public IOverlayHandler getOverlayHandler(GuiContainer gui) {
final GuiContainer firstGui = prepareGui(gui);
@@ -14,6 +14,7 @@ import codechicken.nei.ItemPanels;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
@@ -37,23 +38,16 @@ public class RecipeItemInputHandler implements IContainerInputHandler, IContaine
@Override
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
if (!(gui instanceof GuiRecipe) || ItemPanels.itemPanel.contains(mousex, mousey)
|| ItemPanels.bookmarkPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.historyPanel.contains(mousex, mousey))
return false;
return ShortcutInputHandler.handleMouseClick(GuiContainerManager.getStackMouseOver(gui));
return false;
}
@Override
public Map<String, String> handleHotkeys(GuiContainer gui, int mousex, int mousey, Map<String, String> hotkeys) {
if ((gui instanceof GuiRecipe) || ItemPanels.itemPanel.contains(mousex, mousey)
|| ItemPanels.bookmarkPanel.contains(mousex, mousey)
|| ItemPanels.itemPanel.historyPanel.contains(mousex, mousey)) {
if (gui instanceof GuiRecipe || ItemPanels.itemPanel.containsWithSubpanels(mousex, mousey)
|| ItemPanels.bookmarkPanel.contains(mousex, mousey)) {
hotkeys.putAll(
ShortcutInputHandler
.handleHotkeys(gui, mousex, mousey, GuiContainerManager.getStackMouseOver(gui)));
ShortcutInputHandler.handleHotkeys(mousex, mousey, GuiContainerManager.getStackMouseOver(gui)));
}
return hotkeys;
@@ -88,7 +82,7 @@ public class RecipeItemInputHandler implements IContainerInputHandler, IContaine
final BookmarksGridSlot slot = ItemPanels.bookmarkPanel.getSlotMouseOver(mousex, mousey);
if (slot != null && slot.getRecipeId() != null
&& !slot.isIngredient()
&& slot.getType() != BookmarkItemType.INGREDIENT
&& NEIClientConfig.getRecipeTooltipsMode() != 0) {
final int tooltipMode = NEIClientConfig.getRecipeTooltipsMode();
final BookmarkViewMode viewMode = slot.getGroup().viewMode;
@@ -0,0 +1,158 @@
package codechicken.nei.recipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.Widget;
import codechicken.nei.scroll.ScrollContainer;
public class RecipePageManager {
private SearchRecipeHandler<?> handler;
private ScrollContainer container;
private HandlerInfo handlerInfo;
private String cacheKey = "";
private int currentPageIndex = -1;
private List<Integer> recipeIndices = new ArrayList<>();
private List<List<Widget>> pageWidgets = new ArrayList<>();
public RecipePageManager(SearchRecipeHandler<?> handler, HandlerInfo handlerInfo, ScrollContainer container) {
this.handler = handler;
this.handlerInfo = handlerInfo;
this.container = container;
rebuildPages();
}
public boolean rebuildPages() {
final String cacheKey = handlerInfo.getHandlerName() + ":"
+ getNumRecipes()
+ ":"
+ this.container.getVisibleHeight()
+ ":"
+ GuiRecipe.searchField.text();
if (cacheKey.equals(this.cacheKey)) {
return false;
}
this.cacheKey = cacheKey;
this.pageWidgets.clear();
final boolean useCustomScroll = this.handlerInfo.getUseCustomScroll();
final int handlerHeight = this.handlerInfo.getHeight() + this.handlerInfo.getYShift();
final boolean multipleWidgetsAllowed = !useCustomScroll && handlerInfo.isMultipleWidgetsAllowed();
final boolean infiniteScroll = !useCustomScroll
&& NEIClientConfig.getBooleanSetting("inventory.guirecipe.infiniteScroll");
final int heightAvailable = this.container.getVisibleHeight();
final int width = Math.max(166, this.handlerInfo.getWidth());
final int numRecipes = getNumRecipes();
List<Widget> widgets = new ArrayList<>();
int shiftY = 0;
for (int i = 0; i < numRecipes; i++) {
final int recipeIndex = this.handler.ref(i);
final NEIRecipeWidget widget = RecipeHandlerRef.of(this.handler.original, recipeIndex).getRecipeWidget();
widget.w = width;
if (useCustomScroll) {
widget.h = Math.min(handlerHeight, heightAvailable);
}
if (!widgets.isEmpty()
&& (!multipleWidgetsAllowed || !infiniteScroll && shiftY + widget.h > heightAvailable)) {
this.pageWidgets.add(widgets);
widgets = new ArrayList<>();
shiftY = 0;
}
widgets.add(widget);
shiftY += widget.h;
}
if (!widgets.isEmpty()) {
this.pageWidgets.add(widgets);
}
changePage(0);
return true;
}
public boolean isMultipleWidgetsAllowed() {
return !this.handlerInfo.getUseCustomScroll() && this.handlerInfo.isMultipleWidgetsAllowed();
}
public int getNumRecipes() {
return this.handler.numRecipes();
}
public int getCurrentPageIndex() {
return this.currentPageIndex;
}
public int getNumPages() {
return this.pageWidgets.size();
}
public void changePage(int delta) {
final int numPages = getNumPages();
final int page = numPages > 0 ? (numPages + Math.max(0, this.currentPageIndex) + delta) % numPages : 0;
if (this.currentPageIndex == page) {
return;
}
this.currentPageIndex = page;
this.recipeIndices = new ArrayList<>();
for (Widget widget : getCurrentPageWidgets()) {
if (widget instanceof NEIRecipeWidget recipeWidget) {
this.recipeIndices.add(recipeWidget.getRecipeHandlerRef().recipeIndex);
}
}
this.container.setVerticalScrollOffset(0);
}
public void gotoRefIndex(int refIndex) {
int page = 0;
for (int i = 0; i < this.pageWidgets.size(); i++) {
refIndex -= this.pageWidgets.get(i).size();
if (refIndex < 0) {
page = i;
break;
}
}
changePage(page);
}
public List<Widget> getCurrentPageWidgets() {
if (this.pageWidgets.isEmpty()) {
return Collections.emptyList();
}
List<Widget> currentWidgets = this.pageWidgets.get(this.currentPageIndex);
int shiftY = 0;
for (Widget widget : currentWidgets) {
if (widget instanceof NEIRecipeWidget recipeWidget) {
recipeWidget.setLocation(0, shiftY);
}
shiftY += widget.h;
}
return currentWidgets;
}
public List<Integer> getRecipeIndices() {
return this.recipeIndices;
}
}
@@ -1,23 +1,34 @@
package codechicken.nei.recipe;
import java.awt.Dimension;
import java.util.List;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.gui.GuiDraw.ITooltipLineHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.scroll.GuiHelper;
public class RecipeTooltipLineHandler implements ITooltipLineHandler {
private static final int BG_PADDING = 5;
private static final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/gui/recipebg.png",
0,
0,
176,
166).build();
protected long lastUpdate = System.currentTimeMillis();
protected String recipeName = "";
protected GuiRecipe<?> gui = null;
protected RecipeHandlerRef handlerRef = null;
protected NEIRecipeWidget widget = null;
protected RecipeId recipeId = null;
protected boolean createdGui = false;
@@ -36,19 +47,22 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
@Override
public Dimension getSize() {
if (this.gui == null && !this.createdGui) {
this.gui = GuiCraftingRecipe.createRecipeGui("recipeId", false, this.recipeId.getResult(), this.recipeId);
if (this.widget == null && !this.createdGui) {
this.handlerRef = RecipeHandlerRef.of(this.recipeId);
this.createdGui = true;
if (this.gui != null) {
this.gui.initGui();
this.gui.guiTop = 0;
this.gui.guiLeft = 0;
if (handlerRef != null) {
this.widget = new NEIRecipeWidget(this.handlerRef);
this.widget.showAsWidget(true);
this.widget.x = BG_PADDING;
this.widget.y = BG_PADDING + 12;
this.recipeName = this.widget.getRecipeHandlerRef().handler.getRecipeName().trim();
}
}
if (this.gui != null) {
return this.gui.getWidgetSize();
if (this.widget != null) {
return new Dimension(this.widget.w + BG_PADDING * 2, this.widget.h + BG_PADDING * 2 + 12);
}
return new Dimension(0, 0);
@@ -56,41 +70,40 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
@Override
public void draw(int x, int y) {
if (this.gui == null) return;
if (this.widget == null) return;
if ((System.currentTimeMillis() - lastUpdate) > 50) {
lastUpdate = System.currentTimeMillis();
this.gui.onUpdate();
this.handlerRef.handler.onUpdate();
this.widget.update();
}
GL11.glPushMatrix();
GL11.glScaled(1, 1, 3);
GL11.glTranslatef(x, y, 0);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
RenderHelper.disableStandardItemLighting();
final Dimension size = getSize();
this.gui.drawGuiContainerBackgroundLayer(0.0f, -100, -100);
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
final int zTranslation = GuiContainerManager.TOOLTIP_Z_OFFSET;
GL11.glTranslatef(x, y, zTranslation);
GuiContainerManager.enable2DRender();
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(0, 0, size.width, size.height, BG_PADDING, BG_PADDING, BG_PADDING, BG_PADDING);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GuiDraw.drawRect(BG_PADDING, BG_PADDING, size.width - BG_PADDING * 2, 12, 0x30000000);
GuiDraw.drawStringC(this.recipeName, this.widget.w / 2, BG_PADDING + 2, 0xffffff);
GuiHelper.useScissor(
this.widget.x,
this.widget.y,
this.widget.w,
this.widget.h,
() -> { this.widget.draw(0, 0); });
GL11.glPopAttrib();
if (this.gui.slotcontainer != null) {
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glDisable(GL11.GL_DEPTH_TEST);
List<Slot> slots = this.gui.slotcontainer.inventorySlots;
for (Slot slot : slots) {
if (slot != null && slot.getStack() != null) {
GuiContainerManager.drawItem(slot.xDisplayPosition, slot.yDisplayPosition, slot.getStack());
}
}
GL11.glPopAttrib();
}
this.gui.drawGuiContainerForegroundLayer(-100, -100);
GL11.glPopMatrix();
GL11.glTranslatef(-x, -y, -zTranslation);
}
}
@@ -1,6 +1,7 @@
package codechicken.nei.recipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.IntPredicate;
@@ -23,16 +24,16 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
this.original = handler;
if (this.original.numRecipes() == 0) {
this.filteredRecipes = new ArrayList<>();
this.filteredRecipes = Collections.emptyList();
} else {
final Stream<Integer> items = IntStream.range(0, this.original.numRecipes()).boxed();
final IRecipeFilter filter = this.searchingAvailable() ? GuiRecipe.getRecipeListFilter() : null;
if (filter == null) {
this.filteredRecipes = items.collect(Collectors.toCollection(ArrayList::new));
this.filteredRecipes = items.collect(Collectors.toList());
} else {
this.filteredRecipes = items.filter(recipe -> mathRecipe(this.original, recipe, filter))
.collect(Collectors.toCollection(ArrayList::new));
.collect(Collectors.toList());
}
}
}
@@ -54,7 +54,7 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler {
@Override
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 20, ingredients);
return ingredients;
}
public PositionedStack getResult() {
@@ -64,7 +64,7 @@ public class ShapelessRecipeHandler extends ShapedRecipeHandler {
@Override
public List<PositionedStack> getIngredients() {
return getCycledIngredients(cycleticks / 20, ingredients);
return ingredients;
}
@Override
@@ -76,6 +76,16 @@ public class StackInfo {
return stack;
}
public static ItemStack normalizeRecipeQueryStack(ItemStack stack) {
ItemStack result = null;
for (int i = stackStringifyHandlers.size() - 1; i >= 0 && result == null; i--) {
result = stackStringifyHandlers.get(i).normalizeRecipeQueryStack(stack);
}
return result == null ? stack : result;
}
public static void pauseItemDamageSound(boolean pause) {
if (isPausedItemDamageSound != (isPausedItemDamageSound = pause)) {
for (IStackStringifyHandler handler : stackStringifyHandlers) {
@@ -9,13 +9,11 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.init.Blocks;
@@ -31,8 +29,6 @@ import org.lwjgl.opengl.GL11;
import com.google.common.base.Stopwatch;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
@@ -178,43 +174,16 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
return null;
}
/**
* This will perform default cycling of ingredients, mulitItem capable
*
* @param cycle Current cycle step
* @param ingredients List of ItemStacks to cycle
* @return The provided list of ingredients, with their permutations cycled to a different permutation, if one
* is available
*/
@Deprecated
public List<PositionedStack> getCycledIngredients(int cycle, List<PositionedStack> ingredients) {
if (!NEIClientUtils.shiftKey() && !disableCycledIngredients) {
randomRenderPermutation(ingredients, cycle);
}
return ingredients;
}
public void randomRenderPermutation(List<PositionedStack> stacks, long cycle) {
cycle = NEIClientConfig.useJEIStyledCycledIngredients() ? cycle
: Math.abs(new Random(cycle + offset).nextInt());
for (PositionedStack pStack : stacks) {
if (pStack.items.length <= 1) continue;
final List<ItemStack> items = pStack.getFilteredPermutations(FavoriteRecipes::contains);
pStack.setPermutationToRender(items.get((int) (cycle % items.size())));
}
}
@Deprecated
public void randomRenderPermutation(List<PositionedStack> stacks, long cycle) {}
@Deprecated
public void randomRenderPermutation(PositionedStack stack, long cycle) {
cycle = NEIClientConfig.useJEIStyledCycledIngredients() ? cycle
: Math.abs(new Random(cycle + offset).nextInt());
if (stack.items.length <= 1) return;
final List<ItemStack> items = stack.getFilteredPermutations(FavoriteRecipes::contains);
stack.setPermutationToRender(items.get((int) (cycle % items.size())));
}
public void randomRenderPermutation(PositionedStack stack, long cycle) {}
public void setIngredientPermutation(Collection<PositionedStack> ingredients, ItemStack ingredient) {
for (PositionedStack stack : ingredients) {
@@ -406,8 +375,6 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
*/
public LinkedList<RecipeTransferRect> transferRects = new LinkedList<>();
public static boolean disableCycledIngredients = true;
public TemplateRecipeHandler() {
loadTransferRects();
RecipeTransferRectHandler.registerRectsToGuis(getRecipeTransferRectGuis(), transferRects);
@@ -641,7 +608,7 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
}
public void onUpdate() {
if (!NEIClientUtils.shiftKey()) cycleticks++;
cycleticks++;
}
public boolean hasOverlay(GuiContainer gui, Container container, int recipe) {
@@ -660,11 +627,6 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
return RecipeInfo.getOverlayHandler(gui, getOverlayIdentifier());
}
@Override
public int recipiesPerPage() {
return 2;
}
@Override
public List<String> handleTooltip(GuiRecipe<?> gui, List<String> currenttip, int recipe) {
if (GuiContainerManager.shouldShowTooltip(gui) && currenttip.isEmpty()) {
@@ -705,49 +667,9 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
@Override
public boolean mouseScrolled(GuiRecipe<?> gui, int scroll, int recipe) {
if (!NEIClientUtils.shiftKey()) return false;
final Point pos = GuiDraw.getMousePosition();
final Point offset = gui.getRecipePosition(recipe);
final Point relMouse = new Point(pos.x - gui.guiLeft - offset.x, pos.y - gui.guiTop - offset.y);
final PositionedStack overStack = getIngredientMouseOver(relMouse.x, relMouse.y, recipe);
if (overStack != null && overStack.items.length > 1) {
final List<ItemStack> items = overStack.getFilteredPermutations();
final int stackIndex = getPermutationIndex(overStack.item, items);
final ItemStack stack = items.get((items.size() - scroll + stackIndex) % items.size());
if (NEIClientConfig.useJEIStyledCycledIngredients()) {
Stream.concat(getIngredientStacks(recipe).stream(), getOtherStacks(recipe).stream())
.filter(pStack -> pStack.containsWithNBT(stack))
.forEach(pStack -> pStack.setPermutationToRender(stack));
} else {
overStack.setPermutationToRender(stack);
}
return true;
}
return false;
}
private int getPermutationIndex(ItemStack stack, List<ItemStack> items) {
for (int index = 0; index < items.size(); index++) {
if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(items.get(index), stack)) {
return index;
}
}
return -1;
}
private PositionedStack getIngredientMouseOver(int mousex, int mousey, int recipe) {
return Stream.concat(getIngredientStacks(recipe).stream(), getOtherStacks(recipe).stream())
.filter(pStack -> new Rectangle4i(pStack.relx, pStack.rely, 18, 18).contains(mousex, mousey))
.findFirst().orElse(null);
}
private boolean transferRect(GuiRecipe<?> gui, int recipe, boolean usage) {
Point offset = gui.getRecipePosition(recipe);
return transferRect(gui, transferRects, offset.x, offset.y, usage);
@@ -16,6 +16,7 @@ import net.minecraft.nbt.NBTTagCompound;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
@@ -52,20 +53,12 @@ public class RecipeChainMath {
private final List<ItemStack> containerItemsBlacklist = new ArrayList<>();
private RecipeChainMath(List<BookmarkItem> recipeItems, Set<RecipeId> collapsedRecipes) {
final Map<RecipeId, Integer> recipeState = new HashMap<>();
final Map<RecipeId, Long> multipliers = new HashMap<>();
for (BookmarkItem item : recipeItems) {
if (item.recipeId != null) {
recipeState
.put(item.recipeId, recipeState.getOrDefault(item.recipeId, 0) | (item.isIngredient ? 1 : 2));
}
}
for (BookmarkItem item : recipeItems) {
if (recipeState.getOrDefault(item.recipeId, 0) != 3) {
if (item.recipeId == null || item.type == BookmarkItemType.ITEM) {
this.initialItems.add(item.copy());
} else if (item.isIngredient) {
} else if (item.type == BookmarkItemType.INGREDIENT) {
this.recipeIngredients.add(item.copyWithAmount(0));
} else {
this.recipeResults.add(item.copyWithAmount(0));
@@ -209,7 +202,7 @@ public class RecipeChainMath {
item.getItemStack(amount),
item.getStackSize(amount),
ROOT_RECIPE_ID,
true,
BookmarkItemType.INGREDIENT,
BookmarkItem.generatePermutations(item.itemStack, null)));
}
}
@@ -217,7 +210,7 @@ public class RecipeChainMath {
this.outputRecipes.clear();
this.outputRecipes.put(ROOT_RECIPE_ID, 1L);
this.recipeResults.removeIf(item -> ROOT_RECIPE_ID.equals(item.recipeId));
this.recipeResults.add(BookmarkItem.of(-1, ROOT_ITEM, 1, ROOT_RECIPE_ID, false));
this.recipeResults.add(BookmarkItem.of(-1, ROOT_ITEM, 1, ROOT_RECIPE_ID, BookmarkItemType.RESULT));
this.recipeIngredients.addAll(rootIngredients);
return ROOT_RECIPE_ID;
@@ -236,7 +229,7 @@ public class RecipeChainMath {
final RecipeId recipeId = recipe.getRecipeId();
final ItemStack result = recipe.getResult();
chainItems.add(BookmarkItem.of(-1, result, StackInfo.getAmount(result), recipeId, false));
chainItems.add(BookmarkItem.of(-1, result, StackInfo.getAmount(result), recipeId, BookmarkItemType.RESULT));
for (RecipeIngredient ingr : recipe.getIngredients()) {
chainItems.add(
@@ -245,7 +238,7 @@ public class RecipeChainMath {
ingr.getItemStack(),
ingr.getAmount(),
recipeId,
true,
BookmarkItemType.INGREDIENT,
BookmarkItem.generatePermutations(ingr.getItemStack(), recipe)));
}
@@ -406,14 +399,46 @@ public class RecipeChainMath {
ItemStack itemStack = prefItem.itemStack;
while (ingrAmount > 0 && shiftAmount < maxAmount) {
long multiplier = 1;
itemStack = itemStack.copy();
itemStack.stackSize = 1;
this.containerItems.add(itemStack);
ingrAmount = shiftContainerItems(itemStack, prefItem.getStackSize(ingrAmount))
* prefItem.fluidCellAmount;
shiftAmount += prefItem.fluidCellAmount;
if (ingrAmount > 0) {
long steps = prefItem.getStackSize(ingrAmount);
final ContainerItemResult result = getToolsContainerItems(itemStack, steps);
if (result.stack == null) {
multiplier = steps / (steps - result.leftSteps);
steps = steps % (steps - result.leftSteps);
} else {
steps = result.leftSteps;
}
if (result.containerItem != null) {
long stackSize = result.containerItem.stackSize * multiplier;
while (stackSize > Integer.MAX_VALUE) {
final ItemStack copy = result.containerItem.copy();
copy.stackSize = Integer.MAX_VALUE;
this.containerItems.add(copy);
stackSize -= copy.stackSize;
}
result.containerItem.stackSize = (int) stackSize;
this.containerItems.add(result.containerItem);
}
if (result.stack != null) {
this.containerItems.add(result.stack);
}
ingrAmount = steps * prefItem.fluidCellAmount;
}
shiftAmount += multiplier * prefItem.fluidCellAmount;
}
} else {
@@ -429,8 +454,9 @@ public class RecipeChainMath {
}
private long shiftContainerItems(ItemStack aStack, long steps) {
final int initialSize = this.containerItems.size();
for (int i = 0; i < this.containerItems.size() && steps > 0; i++) {
for (int i = 0; i < initialSize && steps > 0; i++) {
ItemStack bStack = this.containerItems.get(i);
if (bStack != null && NEIClientUtils.areStacksSameTypeCraftingWithNBT(aStack, bStack)) {
@@ -463,12 +489,12 @@ public class RecipeChainMath {
final NBTTagCompound toolStats = tagCompound.getCompoundTag("GT.ToolStats");
final long maxDamage = toolStats.getLong("MaxDamage");
final long damage = toolStats.getLong("Damage");
final long leftSteps = (maxDamage - damage) / damagePerContainerCraft;
final long leftSteps = (long) Math.ceil((maxDamage - damage) / (double) damagePerContainerCraft);
final long availableSteps = Math.min(steps, Math.max(1, leftSteps));
steps -= availableSteps;
if ((damage + availableSteps * damagePerContainerCraft) == maxDamage || leftSteps <= 0) {
if ((damage + availableSteps * damagePerContainerCraft) >= maxDamage || leftSteps <= 0) {
aStack = null;
} else {
toolStats.setLong("Damage", damage + availableSteps * damagePerContainerCraft);
@@ -170,13 +170,13 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler {
inputs.sort(
Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null)
.thenComparing(ItemSorter.instance));
.thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance));
outputs.sort(
Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null)
.thenComparing(ItemSorter.instance));
.thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance));
remainder.sort(
Comparator.comparing((ItemStack stack) -> StackInfo.getFluid(stack) != null)
.thenComparing(ItemSorter.instance));
.thenComparingInt(stack -> -1 * stack.stackSize).thenComparing(ItemSorter.instance));
this.inputs = new ItemsTooltipLineHandler(
this.lastShiftKey ? NEIClientUtils.translate("bookmark.crafting_chain.missing")
@@ -208,6 +208,8 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler {
this.available.setLabelColor(EnumChatFormatting.GREEN);
}
this.size.height = this.size.width = 0;
if (!this.inputs.isEmpty() || !this.outputs.isEmpty()
|| !this.remainder.isEmpty()
|| !this.available.isEmpty()) {
@@ -225,8 +227,6 @@ public class RecipeChainTooltipLineHandler implements ITooltipLineHandler {
this.size.height += this.inputs.getSize().height + this.outputs.getSize().height
+ this.remainder.getSize().height
+ this.available.getSize().height;
} else {
this.size.height = this.size.width = 0;
}
}
@@ -19,9 +19,8 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
protected static Class<?> itemFluidDisplay = null;
protected static Method getFluidDisplayStack = null;
protected static Method getFluidFromDisplayStack = null;
public static boolean replaceAE2FCFluidDrop = false;
private static Class<?> gtMetaGeneratedTool = null;
private static Field playSound = null;
protected static Class<?> gtMetaGeneratedTool = null;
protected static Field playSound = null;
static {
try {
@@ -48,7 +47,7 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
public NBTTagCompound convertItemStackToNBT(ItemStack stack, boolean saveStackSize) {
if (replaceAE2FCFluidDrop || stack.getItem() != GameRegistry.findItem("ae2fc", "fluid_drop")) {
if (stack.getItem() != GameRegistry.findItem("ae2fc", "fluid_drop")) {
final FluidStack fluidStack = getFluid(stack);
if (fluidStack != null) {
@@ -69,14 +68,11 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
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) {}
if (fluid != null) {
try {
return (ItemStack) getFluidDisplayStack.invoke(null, new FluidStack(fluid, amount), true);
} catch (Exception e) {}
}
}
return null;
@@ -114,6 +110,22 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
return null;
}
public ItemStack normalizeRecipeQueryStack(ItemStack stack) {
if (stack.getItem() == GameRegistry.findItem("ae2fc", "fluid_drop")
|| stack.getItem() == GameRegistry.findItem("ae2fc", "fluid_packet")) {
final FluidStack fluidStack = getFluid(stack);
if (fluidStack != null) {
try {
return (ItemStack) getFluidDisplayStack.invoke(null, fluidStack, true);
} catch (Exception e) {}
}
}
return null;
}
@Override
public void pauseItemDamageSound(boolean pause) {
if (playSound != null) {
@@ -0,0 +1,131 @@
package codechicken.nei.scroll;
import java.nio.FloatBuffer;
import java.util.Stack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiHelper {
private static final Stack<int[]> scissorFrameStack = new Stack<>();
public static void useScissor(int x, int y, int width, int height, Runnable codeBlock) {
pushScissorFrame(x, y, width, height);
try {
codeBlock.run();
} finally {
popScissorFrame();
}
}
private static int[] peekFirstScissorOrFullScreen() {
final int[] currentTopFrame = scissorFrameStack.isEmpty() ? null : scissorFrameStack.peek();
if (currentTopFrame == null) {
final Minecraft minecraft = Minecraft.getMinecraft();
return new int[] { 0, 0, minecraft.displayWidth, minecraft.displayHeight };
}
return currentTopFrame;
}
private static void pushScissorFrame(int x, int y, int width, int height) {
int[] matrix = prepareMatrix(x, y, width, height);
int[] parentScissor = peekFirstScissorOrFullScreen();
int parentX = parentScissor[0];
int parentY = parentScissor[1];
int parentWidth = parentScissor[2];
int parentHeight = parentScissor[3];
boolean pushedFrame = false;
x = matrix[0];
y = matrix[1];
width = matrix[2];
height = matrix[3];
if (x <= parentX + parentWidth && y <= parentY + parentHeight) {
int newX = Math.max(x, parentX);
int newY = Math.max(y, parentY);
int newWidth = width - (newX - x);
int newHeight = height - (newY - y);
if (newWidth > 0 && newHeight > 0) {
int maxWidth = parentWidth - (x - parentX);
int maxHeight = parentHeight - (y - parentY);
newWidth = Math.min(maxWidth, newWidth);
newHeight = Math.min(maxHeight, newHeight);
applyScissor(newX, newY, newWidth, newHeight);
// finally, push applied scissor on top of scissor stack
if (scissorFrameStack.isEmpty()) {
GL11.glEnable(GL11.GL_SCISSOR_TEST);
}
scissorFrameStack.push(new int[] { newX, newY, newWidth, newHeight });
pushedFrame = true;
}
}
if (!pushedFrame) {
if (scissorFrameStack.isEmpty()) {
GL11.glEnable(GL11.GL_SCISSOR_TEST);
}
scissorFrameStack.push(new int[] { parentX, parentY, parentWidth, parentHeight });
}
}
public static void popScissorFrame() {
scissorFrameStack.pop();
int[] parentScissor = peekFirstScissorOrFullScreen();
int parentX = parentScissor[0];
int parentY = parentScissor[1];
int parentWidth = parentScissor[2];
int parentHeight = parentScissor[3];
applyScissor(parentX, parentY, parentWidth, parentHeight);
if (scissorFrameStack.isEmpty()) {
GL11.glDisable(GL11.GL_SCISSOR_TEST);
}
}
// applies scissor with gui-space coordinates and sizes
private static void applyScissor(int x, int y, int w, int h) {
// translate upper-left to bottom-left
final Minecraft mc = Minecraft.getMinecraft();
final ScaledResolution res = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
final int scaleFactor = res.getScaleFactor();
final int translatedY = mc.displayHeight - (y + h) * scaleFactor;
GL11.glScissor(x * scaleFactor, translatedY, w * scaleFactor, h * scaleFactor);
}
private static int[] prepareMatrix(int x, int y, int w, int h) {
// Get the current translation component to support the Gui being drawn at any position on the screen
final FloatBuffer matBuf = BufferUtils.createFloatBuffer(16);
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matBuf);
final float xScale = matBuf.get(0);
final float yScale = matBuf.get(5);
final int xTranslate = (int) (matBuf.get(12) / xScale);
final int yTranslate = (int) (matBuf.get(13) / yScale);
x += xTranslate;
y += yTranslate;
x *= xScale;
y *= yScale;
w *= xScale;
h *= yScale;
return new int[] { x, y, w, h };
}
}
@@ -0,0 +1,436 @@
package codechicken.nei.scroll;
import java.awt.Color;
import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
public class ScrollBar {
/** The minimum length of the scrollbar cursor. */
private static final int MINIMUM_THUMB_SIZE = 6;
private static final Color BACKGROUND_COLOR = new Color(0x90B1D4E0);
private static final Color THUMB_COLOR = new Color(0xF0145DA0);
private static final Color THUMB_SELECTED_COLOR = new Color(0xF02E8BC0);
public enum ScrollType {
HORIZONTAL,
VERTICAL
}
public enum OverflowType {
NONE,
AUTO,
SCROLL,
OVERLAY
}
public enum ScrollPlace {
START,
END
}
private ScrollType scrollType = ScrollType.VERTICAL;
private OverflowType overflowType = OverflowType.SCROLL;
private ScrollPlace scrollPlace = ScrollPlace.END;
private float handleClickOffset = -1;
private int trackWidth = 6;
private int thumbPaddingLeft = 0;
private int thumbPaddingRight = 0;
private int thumbPaddingTop = 0;
private int thumbPaddingBottom = 0;
private int trackPaddingLeft = 0;
private int trackPaddingRight = 0;
private int trackPaddingTop = 0;
private int trackPaddingBottom = 0;
private DrawableResource thumbTexture;
private int thumbSliceStart;
private int thumbSliceEnd;
private DrawableResource trackTexture;
private int trackSliceStart;
private int trackSliceEnd;
public static ScrollBar defaultScrollBar() {
return new ScrollBar();
}
public static ScrollBar defaultVerticalBar() {
return new ScrollBar().setTrackWidth(8)
.setTrackTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 29, 95, 8, 11).build(), 3, 4)
.setThumbTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 22, 96, 6, 9).build(), 3, 2)
.setThumbPadding(1, 1, 1, 1);
}
public static ScrollBar defaultHorizontalBar() {
return new ScrollBar().setTrackWidth(8).setOverflowType(OverflowType.SCROLL)
.setTrackTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 0, 97, 11, 8).build(), 3, 4)
.setThumbTexture(new DrawableBuilder("nei:textures/nei_sprites.png", 12, 98, 9, 6).build(), 3, 2)
.setThumbPadding(1, 1, 1, 1);
}
/**
* Sets the size of the scrollbar without texture in the non-scrolling axis (width for vertical, height for
* horizontal).
*
* @param trackWidth
* @return
*/
public ScrollBar setTrackWidth(int trackWidth) {
this.trackWidth = trackWidth;
return this;
}
public ScrollBar setTrackPadding(int left, int top, int right, int bottom) {
this.trackPaddingLeft = left;
this.trackPaddingRight = right;
this.trackPaddingTop = top;
this.trackPaddingBottom = bottom;
return this;
}
public ScrollBar setThumbPadding(int left, int top, int right, int bottom) {
this.thumbPaddingLeft = left;
this.thumbPaddingRight = right;
this.thumbPaddingTop = top;
this.thumbPaddingBottom = bottom;
return this;
}
public int getTrackWidth() {
if (this.trackTexture != null) {
return this.scrollType == ScrollType.HORIZONTAL ? this.trackTexture.getHeight()
: this.trackTexture.getWidth();
}
return this.trackWidth;
}
protected int getThumbWidth() {
if (this.thumbTexture != null) {
return this.scrollType == ScrollType.HORIZONTAL ? this.thumbTexture.getHeight()
: this.thumbTexture.getWidth();
}
return getTrackWidth();
}
public ScrollBar setThumbTexture(DrawableResource texture, int sliceStart, int sliceEnd) {
this.thumbTexture = texture;
this.thumbSliceStart = sliceStart;
this.thumbSliceEnd = sliceEnd;
return this;
}
public ScrollBar setTrackTexture(DrawableResource texture, int sliceStart, int sliceEnd) {
this.trackTexture = texture;
this.trackSliceStart = sliceStart;
this.trackSliceEnd = sliceEnd;
return this;
}
public ScrollBar setOverflowType(OverflowType overflowType) {
this.overflowType = overflowType;
return this;
}
public OverflowType getOverflowType() {
return this.overflowType;
}
public ScrollBar setScrollPlace(ScrollPlace scrollPlace) {
this.scrollPlace = scrollPlace;
return this;
}
public ScrollPlace getScrollPlace() {
return this.scrollPlace;
}
public ScrollBar setScrollType(ScrollType scrollType) {
this.scrollType = scrollType;
return this;
}
private int getActualSize(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.getActualWidth();
} else {
return container.getActualHeight();
}
}
public int getVisibleSize(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.getVisibleWidth();
} else {
return container.getVisibleHeight();
}
}
private int getMaxThumbSize(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return getMaxTrackSize(container) - this.thumbPaddingLeft - this.thumbPaddingRight;
} else {
return getMaxTrackSize(container) - this.thumbPaddingTop - this.thumbPaddingBottom;
}
}
private int getMaxTrackSize(ScrollContainer container) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.w - this.trackPaddingLeft - this.trackPaddingRight;
} else {
return container.h - this.trackPaddingTop - this.trackPaddingBottom;
}
}
private int getMinThumbSize() {
if (this.thumbTexture != null) {
return this.scrollType == ScrollType.HORIZONTAL ? this.thumbTexture.getWidth()
: this.thumbTexture.getHeight();
}
return MINIMUM_THUMB_SIZE;
}
public float getScrollOffset(ScrollContainer container) {
final float thumbSize = getMaxThumbSize(container) - calculateMainAxisSize(container);
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.getHorizontalScrollOffset()
/ (float) (container.getActualWidth() - container.getVisibleWidth())
* thumbSize;
} else {
return container.getVerticalScrollOffset()
/ (float) (container.getActualHeight() - container.getVisibleHeight())
* thumbSize;
}
}
public float calculateMainAxisSize(ScrollContainer container) {
final int visibleSize = getVisibleSize(container);
final int actualSize = getActualSize(container);
final int trackSize = getMaxThumbSize(container);
return Math.max(Math.min(trackSize, (trackSize / (float) actualSize) * visibleSize), getMinThumbSize());
}
public Rectangle4i trackBounds(ScrollContainer container) {
int trackWidth = getTrackWidth();
if (this.scrollType == ScrollType.HORIZONTAL) {
final int y = this.scrollPlace == ScrollPlace.START ? container.y - trackWidth - this.trackPaddingBottom
: container.y + container.h + this.trackPaddingTop;
return new Rectangle4i(container.x + this.trackPaddingLeft, y, getMaxTrackSize(container), trackWidth);
} else {
final int x = this.scrollPlace == ScrollPlace.START ? container.x - trackWidth - this.trackPaddingRight
: container.x + container.w + this.trackPaddingLeft;
return new Rectangle4i(x, container.y + this.trackPaddingTop, trackWidth, getMaxTrackSize(container));
}
}
public Rectangle4i thumbBounds(ScrollContainer container) {
final int mainAxisSize = (int) calculateMainAxisSize(container);
final int offset = (int) Math.ceil(getScrollOffset(container));
final Rectangle4i bounds = trackBounds(container);
if (this.scrollType == ScrollType.HORIZONTAL) {
final int y = this.scrollPlace == ScrollPlace.START
? bounds.y + bounds.h - getThumbWidth() - this.thumbPaddingBottom
: bounds.y + this.thumbPaddingTop;
return new Rectangle4i(
bounds.x + this.thumbPaddingLeft + offset,
y,
mainAxisSize,
bounds.h - this.thumbPaddingTop - this.thumbPaddingBottom);
} else {
final int x = this.scrollPlace == ScrollPlace.START
? bounds.x + bounds.w - getThumbWidth() - this.thumbPaddingRight
: bounds.x + this.thumbPaddingLeft;
return new Rectangle4i(
x,
bounds.y + this.thumbPaddingTop + offset,
bounds.w - this.thumbPaddingLeft - this.thumbPaddingRight,
mainAxisSize);
}
}
public boolean setScrollOffset(ScrollContainer container, int offset) {
if (this.scrollType == ScrollType.HORIZONTAL) {
return container.setHorizontalScrollOffset(offset);
} else {
return container.setVerticalScrollOffset(offset);
}
}
public boolean onClick(ScrollContainer container, int mx, int my, int button) {
final Rectangle4i bounds = trackBounds(container);
if (bounds.contains(mx, my)) {
final float mainAxisSize = calculateMainAxisSize(container);
final float thumbSize = getMaxThumbSize(container) - mainAxisSize;
final Rectangle4i thumbBounds = thumbBounds(container);
if (this.scrollType == ScrollType.HORIZONTAL) {
final int relativeX = mx - bounds.x - this.thumbPaddingLeft;
if (mx < thumbBounds.x || mx > thumbBounds.x + thumbBounds.w) {
this.handleClickOffset = mainAxisSize / 2;
} else {
this.handleClickOffset = mx - thumbBounds.x;
}
final float newOffset = ((relativeX - this.handleClickOffset)
* (container.getActualWidth() - container.getVisibleWidth())) / thumbSize;
container.setHorizontalScrollOffset((int) newOffset);
} else {
final int relativeY = my - bounds.y - this.thumbPaddingTop;
if (my < thumbBounds.y || my > thumbBounds.y + thumbBounds.h) {
this.handleClickOffset = mainAxisSize / 2f;
} else {
this.handleClickOffset = my - thumbBounds.y;
}
final float newOffset = ((relativeY - this.handleClickOffset)
* (container.getActualHeight() - container.getVisibleHeight())) / thumbSize;
container.setVerticalScrollOffset((int) newOffset);
}
return true;
}
return false;
}
public boolean onMouseDragged(ScrollContainer container, int mx, int my, int buttonId, long heldTime) {
if (this.handleClickOffset >= 0) {
final Rectangle4i bounds = trackBounds(container);
final float mainAxisSize = calculateMainAxisSize(container);
final float thumbSize = getMaxThumbSize(container) - mainAxisSize;
if (this.scrollType == ScrollType.HORIZONTAL) {
final int relativeX = mx - bounds.x - this.thumbPaddingLeft;
final float newOffset = ((relativeX - this.handleClickOffset)
* (container.getActualWidth() - container.getVisibleWidth())) / thumbSize;
container.setHorizontalScrollOffset((int) newOffset);
} else {
int relativeY = my - bounds.y - this.thumbPaddingTop;
final float newOffset = ((relativeY - this.handleClickOffset)
* (container.getActualHeight() - container.getVisibleHeight())) / thumbSize;
container.setVerticalScrollOffset((int) newOffset);
}
return true;
}
return false;
}
public boolean onClickReleased(ScrollContainer container, int mx, int my, int buttonId) {
if (this.handleClickOffset >= 0) {
this.handleClickOffset = -1;
return true;
}
return false;
}
public boolean isMouseDragged() {
return this.handleClickOffset >= 0;
}
public void draw(ScrollContainer container, int mx, int my, float opacity) {
if (opacity <= 0 && this.overflowType == OverflowType.OVERLAY) {
return;
}
if (this.overflowType != OverflowType.OVERLAY) {
opacity = 1;
}
final Rectangle4i trackBounds = trackBounds(container);
final Rectangle4i thumbBounds = thumbBounds(container);
final boolean selected = isMouseDragged() || thumbBounds.contains(mx, my);
final boolean disabled = getVisibleSize(container) >= getActualSize(container);
if (this.trackTexture != null) {
drawTexture(this.trackTexture, this.trackSliceStart, this.trackSliceEnd, trackBounds, false, opacity);
} else {
drawTrackRect(container, trackBounds, opacity);
}
if (this.thumbTexture != null) {
drawTexture(this.thumbTexture, this.thumbSliceStart, this.thumbSliceEnd, thumbBounds, disabled, opacity);
} else {
drawThumbRect(container, thumbBounds, selected, opacity);
}
}
private void drawTrackRect(ScrollContainer container, Rectangle4i bounds, float opacity) {
final float trackSize = this.trackWidth / 3f;
final Color trackColor = new Color(
BACKGROUND_COLOR.getRed(),
BACKGROUND_COLOR.getGreen(),
BACKGROUND_COLOR.getBlue(),
(int) (BACKGROUND_COLOR.getAlpha() * opacity));
if (this.scrollType == ScrollType.HORIZONTAL) {
NEIClientUtils.drawRect(bounds.x, bounds.y + trackSize, bounds.w, trackSize, trackColor);
} else {
NEIClientUtils.drawRect(bounds.x + trackSize, bounds.y, trackSize, bounds.h, trackColor);
}
}
private void drawThumbRect(ScrollContainer container, Rectangle4i bounds, boolean selected, float opacity) {
final Color color = selected ? THUMB_SELECTED_COLOR : THUMB_COLOR;
final Color thumbColor = new Color(
color.getRed(),
color.getGreen(),
color.getBlue(),
(int) (color.getAlpha() * opacity));
NEIClientUtils.drawRect(bounds.x, bounds.y, bounds.w, bounds.h, thumbColor);
}
private void drawTexture(DrawableResource texture, int sliceStart, int sliceEnd, Rectangle4i bounds,
boolean disabled, float opacity) {
final float c = disabled ? 0.65f : 1f;
GL11.glColor4f(c, c, c, opacity);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if (this.scrollType == ScrollType.HORIZONTAL) {
texture.draw(bounds.x, bounds.y, bounds.w, texture.getHeight(), sliceStart, sliceEnd, 0, 0);
} else {
texture.draw(bounds.x, bounds.y, texture.getWidth(), bounds.h, 0, 0, sliceStart, sliceEnd);
}
}
}
@@ -0,0 +1,408 @@
package codechicken.nei.scroll;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.Widget;
import codechicken.nei.WidgetContainer;
import codechicken.nei.scroll.ScrollBar.OverflowType;
import codechicken.nei.scroll.ScrollBar.ScrollType;
public class ScrollContainer extends WidgetContainer {
/** The mouse scroll wheel scroll speed */
protected static final int MOUSE_SCROLL_SPEED = 16;
/** The keyboard arrow keys scroll speed */
protected static final int KEYBOARD_SCROLL_SPEED = 36;
/** The scrollbar will fade away over this many ticks */
protected static final int FADE_TICKS = 24;
protected int xScroll = 0;
protected int yScroll = 0;
protected int actualWidth = 0;
protected int actualHeight = 0;
protected int paddingInlineStart = 0;
protected int paddingInlineEnd = 0;
protected int paddingBlockStart = 0;
protected int paddingBlockEnd = 0;
protected final Map<Widget, Point> relativePostion = new HashMap<>();
protected ScrollBar horizontalScrollBar;
protected ScrollBar verticalScrollBar;
protected int fade = 0;
public Rectangle4i boundsOutside() {
int width = this.w;
int height = this.h;
int x = this.x;
int y = this.y;
if (canScrollVertical() && (this.verticalScrollBar.getOverflowType() == OverflowType.SCROLL
|| this.verticalScrollBar.getOverflowType() == OverflowType.AUTO)) {
final Rectangle4i trackBounds = this.verticalScrollBar.trackBounds(this);
x = Math.min(x, trackBounds.x);
y = Math.min(y, trackBounds.y);
height = Math.max(this.y + height, trackBounds.y + trackBounds.h) - y;
width = Math.max(this.x + width, trackBounds.x + trackBounds.w) - x;
}
if (canScrollHorizontal() && (this.horizontalScrollBar.getOverflowType() == OverflowType.SCROLL
|| this.horizontalScrollBar.getOverflowType() == OverflowType.AUTO)) {
final Rectangle4i trackBounds = this.horizontalScrollBar.trackBounds(this);
x = Math.min(x, trackBounds.x);
y = Math.min(y, trackBounds.y);
height = Math.max(this.y + height, trackBounds.y + trackBounds.h) - y;
width = Math.max(this.x + width, trackBounds.x + trackBounds.w) - x;
}
return new Rectangle4i(x, y, width, height);
}
public Rectangle4i boundsInside() {
return new Rectangle4i(
x + this.paddingInlineStart,
y + this.paddingBlockStart,
getVisibleWidth(),
getVisibleHeight());
}
@Override
public void clear() {
super.clear();
this.relativePostion.clear();
}
@Override
public boolean removeIf(Predicate<Widget> filter) {
this.relativePostion.keySet().removeIf(filter);
return super.removeIf(filter);
}
public void addWidget(Widget widget) {
super.addWidget(widget);
this.relativePostion.put(widget, new Point(widget.x, widget.y));
}
public Point getWidgetPosition(Widget widget) {
return this.relativePostion.get(widget);
}
public void setPaddingInline(int start, int end) {
this.paddingInlineStart = start;
this.paddingInlineEnd = end;
}
public void setPaddingBlock(int start, int end) {
this.paddingBlockStart = start;
this.paddingBlockEnd = end;
}
public int getVisibleWidth() {
return this.w - this.paddingInlineStart - this.paddingInlineEnd;
}
public int getActualWidth() {
return this.actualWidth;
}
public boolean setHorizontalScrollOffset(int offset) {
if (!canScrollHorizontal() && getVisibleWidth() < getActualWidth()) {
offset = 0;
}
final int scroll = this.xScroll;
this.xScroll = Math.max(0, Math.min(getActualWidth() - getVisibleWidth(), offset));
if (scroll != this.xScroll) {
for (Widget widget : this.widgets) {
widget.x += scroll - this.xScroll;
}
this.fade = FADE_TICKS;
return true;
}
return false;
}
public int getHorizontalScrollOffset() {
return this.xScroll;
}
public boolean canScrollHorizontal() {
return this.horizontalScrollBar != null && (this.horizontalScrollBar.getOverflowType() != OverflowType.NONE
&& getVisibleWidth() < getActualWidth()
|| this.horizontalScrollBar.getOverflowType() == OverflowType.SCROLL);
}
public ScrollBar getHorizontalScroll() {
return this.horizontalScrollBar;
}
public ScrollContainer setHorizontalScroll() {
return setHorizontalScroll(ScrollBar.defaultScrollBar());
}
public ScrollContainer setHorizontalScroll(ScrollBar scrollBar) {
this.horizontalScrollBar = scrollBar;
if (this.horizontalScrollBar != null) {
this.horizontalScrollBar.setScrollType(ScrollType.HORIZONTAL);
}
return this;
}
public int getVisibleHeight() {
return this.h - this.paddingBlockStart - this.paddingBlockEnd;
}
public int getActualHeight() {
return this.actualHeight;
}
public boolean setVerticalScrollOffset(int offset) {
if (!canScrollVertical() && getVisibleHeight() < getActualHeight()) {
offset = 0;
}
final int scroll = this.yScroll;
this.yScroll = Math.max(0, Math.min(getActualHeight() - getVisibleHeight(), offset));
if (scroll != this.yScroll) {
for (Widget widget : this.widgets) {
widget.y += scroll - this.yScroll;
}
this.fade = FADE_TICKS;
return true;
}
return false;
}
public int getVerticalScrollOffset() {
return this.yScroll;
}
public boolean canScrollVertical() {
return this.verticalScrollBar != null && (this.verticalScrollBar.getOverflowType() != OverflowType.NONE
&& getVisibleHeight() < getActualHeight()
|| this.verticalScrollBar.getOverflowType() == OverflowType.SCROLL);
}
public ScrollBar getVerticalScroll() {
return this.verticalScrollBar;
}
public ScrollContainer setVerticalScroll() {
return setVerticalScroll(ScrollBar.defaultScrollBar());
}
public ScrollContainer setVerticalScroll(ScrollBar scrollBar) {
this.verticalScrollBar = scrollBar;
if (this.verticalScrollBar != null) {
this.verticalScrollBar.setScrollType(ScrollType.VERTICAL);
}
return this;
}
@Override
public void draw(int mousex, int mousey) {
final boolean canScrollVertical = canScrollVertical();
final boolean canScrollHorizontal = canScrollHorizontal();
if (canScrollVertical || canScrollHorizontal) {
GuiHelper.useScissor(
this.x + this.paddingInlineStart,
this.y + this.paddingBlockStart,
this.w - this.paddingInlineStart - this.paddingInlineEnd,
this.h - this.paddingBlockStart - this.paddingBlockEnd,
() -> drawContent(mousex, mousey));
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
if (canScrollVertical) {
this.verticalScrollBar.draw(this, mousex, mousey, getScrollBarOpacity());
}
if (canScrollHorizontal) {
this.horizontalScrollBar.draw(this, mousex, mousey, getScrollBarOpacity());
}
GL11.glPopAttrib();
} else {
drawContent(mousex, mousey);
}
}
protected void drawContent(int mousex, int mousey) {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glPushMatrix();
GL11.glColor4f(1, 1, 1, 1);
super.draw(mousex, mousey);
GL11.glPopMatrix();
GL11.glPopAttrib();
}
private float getScrollBarOpacity() {
return Math.min(2f * this.fade, FADE_TICKS) / FADE_TICKS;
}
@Override
public void update() {
this.actualHeight = 0;
this.actualWidth = 0;
for (Map.Entry<Widget, Point> entry : this.relativePostion.entrySet()) {
entry.getKey().x = entry.getValue().x;
entry.getKey().y = entry.getValue().y;
}
super.update();
final int x = this.x + this.paddingInlineStart - this.xScroll;
final int y = this.y + this.paddingBlockStart - this.yScroll;
for (Widget widget : this.widgets) {
this.actualWidth = Math.max(this.actualWidth, widget.x + widget.w);
this.actualHeight = Math.max(this.actualHeight, widget.y + widget.h);
widget.x += x;
widget.y += y;
}
if (this.fade > 0) {
final Point mouse = GuiDraw.getMousePosition();
if (canScrollVertical() && (this.verticalScrollBar.isMouseDragged()
|| this.verticalScrollBar.trackBounds(this).contains(mouse.x, mouse.y))) {
this.fade = FADE_TICKS;
} else if (canScrollHorizontal() && (this.horizontalScrollBar.isMouseDragged()
|| this.horizontalScrollBar.trackBounds(this).contains(mouse.x, mouse.y))) {
this.fade = FADE_TICKS;
} else {
this.fade--;
}
}
setHorizontalScrollOffset(this.xScroll);
setVerticalScrollOffset(this.yScroll);
}
@Override
public boolean onMouseWheel(int direction, int mousex, int mousey) {
if (super.onMouseWheel(direction, mousex, mousey)) {
return true;
}
if (boundsOutside().contains(mousex, mousey)) {
if (canScrollHorizontal() && (NEIClientUtils.shiftKey()
|| this.horizontalScrollBar.trackBounds(this).contains(mousex, mousey))) {
this.horizontalScrollBar.setScrollOffset(this, this.xScroll - direction * MOUSE_SCROLL_SPEED);
return true;
}
if (canScrollVertical()) {
this.verticalScrollBar.setScrollOffset(this, this.yScroll - direction * MOUSE_SCROLL_SPEED);
return true;
}
}
return false;
}
@Override
public boolean handleClick(int mousex, int mousey, int button) {
if (canScrollVertical() && this.verticalScrollBar.onClick(this, mousex, mousey, button)) {
return true;
}
if (canScrollHorizontal() && this.horizontalScrollBar.onClick(this, mousex, mousey, button)) {
return true;
}
if (super.handleClick(mousex, mousey, button)) {
return true;
}
return false;
}
@Override
public void mouseDragged(int mousex, int mousey, int button, long heldTime) {
if (canScrollVertical() && this.verticalScrollBar.onMouseDragged(this, mousex, mousey, button, heldTime)) {
return;
}
if (canScrollHorizontal() && this.horizontalScrollBar.onMouseDragged(this, mousex, mousey, button, heldTime)) {
return;
}
super.mouseDragged(mousex, mousey, button, heldTime);
}
@Override
public void mouseUp(int mousex, int mousey, int button) {
if (canScrollVertical()) {
this.verticalScrollBar.onClickReleased(this, mousex, mousey, button);
}
if (canScrollHorizontal()) {
this.horizontalScrollBar.onClickReleased(this, mousex, mousey, button);
}
super.mouseUp(mousex, mousey, button);
}
@Override
public boolean handleKeyPress(int keyCode, char keyChar) {
if (this.isFocused()) {
switch (keyCode) {
case Keyboard.KEY_UP:
return canScrollVertical()
&& this.verticalScrollBar.setScrollOffset(this, this.yScroll - KEYBOARD_SCROLL_SPEED);
case Keyboard.KEY_DOWN:
return canScrollVertical()
&& this.verticalScrollBar.setScrollOffset(this, this.yScroll + KEYBOARD_SCROLL_SPEED);
case Keyboard.KEY_LEFT:
return canScrollHorizontal()
&& this.horizontalScrollBar.setScrollOffset(this, this.xScroll - KEYBOARD_SCROLL_SPEED);
case Keyboard.KEY_RIGHT:
return canScrollHorizontal()
&& this.horizontalScrollBar.setScrollOffset(this, this.xScroll + KEYBOARD_SCROLL_SPEED);
}
}
return super.handleKeyPress(keyCode, keyChar);
}
}
@@ -20,7 +20,7 @@ import codechicken.nei.api.ItemFilter;
public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilter> {
private static final Pattern REGEX_ESCAPED_SPACE_PATTERN = Pattern.compile("([^\\\\](?:\\\\\\\\)+)?\\\\ ");
private static final Pattern PLAIN_TEXT_ESCAPED_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_SYMBOL_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
private static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
@@ -69,21 +69,21 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
@Override
public ItemFilter visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
if (ctx.token() != null) {
final String cleanText = getTokenCleanText(ctx.token());
final String cleanPattern = getCleanPattern(ctx.token());
final SearchTokenParser.ISearchParserProvider provider = searchParser.getProvider(ctx.token().prefix);
if (cleanText == null || provider == null) {
if (cleanPattern == null || provider == null) {
return defaultResult();
}
return provider.getFilter(cleanText);
return provider.getFilter(cleanPattern);
}
return defaultResult();
}
@Override
public ItemFilter visitToken(SearchExpressionParser.TokenContext ctx) {
final String cleanText = getTokenCleanText(ctx);
if (cleanText != null) {
return getAlwaysProvidersFilter(cleanText);
final String cleanPattern = getCleanPattern(ctx);
if (cleanPattern != null) {
return getAlwaysProvidersFilter(cleanPattern);
}
return defaultResult();
}
@@ -118,36 +118,36 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
return constructFilter(filters, AllMultiItemFilter::new);
}
private String getTokenCleanText(SearchExpressionParser.TokenContext ctx) {
String cleanText = null;
if (ctx.PLAIN_TEXT() != null) {
cleanText = Pattern.quote(
PLAIN_TEXT_ESCAPED_PATTERN.matcher(ctx.PLAIN_TEXT().getSymbol().getText())
private String getCleanPattern(SearchExpressionParser.TokenContext ctx) {
String cleanPattern = null;
if (ctx.plainText() != null) {
cleanPattern = Pattern.quote(
ESCAPED_SYMBOL_PATTERN.matcher(ctx.plainText().getText())
// Unescape everything in search expression
.replaceAll("$1"));
} else if (ctx.regex() != null) {
if (ctx.regex().REGEX_CONTENT() != null) {
cleanText = ctx.regex().REGEX_CONTENT().getSymbol().getText();
cleanPattern = ctx.regex().REGEX_CONTENT().getSymbol().getText();
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll("$1 ");
cleanPattern = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll("$1 ");
}
}
} else if (ctx.quoted() != null) {
if (ctx.quoted().QUOTED_CONTENT() != null) {
cleanText = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
cleanPattern = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
// Unescape quotes
cleanText = ESCAPED_QUOTE_PATTERN.matcher(cleanText).replaceAll("\"");
cleanText = Pattern.quote(cleanText);
cleanPattern = ESCAPED_QUOTE_PATTERN.matcher(cleanPattern).replaceAll("\"");
cleanPattern = Pattern.quote(cleanPattern);
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
cleanPattern = ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll(" ");
}
}
}
return cleanText;
return cleanPattern;
}
private ItemFilter visitChildren(ParserRuleContext node, Function<List<ItemFilter>, ItemFilter> filterConstructor) {
@@ -62,8 +62,8 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
private String getTokenCleanText(SearchExpressionParser.TokenContext ctx, Character prefix) {
String cleanText = null;
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
if (ctx.PLAIN_TEXT() != null) {
cleanText = ctx.PLAIN_TEXT().getSymbol().getText();
if (ctx.plainText() != null) {
cleanText = ctx.plainText().getText();
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
@@ -0,0 +1,63 @@
package codechicken.nei.util;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class SlotInaccessible extends Slot {
private ItemStack itemStack = null;
public SlotInaccessible(ItemStack itemStack, int xDisplayPosition, int yDisplayPosition) {
super(null, 0, xDisplayPosition, yDisplayPosition);
this.itemStack = itemStack;
}
@Override
public void onSlotChange(final ItemStack par1ItemStack, final ItemStack par2ItemStack) {}
@Override
public void onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) {}
@Override
public boolean isItemValid(final ItemStack par1ItemStack) {
return false;
}
@Override
public ItemStack getStack() {
return this.itemStack;
}
@Override
public void putStack(final ItemStack par1ItemStack) {}
@Override
public void onSlotChanged() {}
@Override
public int getSlotStackLimit() {
return 0;
}
@Override
public ItemStack decrStackSize(final int par1) {
return null;
}
@Override
public boolean isSlotInInventory(final IInventory par1IInventory, final int par2) {
return false;
}
@Override
public boolean canTakeStack(final EntityPlayer par1EntityPlayer) {
return false;
}
@Override
public int getSlotIndex() {
return 0;
}
}
@@ -0,0 +1,5 @@
# This file contains a list of GUIs that can use the DefaultBookmarkContainerHandler for bookmarks.
# It serves as an alternative to API.registerBookmarkContainerHandler and is intended for cases
# where you can't modify the mod itself and its GUI doesn't have custom slots.
# Each line in this file should either be a comment (starting with '#') or a guiContainer class name.
# If you delete this file, it will be regenerated with the default bookmark containers list.
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more