Compare commits

...
Author SHA1 Message Date
slprime 463d8d1f12 fix counter label position 2026-11-25 23:43:56 +02:00
github-actions[bot]andGitHub GTNH Actions c7188f1952 Optimising images contained in recipe/ui-skin-sizes for #1165 (#1166)
Co-authored-by: GitHub GTNH Actions <[email protected]>
2026-11-25 21:22:16 +02:00
slprime db9dc1706b Improve recipe screen 2026-11-25 21:07:56 +02:00
a665a5be56 Fix item hotkeys on crafting tree Crafting slots (#1151)
Co-authored-by: Lorenzo <[email protected]>
Co-authored-by: Chitak 985 <[email protected]>
Co-authored-by: slprime <[email protected]>
2026-11-25 09:08:16 +02:00
slprime bdadcc37a6 Extract inventory and missing ingredient helpers (#1164) 2026-11-25 01:04:09 +02:00
gorbit99 cdc8e22aec Fix hotkeys with modifiers double firing when pressed at the same time (#1117) 2026-11-24 17:57:20 -05:00
slprimeandgithub-actions[bot] bf957e4642 Move shared button and scrollbar textures to UIWidgetTexture (#1158)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-24 00:32:59 +02:00
slprime 09e3846bea Rebuild recipe catalysts only when something changes (#1157) 2026-11-23 21:12:03 +02:00
gorbit99andslprime d73df3aedc Clear bookmark group tooltip when pulling items or changing quantities (#1152)
Co-authored-by: slprime <[email protected]>
2026-11-22 10:11:37 +02:00
slprime f84b24724a Fix autocraft crash when started from the recipe screen (#1108) (#1150) 2026-11-21 19:57:06 +02:00
OrderedSet86 1bb550305c Less hacky light overlay fix for light opacity 0 blocks (#1124) 2026-11-19 16:26:46 +00:00
gorbit99 6649d28708 Change layout recalculation order (#1125) 2026-11-19 14:55:18 +01:00
slprime 6b7e465306 Copy fluid registry name instead of the display item id (#1122) 2026-11-17 21:53:30 +02:00
ab1e8153f5 Add NEI mob spawn overlay variants (#1111)
- Add multiple light level overlay modes (Connected, Square, GTNH Logo, Pufferfish, X)
- Set default F7 overlay to Connected
- Allow changing horizontal and vertical radius of light level overlay (before it was stuck at 16 blocks)
- Set default horizontal radius to 32 blocks
- Optimize performance by 10-30x compared to master
- Works with shaders (tested Complementary Unbound + Euphoria patches)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Martin Robertz <[email protected]>
2026-11-16 19:51:42 +02:00
slprime 4257235e6e Don't toggle handler info widget while typing in recipe search (#1121) 2026-11-15 16:20:26 +02:00
slprime 1c33a5b7d6 Add recipe text search with ~ prefix (#1120) 2026-11-15 15:43:35 +02:00
slprime 8e6b31de18 Speed up GUID cache and bookmark recipe lookups (#1119) 2026-11-13 23:25:20 +02:00
DarkShadow44andslprime 1a27b02412 Don't copy stack unless it changed (#1116)
Co-authored-by: slprime <[email protected]>
2026-11-13 01:53:07 +02:00
slprime 0185cd64b1 Optimize GUI overlap scan for item panels (#1118) 2026-11-12 01:35:53 +02:00
slprime fbbeafcd79 Fix WorldClient leak after leaving the world (#1115) 2026-11-10 19:22:17 +02:00
UltraProdigy 9839d1d08f ci: run build and test on release branches 2026-11-09 01:11:38 -05:00
slprime 84d42de15f Make name optional in API.addCollapsibleGroup (#1114) 2026-11-08 18:13:37 +02:00
slprime d04e1c8e83 Add API.addCollapsibleGroup for registering collapsible item groups (#1113) 2026-11-08 17:37:44 +02:00
109 changed files with 3601 additions and 1358 deletions

No files matched your search

+2 -2
View File
@@ -3,9 +3,9 @@ name: Build and test
on:
pull_request:
branches: [ master, main ]
branches: [ master, main, release/** ]
push:
branches: [ master, main ]
branches: [ master, main, release/** ]
jobs:
build-and-test:
+2 -1
View File
@@ -24,6 +24,7 @@ DASH : '-' ;
RECIPE_INGREDIENTS : '<&' | '<' ;
RECIPE_RESULT : '>&' | '>' ;
RECIPE_OTHERS : '^&' | '^' ;
RECIPE_TEXT : '~' ;
OR : '|' ;
LEFT_BRACKET : '{' ;
@@ -33,7 +34,7 @@ SPACE : ' ' ;
ESCAPED_SYMBOL : '\\' . ;
PREFIX : CLEAN_SYMBOL {searchParser.hasRedefinedPrefix(getText().charAt(0))}? ;
CLEAN_SYMBOL : ~[-<>^{}|/\\ "] ;
CLEAN_SYMBOL : ~[-<>^~{}|/\\ "] ;
mode REGEX;
+1
View File
@@ -19,6 +19,7 @@ recipeClauseExpression
: ingredientsPrefix=RECIPE_INGREDIENTS searchExpression[0, $ingredientsPrefix.getText().length() > 1]
| resultPrefix=RECIPE_RESULT searchExpression[1, $resultPrefix.getText().length() > 1]
| othersPrefix=RECIPE_OTHERS searchExpression[2, $othersPrefix.getText().length() > 1]
| RECIPE_TEXT searchExpression[4, false]
| searchExpression[3, false]
;
@@ -8,6 +8,7 @@ import org.lwjgl.opengl.GL11;
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.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
@@ -55,12 +56,14 @@ public abstract class AbstractSubpanel<T extends ItemsGrid<? extends ItemsGridSl
}
protected void updateLinePadding() {
GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final INEIGuiHandler[] handlers = GuiInfo.getGuiHandlersSnapshot();
final Rectangle4i rect = new Rectangle4i(this.x, this.y - 1, 10, 2);
this.linePaddingStart = 0;
while (GuiInfo
.hideItemPanelSlot(guiContainer, new Rectangle4i(this.x + this.linePaddingStart, this.y - 1, 10, 2))) {
while (this.linePaddingStart < this.w && GuiInfo.hideItemPanelSlot(guiContainer, rect, handlers)) {
this.linePaddingStart += 10;
rect.x += 10;
}
}
@@ -1073,6 +1073,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
this.grid.shiftGroupAmount(groupId, multiplier * shift);
clearTooltips();
return true;
}
}
@@ -1226,6 +1227,8 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
if (helmStackIndex != -1) {
FastTransferManager.clickSlot(guiContainer, helmStackIndex, 0, 0);
}
clearTooltips();
}
}
@@ -54,7 +54,10 @@ import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.recipe.RecipeItemInputHandler;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.debug.DebugHandlerWidget;
import cpw.mods.fml.client.CustomModLoadingErrorDisplayException;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
@@ -444,6 +447,12 @@ public class ClientHandler {
if (event.world == mc.theWorld) {
NEIClientConfig.unloadWorld();
ItemMobSpawner.clearEntityReferences();
WorldOverlayRenderer.onWorldUnload();
RecipeItemInputHandler.instance.clearTooltipCache();
RecipeHandlerRef.clearCache();
ItemPanels.itemPanel.craftablesPanel.clearGuiReferences();
DebugHandlerWidget.instance.clearGuiReferences();
NEIController.manager = null;
}
}
@@ -7,8 +7,11 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTBase.NBTPrimitive;
@@ -35,6 +38,7 @@ public class CollapsibleItems {
public ItemFilter filter;
public boolean expanded = false;
public String displayName = "";
public String unlocalizedName;
public void setFilter(String filter) {
this.filter = ItemStackFilterParser.parse(filter.trim());
@@ -46,15 +50,38 @@ public class CollapsibleItems {
this.guid = guid;
}
public String getDisplayName() {
if (this.unlocalizedName != null && !this.unlocalizedName.isEmpty()) {
final String translated = StatCollector.translateToLocal(this.unlocalizedName);
if (!translated.equals(this.unlocalizedName)) {
return translated;
}
}
return this.displayName;
}
public boolean matches(ItemStack stack) {
return this.filter.matches(stack);
}
}
public static class ApiGroup {
private String unlocalizedName;
public ApiGroup setName(String unlocalizedName) {
this.unlocalizedName = unlocalizedName;
return this;
}
}
private static final String STATE_KEY = "collapsibleitems";
protected static File statesFile;
protected static final List<GroupItem> groups = new ArrayList<>();
protected static final List<Supplier<GroupItem>> apiGroups = new CopyOnWriteArrayList<>();
protected static final Map<ItemStack, Integer> cache = new ConcurrentHashMap<>();
private CollapsibleItems() {}
@@ -77,11 +104,57 @@ public class CollapsibleItems {
ClientHandler.loadSettingsFile(
"collapsibleitems.cfg",
lines -> parseFile(lines.collect(Collectors.toCollection(ArrayList::new))));
for (Supplier<GroupItem> apiGroup : CollapsibleItems.apiGroups) {
try {
addGroup(apiGroup.get());
} catch (Exception e) {
NEIClientConfig.logger.error("Failed to add API group", e);
}
}
}
loadStates();
}
public static ApiGroup registerGroup(String filter) {
final ApiGroup apiGroup = new ApiGroup();
CollapsibleItems.apiGroups.add(() -> {
GroupItem group = new GroupItem();
group.setFilter(filter);
group.unlocalizedName = apiGroup.unlocalizedName;
return group;
});
return apiGroup;
}
public static ApiGroup registerGroup(Iterable<ItemStack> items) {
final ApiGroup apiGroup = new ApiGroup();
final ItemStackSet filter = new ItemStackSet();
for (ItemStack stack : items) {
if (stack != null) filter.add(stack.copy());
}
if (filter.isEmpty()) return apiGroup;
final String key = filter.keys().stream()
.map(stack -> Item.itemRegistry.getNameForObject(stack.getItem()) + ":" + stack.getItemDamage())
.sorted().collect(Collectors.joining(","));
final String guid = UUID.nameUUIDFromBytes(key.getBytes()).toString();
CollapsibleItems.apiGroups.add(() -> {
GroupItem group = new GroupItem();
group.setFilter(filter, guid);
group.unlocalizedName = apiGroup.unlocalizedName;
return group;
});
return apiGroup;
}
private static void parseFile(List<String> itemStrings) {
final JsonParser parser = new JsonParser();
GroupItem group = new GroupItem();
@@ -92,17 +165,8 @@ public class CollapsibleItems {
if (itemStr.startsWith("; ")) {
JsonObject settings = parser.parse(itemStr.substring(2)).getAsJsonObject();
if (settings.get("displayName") != null) {
group.displayName = settings.get("displayName").getAsString();
}
if (settings.get("unlocalizedName") != null) {
String unlocalizedName = settings.get("unlocalizedName").getAsString();
String displayName = StatCollector.translateToLocal(unlocalizedName);
if (!displayName.equals(unlocalizedName)) {
group.displayName = displayName;
}
group.unlocalizedName = settings.get("unlocalizedName").getAsString();
}
if (settings.get("expanded") != null) {
@@ -176,7 +240,7 @@ public class CollapsibleItems {
public static String getDisplayName(int groupIndex) {
if (groupIndex < CollapsibleItems.groups.size()) {
return CollapsibleItems.groups.get(groupIndex).displayName;
return CollapsibleItems.groups.get(groupIndex).getDisplayName();
}
return null;
@@ -11,9 +11,11 @@ public class ColorUtils {
textGray = color.rgb("textGray", "0x404040"),
textLightGray = color.rgb("textLightGray", "0x606060"),
recipeTitle = color.rgb("recipeTitle", "0xFFFFFF"),
recipeTitleBG = color.argb("recipeTitleBG", "0x30000000"),
recipeTitleHover = color.rgb("recipeTitleHover", "0xFFFF55"),
subsetWidget = color.rgb("subsetWidget", "0xAA00AA"),
recipeBadge = color.rgb("recipeBadge", "0xFDD835"),
subsetWidget = color.rgb("subsetWidget", "0xAA00AA"),
buttonLabelNormal = color.rgb("buttonLabelNormal", "0xE0E0E0"),
buttonLabelHover = color.rgb("buttonLabelHover", "0xFFFFA0"),
buttonLabelDisabled = color.rgb("buttonLabelDisabled", "0x601010"),
@@ -0,0 +1,188 @@
package codechicken.nei;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.function.Predicate;
import net.minecraft.client.gui.inventory.GuiContainer;
import codechicken.lib.vec.Rectangle4i;
final class GridOverlapScanner {
private static boolean scanRequested = true;
private static boolean scanFrame = true;
private static boolean wasShowTooltip = true;
private static WeakReference<GuiContainer> lastGui = new WeakReference<>(null);
private boolean invalidated = true;
private final Rectangle4i rect = new Rectangle4i();
private boolean[] checked = new boolean[0];
private int[] queue = new int[0];
private int tail;
private Predicate<Rectangle4i> isHidden;
private boolean[] hidden;
private int hiddenCount;
private int left;
private int top;
private int slotSize;
private int columns;
public static void requestScan() {
scanRequested = true;
}
public static void beginFrame(GuiContainer gui, boolean shouldShowTooltip) {
if (wasShowTooltip != shouldShowTooltip) {
scanRequested = true;
}
wasShowTooltip = shouldShowTooltip;
if (lastGui.get() != gui) {
lastGui = new WeakReference<>(gui);
scanRequested = true;
}
scanFrame = scanRequested;
scanRequested = false;
}
public static boolean isScanFrame() {
return scanFrame;
}
public void invalidate() {
this.invalidated = true;
}
public boolean shouldRefresh() {
final boolean refresh = this.invalidated || scanFrame;
this.invalidated = false;
return refresh;
}
public int scan(Predicate<Rectangle4i> isHidden, int left, int top, int slotSize, int rows, int columns,
boolean seedLeft, boolean seedRight, boolean[] hidden) {
final int size = rows * columns;
if (this.checked.length < size) {
this.checked = new boolean[size];
this.queue = new int[size];
} else {
Arrays.fill(this.checked, 0, size, false);
}
this.isHidden = isHidden;
this.hidden = hidden;
this.hiddenCount = 0;
this.tail = 0;
this.left = left;
this.top = top;
this.slotSize = slotSize;
this.columns = columns;
for (int r = 0; r < rows; r++) {
if (seedLeft) {
probe(r, 0);
}
if (seedRight) {
probe(r, columns - 1);
}
}
for (int head = 0; head < this.tail; head++) {
final int row = this.queue[head] / columns;
final int column = this.queue[head] % columns;
for (int r = Math.max(0, row - 1); r <= Math.min(rows - 1, row + 1); r++) {
for (int c = Math.max(0, column - 1); c <= Math.min(columns - 1, column + 1); c++) {
probe(r, c);
}
}
}
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
if (this.checked[r * columns + c]) {
continue;
}
int c1 = c;
while (c1 + 1 < columns && !this.checked[r * columns + c1 + 1]) {
c1++;
}
int r1 = r;
while (r1 + 1 < rows && isUnchecked(r1 + 1, c, c1)) {
r1++;
}
scanArea(r, r1, c, c1);
c = c1;
}
}
this.isHidden = null;
this.hidden = null;
return this.hiddenCount;
}
private void probe(int row, int column) {
final int idx = row * this.columns + column;
if (!this.checked[idx]) {
this.checked[idx] = true;
if (test(row, row, column, column)) {
this.hidden[idx] = true;
this.queue[this.tail++] = idx;
this.hiddenCount++;
}
}
}
private void scanArea(int r0, int r1, int c0, int c1) {
if (!test(r0, r1, c0, c1)) {
for (int r = r0; r <= r1; r++) {
Arrays.fill(this.checked, r * this.columns + c0, r * this.columns + c1 + 1, true);
}
} else if (r0 == r1 && c0 == c1) {
this.checked[r0 * this.columns + c0] = true;
this.hidden[r0 * this.columns + c0] = true;
this.hiddenCount++;
} else if (r1 - r0 >= c1 - c0) {
final int mid = (r0 + r1) / 2;
scanArea(r0, mid, c0, c1);
scanArea(mid + 1, r1, c0, c1);
} else {
final int mid = (c0 + c1) / 2;
scanArea(r0, r1, c0, mid);
scanArea(r0, r1, mid + 1, c1);
}
}
private boolean isUnchecked(int row, int c0, int c1) {
for (int c = c0; c <= c1; c++) {
if (this.checked[row * this.columns + c]) {
return false;
}
}
return true;
}
private boolean test(int r0, int r1, int c0, int c1) {
this.rect.set(
this.left + c0 * this.slotSize,
this.top + r0 * this.slotSize,
(c1 - c0 + 1) * this.slotSize,
(r1 - r0 + 1) * this.slotSize);
return this.isHidden.test(this.rect);
}
}
@@ -18,7 +18,6 @@ import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemsGrid.ItemsGridSlot;
import codechicken.nei.ItemsGrid.MouseContext;
import codechicken.nei.NEIClientUtils.Alignment;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.ICraftingHandler;
@@ -137,7 +136,11 @@ public class ItemCraftablesPanel
@Override
public void execute() {
pendingResult.set(generateCraftables(ItemCraftablesPanel.this.pendingSnapshot));
final CraftablesSnapshot snapshot = ItemCraftablesPanel.this.pendingSnapshot;
if (snapshot != null) {
pendingResult.set(generateCraftables(snapshot));
}
}
};
@@ -264,7 +267,7 @@ public class ItemCraftablesPanel
if (firstGui != null && !ItemCraftablesPanel.guiBlacklist.contains(firstGui.getClass().getName())) {
final boolean showOnlyFavorites = NEIClientConfig
.getBooleanSetting("inventory.craftables.favoritesOnly");
final ItemStackAmount inv = AutoCraftingManager.getInventoryItems(firstGui);
final ItemStackAmount inv = ItemStackAmount.of(firstGui);
if (this.lastGuiContainer != firstGui
|| showOnlyFavorites && this.lastFavoritesCount != FavoriteRecipes.size()
@@ -298,6 +301,11 @@ public class ItemCraftablesPanel
}
}
public void clearGuiReferences() {
this.lastGuiContainer = null;
this.pendingSnapshot = null;
}
private GuiContainer getGuiContainer() {
final GuiContainer firstGui = NEIClientUtils.getGuiContainer();
return (firstGui instanceof GuiRecipe<?>gui) ? gui.firstGui : firstGui;
@@ -308,7 +316,7 @@ public class ItemCraftablesPanel
final Map<ItemStack, RecipeId> availableRecipes = new HashMap<>();
if (!availableHandlers.isEmpty()) {
final Map<Item, List<ItemStack>> invByItem = indexInventoryByItem(snapshot.inventory.values());
final Map<Item, List<ItemStack>> invByItem = snapshot.inventory.groupByItem();
if (snapshot.showOnlyFavorites) {
for (IRecipeHandler handler : availableHandlers) {
@@ -340,16 +348,6 @@ public class ItemCraftablesPanel
return availableHandlers;
}
private static Map<Item, List<ItemStack>> indexInventoryByItem(List<ItemStack> invStacks) {
final Map<Item, List<ItemStack>> index = new HashMap<>();
for (ItemStack stack : invStacks) {
index.computeIfAbsent(stack.getItem(), i -> new ArrayList<>()).add(stack);
}
return index;
}
private void collectHandlerCandidates(IRecipeHandler handler, Map<Item, List<ItemStack>> invByItem,
List<RecipeCandidate> candidates) {
IntStream.range(0, handler.numRecipes()).parallel().forEach(recipeIndex -> {
@@ -439,36 +437,8 @@ public class ItemCraftablesPanel
return availableRecipes;
}
private boolean existsIngredients(List<PositionedStack> ingredients, Map<Item, List<ItemStack>> invByItem) {
final Map<ItemStack, Integer> usedItems = new HashMap<>();
for (PositionedStack pStack : ingredients) {
ItemStack used = null;
for (ItemStack permutation : pStack.items) {
final List<ItemStack> candidates = invByItem.get(permutation.getItem());
if (candidates == null) continue;
for (ItemStack is : candidates) {
if (usedItems.getOrDefault(is, is.stackSize) >= pStack.item.stackSize
&& NEIServerUtils.areStacksSameTypeCrafting(permutation, is)) {
used = is;
break;
}
}
if (used != null) break;
}
if (used != null) {
usedItems.put(used, usedItems.getOrDefault(used, used.stackSize) - pStack.item.stackSize);
} else {
return false;
}
}
return !usedItems.isEmpty();
private static boolean existsIngredients(List<PositionedStack> ingredients, Map<Item, List<ItemStack>> invByItem) {
return !ingredients.isEmpty() && NEIClientUtils.countMissingIngredients(ingredients, invByItem, 1) == 0;
}
}
@@ -1,12 +1,17 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
@@ -96,6 +101,16 @@ public class ItemStackAmount {
return list;
}
public Map<Item, List<ItemStack>> groupByItem() {
final Map<Item, List<ItemStack>> groups = new HashMap<>();
for (ItemStack stack : values()) {
groups.computeIfAbsent(stack.getItem(), i -> new ArrayList<>()).add(stack);
}
return groups;
}
public int size() {
return this.itemMap.size();
}
@@ -140,4 +155,16 @@ public class ItemStackAmount {
return result;
}
public static ItemStackAmount of(GuiContainer gui) {
final ItemStackAmount result = new ItemStackAmount();
for (Slot slot : gui.inventorySlots.inventorySlots) {
if (slot.getHasStack() && !(slot instanceof SlotCrafting) && slot.canTakeStack(gui.mc.thePlayer)) {
result.add(slot.getStack());
}
}
return result;
}
}
+6 -1
View File
@@ -127,7 +127,12 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
this.displayName = "Unnamed";
}
this.stack = StackInfo.loadFromNBT(StackInfo.itemStackToNBT(stack), 0);
// Copying the stack copies its whole NBT, so it is only done when the hovered stack changes
final boolean sameStack = this.stack != null && this.stack.isItemEqual(stack)
&& ItemStack.areItemStackTagsEqual(this.stack, stack);
if (!sameStack) {
this.stack = StackInfo.withAmount(stack, 0);
}
} else {
this.stack = null;
this.displayName = "";
+26 -36
View File
@@ -282,6 +282,8 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
protected boolean[] invalidSlotMap;
private final GridOverlapScanner overlapScanner = new GridOverlapScanner();
protected ScreenCapture screenCapture = null;
public ArrayList<ItemStack> getItems() {
@@ -359,12 +361,13 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
width = newWidth;
height = newHeight;
columns = width / SLOT_SIZE;
rows = height / SLOT_SIZE;
this.columns = newWidth / SLOT_SIZE;
this.rows = newHeight / SLOT_SIZE;
paddingLeft = (width % SLOT_SIZE) / 2;
if (changed) {
this.overlapScanner.invalidate();
onGridChanged();
}
}
@@ -405,55 +408,42 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
}
public void refresh(GuiContainer gui) {
final int gridRenderingCacheMode = getGridRenderingCacheMode();
if (gridRenderingCacheMode <= 0 || screenCapture == null || screenCapture.needRefresh(gridRenderingCacheMode)) {
if (this.overlapScanner.shouldRefresh()) {
updateGuiOverlapSlots(gui);
}
shiftPage(0);
}
protected void updateGuiOverlapSlots(GuiContainer gui) {
final boolean[] oldSlotMap = invalidSlotMap;
final int oldRows = rows;
final int oldColumns = columns;
final boolean[] oldSlotMap = this.invalidSlotMap;
final int size = this.rows * this.columns;
final boolean[] slotMap = new boolean[size];
invalidSlotMap = new boolean[rows * columns];
perPage = columns * rows;
this.perPage = size;
if (gui != null) {
if (gui != null && size > 0) {
final INEIGuiHandler[] handlers = GuiInfo.getGuiHandlersSnapshot();
if (NEIClientConfig.optimizeGuiOverlapComputation()) {
checkGuiOverlap(gui, handlers, 0, columns - 2, 1);
checkGuiOverlap(gui, handlers, columns - 1, 1, -1);
} else {
checkGuiOverlap(gui, handlers, 0, columns, 1);
}
final Rectangle4i origin = getSlotRect(0, 0);
this.perPage -= this.overlapScanner.scan(
rect -> GuiInfo.hideItemPanelSlot(gui, rect, handlers),
origin.x,
origin.y,
SLOT_SIZE,
this.rows,
this.columns,
origin.x + this.columns * SLOT_SIZE > gui.guiLeft,
origin.x < gui.guiLeft + gui.xSize,
slotMap);
}
if (oldRows != rows || oldColumns != columns || !Arrays.equals(oldSlotMap, invalidSlotMap)) {
this.invalidSlotMap = slotMap;
if (!Arrays.equals(oldSlotMap, slotMap)) {
onGridChanged();
}
}
private void checkGuiOverlap(GuiContainer gui, INEIGuiHandler[] handlers, int start, int end, int dir) {
boolean validColumn = false;
for (int c = start; c != end && (!NEIClientConfig.optimizeGuiOverlapComputation() || !validColumn); c += dir) {
validColumn = true;
for (int r = 0; r < rows; r++) {
final int idx = columns * r + c;
if (idx >= 0 && idx < invalidSlotMap.length
&& !invalidSlotMap[idx]
&& GuiInfo.hideItemPanelSlot(gui, getSlotRect(r, c), handlers)) {
invalidSlotMap[idx] = true;
validColumn = false;
perPage--;
}
}
}
}
public T getSlotMouseOver(int mousex, int mousey) {
if (!contains(mousex, mousey)) {
return null;
+36 -17
View File
@@ -5,6 +5,7 @@ import java.util.LinkedList;
import java.util.Map;
import java.util.StringJoiner;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
@@ -30,7 +31,9 @@ public class KeyManager {
private static final Map<String, KeyBinding> keyBindings = new HashMap<>();
private static final Map<String, String> keyAliases = new HashMap<>();
private static volatile boolean pendingOptionsReload = false;
private static int clickedButton = -1;
private static final int NO_INPUT_EVENT = Integer.MIN_VALUE;
private static int currentEvent = NO_INPUT_EVENT;
static {
// Aliases for legacy keybinds
@@ -70,16 +73,22 @@ public class KeyManager {
public static boolean isKeyDown(String ident) {
final KeyBinding binding = getKeyBinding(ident);
if (binding == null) {
return false;
}
if (binding != null) {
final int keyCode = binding.getKeyCode();
final int keyCode = binding.getKeyCode();
if (currentEvent != NO_INPUT_EVENT) {
return keyCode == currentEvent;
}
if (keyCode < 0) {
final int button = keyCode + 100;
return Mouse.isButtonDown(button) || button == clickedButton;
} else if (keyCode > Keyboard.KEY_NONE && keyCode < Keyboard.KEYBOARD_SIZE) {
return Keyboard.isKeyDown(keyCode);
}
if (keyCode < 0) {
final int button = keyCode + 100;
return Mouse.isButtonDown(button);
}
if (keyCode > Keyboard.KEY_NONE && keyCode < Keyboard.KEYBOARD_SIZE) {
return Keyboard.isKeyDown(keyCode);
}
return false;
@@ -97,6 +106,23 @@ public class KeyManager {
return false;
}
private static <T> T withEvent(int code, Supplier<T> handler) {
final int previous = currentEvent;
currentEvent = code;
try {
return handler.get();
} finally {
currentEvent = previous;
}
}
public static void handleKeyEvent(int keyCode, Runnable handler) {
withEvent(keyCode, () -> {
handler.run();
return null;
});
}
/**
* Runs a hotkey handler for a click of the given mouse button if the button is bound to any NEI key binding. The
* button is reported as down by {@link #isKeyDown} for the duration of the call, because the LWJGL button state can
@@ -109,14 +135,7 @@ public class KeyManager {
return false;
}
final int previous = clickedButton;
clickedButton = button;
try {
return handler.getAsBoolean();
} finally {
clickedButton = previous;
}
return withEvent(button - 100, handler::getAsBoolean);
}
public static boolean isHashDown(String ident) {
@@ -388,6 +388,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
public static void layout(GuiContainer gui) {
GridOverlapScanner.beginFrame(gui, GuiContainerManager.shouldShowTooltip(gui));
VisiblityData visiblity = new VisiblityData();
visiblity.showNEI = !isHidden();
visiblity.showBookmarkPanel = !isBookmarkPanelHidden();
@@ -711,6 +713,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public void load(GuiContainer gui) {
NEIController.load(gui);
if (isEnabled()) {
setInputFocused(null);
@@ -724,8 +728,6 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
AutoFocusWidget.instance.load(gui);
}
NEIController.load(gui);
if (checkCreativeInv(gui) && gui.mc.currentScreen instanceof GuiContainerCreative) // override creative with
// creative+
gui.mc.displayGuiScreen(null); // close the screen and wait for the server to open it for us
@@ -821,6 +823,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (!isEnabled()) return;
GridOverlapScanner.requestScan();
AutoFocusWidget.instance.guiTick();
for (Widget widget : drawWidgets) widget.update();
@@ -11,8 +11,9 @@ import codechicken.nei.api.LayoutStyle;
public class LayoutStyleMinecraft extends LayoutStyle {
protected static final int BUTTON_SIZE = 20;
protected static final int MARGIN = 2;
public static final int BUTTON_SIZE = 20;
public static final int MARGIN = 2;
public static final int SUBSET_BAR_HEIGHT = 16;
public int buttonCount;
public int leftSize;
@@ -147,7 +148,7 @@ public class LayoutStyleMinecraft extends LayoutStyle {
LayoutManager.searchField.x += BUTTON_SIZE;
LayoutManager.searchField.w -= BUTTON_SIZE;
} else {
LayoutManager.dropDown.h = 16;
LayoutManager.dropDown.h = SUBSET_BAR_HEIGHT;
LayoutManager.dropDown.w = 150;
LayoutManager.dropDown.y = MARGIN;
LayoutManager.dropDown.x = (gui.width - LayoutManager.dropDown.w) / 2;
@@ -57,6 +57,9 @@ import codechicken.nei.config.OptionToggleButtonBoubs;
import codechicken.nei.config.OptionUtilities;
import codechicken.nei.config.preset.GuiPresetList;
import codechicken.nei.event.NEIConfigsLoadedEvent;
import codechicken.nei.moboverlay.MobOverlayScan;
import codechicken.nei.moboverlay.MobOverlayStyle;
import codechicken.nei.recipe.HandlerInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.recipe.RecipeCatalysts;
@@ -268,9 +271,20 @@ public class NEIClientConfig {
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.guirecipe.infiniteScroll", true));
tag.getTag("inventory.guirecipe.evenRecipeSpacing").setComment("Spread recipes evenly across the page height")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.guirecipe.evenRecipeSpacing", true));
tag.getTag("inventory.guirecipe.topMargin").setComment("Recipe GUI Top Margin").getIntValue(0);
API.addOption(new OptionIntegerField("inventory.guirecipe.topMargin", 0, 200));
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.minWidth").setComment("Recipe GUI Min Width")
.getIntValue(HandlerInfo.DEFAULT_WIDTH);
API.addOption(new OptionIntegerField("inventory.guirecipe.minWidth", HandlerInfo.DEFAULT_WIDTH, 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));
@@ -442,6 +456,46 @@ public class NEIClientConfig {
tag.getTag("world.overlays.lock").getBooleanValue(true);
API.addOption(new OptionToggleButton("world.overlays.lock", true));
tag.getTag("world.overlays.mobOverlayStyle")
.setComment("Mark on each block of the mob spawn overlay: " + MobOverlayStyle.formatAllNames())
.getValue(MobOverlayStyle.DEFAULT.formatName());
API.addOption(new OptionCycled("world.overlays.mobOverlayStyle", MobOverlayStyle.values().length, true) {
@Override
public int value() {
return MobOverlayStyle.parseStyle(getTag().getValue()).ordinal();
}
@Override
public void setValue(int value) {
getTag().setValue(MobOverlayStyle.values()[value].formatName());
}
@Override
public String getButtonText() {
return translateN(
"world.overlays.mobOverlayStyle."
+ MobOverlayStyle.parseStyle(getTag().getValue()).formatName());
}
});
tag.getTag("world.overlays.mobOverlayRadius")
.setComment("Blocks scanned on each side of the player by the mob spawn overlay")
.getIntValue(MobOverlayScan.DEFAULT_RADIUS);
API.addOption(
new OptionIntegerField(
"world.overlays.mobOverlayRadius",
MobOverlayScan.MIN_RADIUS,
MobOverlayScan.MAX_RADIUS));
tag.getTag("world.overlays.mobOverlayVerticalRadius")
.setComment("Blocks scanned above and below the player by the mob spawn overlay")
.getIntValue(MobOverlayScan.DEFAULT_VERTICAL_RADIUS);
API.addOption(
new OptionIntegerField(
"world.overlays.mobOverlayVerticalRadius",
MobOverlayScan.MIN_VERTICAL_RADIUS,
MobOverlayScan.MAX_VERTICAL_RADIUS));
tag.getTag("inventory.itempanelScale").getIntValue(100);
ItemsPanelGrid.updateScale();
API.addOption(new OptionIntegerField("inventory.itempanelScale", 1, 1000) {
@@ -498,10 +552,6 @@ public class NEIClientConfig {
tag.getTag("inventory.showItemQuantityWidget").setComment("Show Item Quantity Widget").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.showItemQuantityWidget", true));
tag.getTag("inventory.optimize_gui_overlap_computation").setComment("Optimize computation for GUI overlap")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.optimize_gui_overlap_computation", true));
tag.getTag("inventory.autocrafting").setComment("Autocrafting").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.autocrafting", true));
@@ -1160,10 +1210,6 @@ public class NEIClientConfig {
return getBooleanSetting("inventory.bookmarks.craftingTreeZoomWithoutModifier");
}
public static boolean optimizeGuiOverlapComputation() {
return getBooleanSetting("inventory.optimize_gui_overlap_computation");
}
public static boolean showCycledIngredientsTooltip() {
return getBooleanSetting("inventory.guirecipe.cycledIngredientsTooltip");
}
@@ -538,6 +538,40 @@ public class NEIClientUtils extends NEIServerUtils {
return null;
}
public static int countMissingIngredients(List<PositionedStack> ingredients, Map<Item, List<ItemStack>> index,
int limit) {
Map<ItemStack, Integer> usedItems = new HashMap<>();
int missing = 0;
for (PositionedStack pStack : ingredients) {
ItemStack used = null;
for (ItemStack permutation : pStack.items) {
final List<ItemStack> candidates = index.get(permutation.getItem());
if (candidates == null) continue;
for (ItemStack is : candidates) {
if (usedItems.getOrDefault(is, is.stackSize) >= pStack.item.stackSize
&& NEIServerUtils.areStacksSameTypeCrafting(permutation, is)) {
used = is;
break;
}
}
if (used != null) break;
}
if (used != null) {
usedItems.put(used, usedItems.getOrDefault(used, used.stackSize) - pStack.item.stackSize);
} else if (++missing >= limit) {
return missing;
}
}
return missing;
}
public static boolean altKey() {
return Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU);
}
+31 -20
View File
@@ -29,6 +29,9 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
protected T grid;
private int headerPaddingLeft;
private int headerPaddingRight;
public ArrayList<ItemStack> getItems() {
return this.grid.getItems();
}
@@ -105,26 +108,15 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
protected int resizeHeader(GuiContainer gui) {
final int BUTTON_SIZE = 16;
int paddingLeft = 0;
int paddingRight = 0;
while (paddingLeft < w && GuiInfo.hideItemPanelSlot(
gui,
new Rectangle4i(x + paddingLeft, y, ItemsGrid.SLOT_SIZE, ItemsGrid.SLOT_SIZE))) {
paddingLeft += ItemsGrid.SLOT_SIZE;
if (GridOverlapScanner.isScanFrame()) {
updateHeaderPadding(gui);
}
while (paddingRight < w && GuiInfo.hideItemPanelSlot(
gui,
new Rectangle4i(
x + w - paddingRight - ItemsGrid.SLOT_SIZE,
y,
ItemsGrid.SLOT_SIZE,
ItemsGrid.SLOT_SIZE))) {
paddingRight += ItemsGrid.SLOT_SIZE;
}
final int paddingLeft = this.headerPaddingLeft;
final int paddingRight = this.headerPaddingRight;
if (paddingLeft + paddingRight >= w) {
if (paddingLeft + paddingRight >= this.w) {
return 0;
}
@@ -132,16 +124,35 @@ public abstract class PanelWidget<T extends ItemsGrid<? extends ItemsGridSlot, ?
pagePrev.h = pageNext.h = BUTTON_SIZE;
pagePrev.y = pageNext.y = y;
pagePrev.x = x + paddingLeft;
pageNext.x = x + w - pageNext.w - paddingRight;
pagePrev.x = this.x + paddingLeft;
pageNext.x = this.x + this.w - pageNext.w - paddingRight;
pageLabel.x = x + paddingLeft + (w - paddingLeft - paddingRight) / 2;
pageLabel.y = y + 5;
pageLabel.x = this.x + paddingLeft + (this.w - paddingLeft - paddingRight) / 2;
pageLabel.y = this.y + 5;
pageLabel.text = getLabelText();
return BUTTON_SIZE + 2;
}
private void updateHeaderPadding(GuiContainer gui) {
final INEIGuiHandler[] handlers = GuiInfo.getGuiHandlersSnapshot();
final Rectangle4i slot = new Rectangle4i(this.x, this.y, ItemsGrid.SLOT_SIZE, ItemsGrid.SLOT_SIZE);
this.headerPaddingLeft = 0;
this.headerPaddingRight = 0;
while (this.headerPaddingLeft < this.w && GuiInfo.hideItemPanelSlot(gui, slot, handlers)) {
this.headerPaddingLeft += ItemsGrid.SLOT_SIZE;
slot.x += ItemsGrid.SLOT_SIZE;
}
slot.x = this.x + this.w - ItemsGrid.SLOT_SIZE;
while (this.headerPaddingRight < this.w && GuiInfo.hideItemPanelSlot(gui, slot, handlers)) {
this.headerPaddingRight += ItemsGrid.SLOT_SIZE;
slot.x -= ItemsGrid.SLOT_SIZE;
}
}
protected abstract int resizeFooter(GuiContainer gui);
public void setVisible() {
@@ -58,7 +58,9 @@ public class SearchTextFormatter implements TextFormatter {
int startIndex = 0;
for (SearchToken token : searchParser.splitSearchText(contextPart[1])) {
final String prefixes = contextPart[0].startsWith("~") ? "" : searchParser.getPrefixes();
for (SearchToken token : searchParser.splitSearchText(contextPart[1], prefixes)) {
formattedText.append(contextPart[1].substring(startIndex, token.start));
EnumChatFormatting tokenColor = EnumChatFormatting.RESET;
@@ -5,6 +5,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import net.minecraft.client.Minecraft;
@@ -21,6 +22,7 @@ import codechicken.nei.filter.AllMultiRecipeFilter;
import codechicken.nei.filter.AnyMultiRecipeFilter;
import codechicken.nei.filter.RecipeFilter;
import codechicken.nei.filter.RecipeFilter.FilterContext;
import codechicken.nei.filter.RecipeTextFilter;
import codechicken.nei.search.ItemFilterVisitor;
import codechicken.nei.search.RecipeFilterVisitor;
import codechicken.nei.search.SearchExpressionUtils;
@@ -207,7 +209,8 @@ public class SearchTokenParser {
for (String[] contextQuery : splitByDelimiters(subQuery[1], contextTokens, false)) {
if (contextQuery[1].isEmpty() || contextQuery[0].startsWith(">")
|| contextQuery[0].startsWith("^")) {
|| contextQuery[0].startsWith("^")
|| contextQuery[0].startsWith("~")) {
continue;
}
@@ -286,6 +289,7 @@ public class SearchTokenParser {
}
final List<IRecipeFilter> tokens = new ArrayList<>();
final boolean recipeText = contextQuery[0].startsWith("~");
FilterContext context = FilterContext.ANY;
if (!contextQuery[0].isEmpty()) {
@@ -293,12 +297,26 @@ public class SearchTokenParser {
contextQuery[0] = contextQuery[0].substring(1);
}
for (SearchToken token : splitSearchText(contextQuery[0] + contextQuery[1])) {
final ItemFilter result = token.getFilter(this);
if (result != null) {
tokens.add(
new RecipeFilter(context, token.ignore == null || token.ignore != '!', result));
for (SearchToken token : splitSearchText(
contextQuery[0] + contextQuery[1],
recipeText ? "" : getPrefixes())) {
if (recipeText) {
final IRecipeFilter text = recipeTextFilter(token);
if (text != null) {
tokens.add(text);
}
} else {
final ItemFilter result = token.getFilter(this);
if (result != null) {
tokens.add(
new RecipeFilter(
context,
token.ignore == null || token.ignore != '!',
result));
}
}
}
if (tokens.size() == 1) {
@@ -338,14 +356,31 @@ public class SearchTokenParser {
}
private static IRecipeFilter recipeTextFilter(SearchToken token) {
if (token.rawText.isEmpty()) return null;
final List<Predicate<List<String>>> words = new ArrayList<>();
for (String word : token.words) {
final Pattern pattern = SearchField.getPattern(word);
if (pattern != null) words.add(RecipeTextFilter.matching(pattern));
}
if (words.isEmpty()) return null;
final Predicate<List<String>> text = lines -> words.stream().allMatch(word -> word.test(lines));
return new RecipeTextFilter(token.ignore == null ? text : text.negate());
}
public List<SearchToken> splitSearchText(String filterText) {
return splitSearchText(filterText, getPrefixes());
}
public List<SearchToken> splitSearchText(String filterText, String prefixes) {
if (filterText.isEmpty()) {
return Collections.emptyList();
}
final List<SearchToken> tokens = new ArrayList<>();
final int spaceMode = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
final String prefixes = getPrefixes();
SearchToken lastToken = null;
int lastEnd = 0;
@@ -514,7 +549,7 @@ public class SearchTokenParser {
public String getRecipeContextTokens() {
// '^' is the start anchor and the negated class in regex mode
return NEIClientConfig.getIntSetting("inventory.search.patternMode") == 2 ? "<>" : "<>^";
return NEIClientConfig.getIntSetting("inventory.search.patternMode") == 2 ? "<>~" : "<>~^";
}
public char getRedefinedPrefix(char prefix) {
@@ -4,27 +4,22 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockSnow;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatComponentText;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.SpawnerAnimals;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import org.lwjgl.opengl.GL11;
import com.cardinalstar.cubicchunks.world.api.IMinMaxHeight;
import codechicken.lib.math.MathHelper;
import codechicken.nei.KeyManager.IKeyStateTracker;
import codechicken.nei.moboverlay.MobOverlayDisplayList;
import codechicken.nei.moboverlay.MobOverlayFace;
import codechicken.nei.moboverlay.MobOverlayScan;
import codechicken.nei.moboverlay.MobOverlayStyle;
import cpw.mods.fml.relauncher.ReflectionHelper;
public class WorldOverlayRenderer implements IKeyStateTracker {
@@ -32,14 +27,20 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
public static int chunkOverlay = 0;
public static int mobOverlay = 0;
private static byte[] mobSpawnCache;
private static long mobOverlayUpdateTime;
private static final MobOverlayScan MOB_OVERLAY_SCAN = new MobOverlayScan();
private static final MobOverlayFace MARKED_FACE = new MobOverlayFace();
private static final MobOverlayDisplayList MOB_OVERLAY_LIST = new MobOverlayDisplayList();
public static void reset() {
mobOverlay = 0;
chunkOverlay = 0;
}
public static void onWorldUnload() {
MOB_OVERLAY_SCAN.clear();
MOB_OVERLAY_LIST.delete();
}
@Override
public void tickKeyStates() {
if (Minecraft.getMinecraft().currentScreen != null) return;
@@ -82,158 +83,97 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glPopAttrib();
}
private static void buildMobSpawnOverlay(Entity entity) {
if (mobSpawnCache == null) {
mobSpawnCache = new byte[33 * 33 * 33]; // 35kB
}
World world = entity.worldObj;
int worldHeight = world.getHeight();
int x1 = (int) entity.posX;
int z1 = (int) entity.posZ;
int y1 = (int) MathHelper.clip(entity.posY, 16, worldHeight - 16);
for (int i = 0; i <= 32; i++) {
int x = x1 - 16 + i;
for (int j = 0; j <= 32; j++) {
int z = z1 - 16 + j;
int bufIndex = (i * 33 + j) * 33;
Chunk chunk = world.getChunkFromBlockCoords(x, z);
BiomeGenBase biome = world.getBiomeGenForCoords(x, z);
if (biome.getSpawnableList(EnumCreatureType.monster).isEmpty() || biome.getSpawningChance() <= 0) {
mobSpawnCache[bufIndex] = -1;
continue;
}
int maxHeight = chunk.worldObj.getHeightValue(x, z);
for (int k = 0; k <= 32; k++) {
int y = y1 - 16 + k;
if (y >= worldHeight) {
mobSpawnCache[bufIndex + k] = -1;
continue;
}
if (y > maxHeight) {
mobSpawnCache[bufIndex + k] = -1;
break;
}
mobSpawnCache[bufIndex + k] = getSpawnMode(chunk, x, y, z);
}
}
}
}
private static double getOverlayYOffset(World world, int x, int y, int z) {
Block block = world.getBlock(x, y, z);
if (block instanceof BlockSnow) {
int meta = world.getBlockMetadata(x, y, z) & 7;
return (1 + meta) / 8.0 + 0.02;
}
return 0.02;
}
/**
* The model view matrix is relative to ({@code intOffsetX}, {@code intOffsetY}, {@code intOffsetZ}), the camera
* position cast to {@code int}.
*/
private static void renderMobSpawnOverlay(Entity entity, int intOffsetX, int intOffsetY, int intOffsetZ) {
if (mobOverlay == 0) {
if (mobSpawnCache != null) {
mobSpawnCache = null;
}
MOB_OVERLAY_SCAN.clear();
MOB_OVERLAY_LIST.delete();
return;
}
long worldTime = entity.worldObj.getTotalWorldTime();
if (mobSpawnCache == null || mobOverlayUpdateTime != worldTime) {
mobOverlayUpdateTime = worldTime;
buildMobSpawnOverlay(entity);
MOB_OVERLAY_SCAN.update(
entity,
NEIClientConfig.getIntSetting("world.overlays.mobOverlayRadius"),
NEIClientConfig.getIntSetting("world.overlays.mobOverlayVerticalRadius"));
final MobOverlayStyle style = MobOverlayStyle
.parseStyle(NEIClientConfig.getSetting("world.overlays.mobOverlayStyle").getValue());
final long worldTicks = entity.worldObj.getTotalWorldTime();
if (MOB_OVERLAY_LIST.isCompileDue(MOB_OVERLAY_SCAN.getModesVersion(), style, worldTicks)) {
compileMobOverlayList(style, worldTicks);
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
beginMobOverlayDraw(style);
MOB_OVERLAY_LIST.draw(intOffsetX, intOffsetY, intOffsetZ);
endMobOverlayDraw();
}
/**
* Add a marked face to {@link #MOB_OVERLAY_LIST} for each block of {@link #MOB_OVERLAY_SCAN} where mobs can spawn.
*/
private static void compileMobOverlayList(MobOverlayStyle style, long worldTicks) {
MOB_OVERLAY_LIST.beginCompile(MOB_OVERLAY_SCAN, style, worldTicks);
final float alpha = style.computeAlpha();
final Tessellator tess = Tessellator.instance;
tess.startDrawing(style.glMode);
final int span = MOB_OVERLAY_SCAN.getSpan();
for (int i = 0; i < span; i++) {
for (int j = 0; j < span; j++) {
for (int k = 0; k < MOB_OVERLAY_SCAN.getHeight(); k++) {
if (MOB_OVERLAY_SCAN.readSpawnMode(i, k, j) == 0) continue;
MARKED_FACE.moveTo(i, k + MOB_OVERLAY_SCAN.readOverlayYOffset(i, k, j), j);
loadNeighbourModes(i, k, j);
MARKED_FACE.applyColor(style.colouring, alpha);
style.addVertices(MARKED_FACE);
}
}
}
tess.draw();
MOB_OVERLAY_LIST.endCompile();
}
private static void beginMobOverlayDraw(MobOverlayStyle style) {
final ResourceLocation texture = style.texture;
if (texture == null) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
} else {
GL11.glEnable(GL11.GL_TEXTURE_2D);
Minecraft.getMinecraft().getTextureManager().bindTexture(texture);
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glLineWidth(1.5F);
// the outline of `MobOverlayStyle.CONNECTED` lies in the plane of the tint. With depth writes on, the depth
// test discards most of the outline
GL11.glDepthMask(false);
}
int curSpawnMode = 2;
World world = entity.worldObj;
int x1 = (int) entity.posX - intOffsetX;
int z1 = (int) entity.posZ - intOffsetZ;
int y1 = (int) MathHelper.clip(entity.posY, 16, world.getHeight() - 16) - intOffsetY;
final Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_LINES);
tess.setColorOpaque(255, 0, 0);
for (int i = 0; i <= 32; i++) {
int x = x1 - 16 + i;
for (int j = 0; j <= 32; j++) {
int z = z1 - 16 + j;
int cacheIndex = (i * 33 + j) * 33;
for (int k = 0; k <= 32; k++) {
int y = y1 - 16 + k;
int spawnMode = mobSpawnCache[cacheIndex + k];
if (spawnMode == 0) {
continue;
} else if (spawnMode == -1) {
break;
}
if (spawnMode != curSpawnMode) {
if (spawnMode == 1) {
tess.setColorOpaque(255, 255, 0);
} else {
tess.setColorOpaque(255, 0, 0);
}
curSpawnMode = spawnMode;
}
double yOff = getOverlayYOffset(world, x + intOffsetX, y + intOffsetY, z + intOffsetZ);
tess.addVertex(x, y + yOff, z);
tess.addVertex(x + 1, y + yOff, z + 1);
tess.addVertex(x + 1, y + yOff, z);
tess.addVertex(x, y + yOff, z + 1);
}
private static void loadNeighbourModes(int i, int k, int j) {
final int span = MOB_OVERLAY_SCAN.getSpan();
for (int offsetX = -1; offsetX <= 1; offsetX++) {
for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
final int neighbourI = i + offsetX;
final int neighbourJ = j + offsetZ;
final boolean isInScan = neighbourI >= 0 && neighbourI < span && neighbourJ >= 0 && neighbourJ < span;
final byte spawnMode = isInScan ? MOB_OVERLAY_SCAN.readSpawnMode(neighbourI, k, neighbourJ)
: MobOverlayFace.OUTSIDE_SCAN;
MARKED_FACE.setNeighbourMode(offsetX, offsetZ, spawnMode);
}
}
}
tess.draw();
/** Undo the GL state changes of {@link #beginMobOverlayDraw}, except the texture binding. */
private static void endMobOverlayDraw() {
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
private static final Entity dummyEntity = new EntityPig(null);
private static final AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(0, 0, 0, 0, 0, 0);
private static byte getSpawnMode(Chunk chunk, int x, int y, int z) {
if (y >= chunk.worldObj.getHeight()) {
return 0;
}
if (chunk.getSavedLightValue(EnumSkyBlock.Block, x & 15, y, z & 15) >= 8
|| !SpawnerAnimals.canCreatureTypeSpawnAtLocation(EnumCreatureType.monster, chunk.worldObj, x, y, z)) {
return 0;
}
aabb.minX = x + 0.2;
aabb.maxX = x + 0.8;
aabb.minY = y + 0.01;
aabb.maxY = y + 1.8;
aabb.minZ = z + 0.2;
aabb.maxZ = z + 0.8;
if (!chunk.worldObj.getCollidingBoundingBoxes(dummyEntity, aabb).isEmpty()
|| chunk.worldObj.isAnyLiquid(aabb)) {
return 0;
}
return (byte) (chunk.getSavedLightValue(EnumSkyBlock.Sky, x & 15, y, z & 15) >= 8 ? 1 : 2);
}
private static void renderChunkBounds(Entity entity, int intOffsetX, int intOffsetY, int intOffsetZ) {
if (chunkOverlay == 0) return;
@@ -19,6 +19,7 @@ import org.lwjgl.input.Keyboard;
import com.google.common.collect.Sets;
import codechicken.nei.BookmarkContainerInfo;
import codechicken.nei.CollapsibleItems;
import codechicken.nei.ItemList;
import codechicken.nei.ItemSorter;
import codechicken.nei.ItemStackSet;
@@ -341,6 +342,30 @@ public class API {
SubsetWidget.addTag(tag);
}
/**
* Registers a group of items that is collapsed into a single entry in the item panel. Groups registered here have
* the lowest priority: an item that matches a preset or a collapsibleitems.cfg group stays there. They are active
* only while the Collapsible Items option is enabled. Must be called while plugins are loading.
*
* @param filter A search string for matching items that belong to this group. Also identifies the group when its
* expanded state is saved, so changing it resets the saved state.
* @return A handle to optionally set the name shown for the group
*/
public static CollapsibleItems.ApiGroup addCollapsibleGroup(String filter) {
return CollapsibleItems.registerGroup(filter);
}
/**
* Same as {@link #addCollapsibleGroup(String)}, but the group is given as a list of item stacks. The stacks
* identify the group when its expanded state is saved, so changing them resets the saved state.
*
* @param items Item stacks that belong to this group
* @return A handle to optionally set the name shown for the group
*/
public static CollapsibleItems.ApiGroup addCollapsibleGroup(Iterable<ItemStack> items) {
return CollapsibleItems.registerGroup(items);
}
@Deprecated
public static void addSearchProvider(ISearchProvider provider) {}
@@ -10,6 +10,8 @@ import java.util.Map;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import org.lwjgl.input.Mouse;
@@ -19,6 +21,7 @@ import codechicken.nei.BookmarkContainerInfo;
import codechicken.nei.FavoriteRecipes;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemQuantityField;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.KeyManager;
import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
@@ -205,9 +208,24 @@ public abstract class ShortcutInputHandler {
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() : ""));
String clipboard;
if (StackInfo.isFluidDisplayItem(stackover)) {
final FluidStack fluid = StackInfo.getFluid(stackover);
if (fluid == null) {
return false;
}
clipboard = FluidRegistry.getDefaultFluidName(fluid.getFluid());
} else {
clipboard = stackover.getItem().delegate.name()
+ (stackover.getItemDamage() != 0 ? "/" + stackover.getItemDamage() : "");
}
GuiScreen.setClipboardString(clipboard);
return true;
}
@@ -700,7 +718,7 @@ public abstract class ShortcutInputHandler {
private static void autocraftingIgnoreInventory(RecipeChainMath math) {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final List<ItemStack> playerInventory = AutoCraftingManager.getInventoryItems(guiContainer).values();
final List<ItemStack> playerInventory = ItemStackAmount.of(guiContainer).values();
final RecipeId rootRecipeId = math.createMasterRoot();
for (int i = 0; i < math.recipeIngredients.size(); i++) {
@@ -7,7 +7,6 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemSorter;
@@ -132,7 +131,7 @@ public class BookmarkGridGenerator {
itemIndex++;
}
} else if (group.crafting != null && group.crafting.itemToRecipe.values().contains(bookmarkItem.recipeId)) {
} else if (group.crafting != null && group.crafting.recipeToItems.containsKey(bookmarkItem.recipeId)) {
absoluteSlotIndex = generateCollapsedRecipe(prevBookmarkItem, itemIndex, absoluteSlotIndex, borderGrid);
prevBookmarkItem = bookmarkItem;
@@ -218,8 +217,7 @@ public class BookmarkGridGenerator {
}
private List<Integer> getShadows(BookmarkGroup group, RecipeId recipeId) {
return group.crafting.itemToRecipe.entrySet().stream().filter(entry -> recipeId.equals(entry.getValue()))
.map(entry -> entry.getKey()).collect(Collectors.toList());
return new ArrayList<>(group.crafting.recipeToItems.getOrDefault(recipeId, Collections.emptyList()));
}
private int nextSlotIndex(int index, BookmarkItem previousMeta, BookmarkItem meta, BookmarkViewMode viewMode) {
@@ -111,6 +111,7 @@ public class RecipeChainDetails {
public final Map<Integer, BookmarkChainItem> calculatedItems = new HashMap<>();
public final Map<Integer, RecipeId> itemToRecipe = new HashMap<>();
public final Map<RecipeId, List<Integer>> recipeToItems = new HashMap<>();
public final Set<RecipeId> outputRecipes = new HashSet<>();
public final Set<RecipeId> recipeInMiddle = new HashSet<>();
@@ -124,6 +125,7 @@ public class RecipeChainDetails {
}
this.itemToRecipe.clear();
this.recipeToItems.clear();
this.outputRecipes.clear();
this.recipeInMiddle.clear();
this.calculatedItems.clear();
@@ -180,6 +182,10 @@ public class RecipeChainDetails {
}
for (Map.Entry<Integer, RecipeId> entry : this.itemToRecipe.entrySet()) {
this.recipeToItems.computeIfAbsent(entry.getValue(), recipeId -> new ArrayList<>()).add(entry.getKey());
}
for (Map.Entry<Integer, BookmarkItem> entry : chainItems.entrySet()) {
final int itemIndex = entry.getKey();
if (itemIndex >= 0 && this.calculatedItems.containsKey(itemIndex)) {
@@ -37,8 +37,8 @@ public class SortableItem {
&& (group.viewMode == BookmarkViewMode.TODO_LIST || group.crafting != null);
this.crossGroup = !group.collapsed && group.viewMode == BookmarkViewMode.TODO_LIST
&& bookmarkItem.type != BookmarkItemType.INGREDIENT;
this.isCollapsedRecipe = group.crafting != null && group.crafting.itemToRecipe.values().stream()
.anyMatch(recipeId -> this.bookmarkItem.equalsRecipe(recipeId, this.bookmarkItem.groupId));
this.isCollapsedRecipe = group.crafting != null && this.bookmarkItem.recipeId != null
&& group.crafting.recipeToItems.containsKey(this.bookmarkItem.recipeId);
this.update();
}
@@ -52,14 +52,7 @@ class CraftingTreeToolbar {
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glTranslated(iconX, iconY, 0);
GL11.glScalef(0.5f, 0.5f, 1);
icon.bindTexture();
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
icon.draw(0, 0);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
@@ -36,6 +36,7 @@ import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemStackAmount;
import codechicken.nei.KeyManager;
import codechicken.nei.LRUCache;
import codechicken.nei.NEICPH;
@@ -60,7 +61,6 @@ import codechicken.nei.guihook.IGuiClientSide;
import codechicken.nei.guihook.IGuiHandleMouseWheel;
import codechicken.nei.guihook.IGuiHotkeyListener;
import codechicken.nei.recipe.AcceptsFollowingTooltipLineHandler;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiOverlayButton;
import codechicken.nei.recipe.GuiRecipe;
@@ -284,10 +284,8 @@ public class GuiCraftingTree extends GuiContainer implements INEIGuiHandler, IGu
final GuiContainer firstGui = getFirstScreen();
if (firstGui != null) {
for (ItemStack stack : AutoCraftingManager.getInventoryItems(firstGui).values()) {
if (stack != null) {
this.math.initialItems.add(BookmarkItem.of(-1, stack));
}
for (ItemStack stack : ItemStackAmount.of(firstGui).values()) {
this.math.initialItems.add(BookmarkItem.of(-1, stack));
}
}
}
@@ -524,7 +524,7 @@ class StatsPanel extends ScrollContainer {
public ItemStack getStackMouseOver(int mouseX, int mouseY) {
final Widget widget = getWidgetUnderMouse(mouseX, mouseY);
return widget instanceof ItemStatsSlot slot && slot.recipeId == null ? slot.getStack() : null;
return widget instanceof ItemStatsSlot slot ? slot.getStack() : null;
}
public void setHighlight(SearchResult searchResult) {
@@ -3,25 +3,15 @@ package codechicken.nei.bookmark.tree;
import java.util.List;
import java.util.Map;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.recipe.GuiRecipeButton;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.theme.UIRecipeTexture;
public class TreeOverlayButton extends GuiRecipeButton {
protected static final DrawableResource ICON_FILL = new DrawableBuilder(
"nei:textures/nei_sprites.png",
28,
76,
9,
10).build();
protected static final int BUTTON_ID_SHIFT = 4;
public final GuiCraftingTree treeGui;
@@ -50,16 +40,8 @@ public class TreeOverlayButton extends GuiRecipeButton {
}
@Override
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
final int iconX = this.xPosition + (this.width - ICON_FILL.width - 1) / 2;
final int iconY = this.yPosition + (this.height - ICON_FILL.height) / 2;
GL11.glColor4f(1, 1, 1, this.enabled ? 1 : 0.5f);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
ICON_FILL.draw(iconX, iconY);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
protected DrawableResource getIcon() {
return UIRecipeTexture.ICON_OVERLAY_FILL;
}
@Override
@@ -109,6 +109,8 @@ public class IMCHandler {
info.setShowFavoritesButton(!tag.hasKey("showFavoritesButton") || tag.getBoolean("showFavoritesButton"));
info.setShowOverlayButton(!tag.hasKey("showOverlayButton") || tag.getBoolean("showOverlayButton"));
info.setShowBadge(tag.hasKey("showBadge") && tag.getBoolean("showBadge"));
info.setWindowWidth(tag.getInteger("windowWidth"));
info.setRecipeSpacing(tag.getBoolean("recipeSpacing"));
GuiRecipeTab.handlerAdderFromIMC.remove(handler);
GuiRecipeTab.handlerAdderFromIMC.put(handler, info);
@@ -0,0 +1,57 @@
package codechicken.nei.drawable;
public interface Drawable {
@FunctionalInterface
public interface Painter {
public void draw(int x, int y, int width, int height);
}
public int getWidth();
public int getHeight();
public void draw(int x, int y, int width, int height);
default void draw(int x, int y) {
draw(x, y, getWidth(), getHeight());
}
public static Drawable of(int width, int height, Painter painter) {
return new Drawable() {
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void draw(int x, int y, int w, int h) {
painter.draw(x, y, w, h);
}
};
}
// every layer is drawn into the whole rectangle, the first one at the bottom
public static Drawable stack(Drawable... layers) {
int width = 0;
int height = 0;
for (Drawable layer : layers) {
width = Math.max(width, layer.getWidth());
height = Math.max(height, layer.getHeight());
}
return of(width, height, (x, y, w, h) -> {
for (Drawable layer : layers) {
layer.draw(x, y, w, h);
}
});
}
}
@@ -8,7 +8,7 @@ import org.lwjgl.opengl.GL11;
import codechicken.nei.Image;
public class DrawableResource extends Image {
public class DrawableResource extends Image implements Drawable {
private final ResourceLocation resourceLocation;
private final int textureWidth;
@@ -220,8 +220,9 @@ public class DrawableResource extends Image {
final float scaleU = 1.0F / this.textureWidth;
final float scaleV = 1.0F / this.textureHeight;
final int x = xOffset + this.paddingLeft;
final int y = yOffset + this.paddingTop;
// 1/64 shift keeps pixel centers off texel edges, where NEAREST picks a texel at random when downscaled
final double x = xOffset + this.paddingLeft + 1 / 64d;
final double y = yOffset + this.paddingTop + 1 / 64d;
final float u0 = (this.x + u) * scaleU;
final float u1 = (this.x + u + width) * scaleU;
final float v0 = (this.y + v) * scaleV;
@@ -9,6 +9,7 @@ import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeRole;
public class RecipeFilter implements IRecipeFilter {
@@ -47,17 +48,17 @@ public class RecipeFilter implements IRecipeFilter {
public boolean matches(IRecipeHandler handler, int recipeIndex) {
if ((this.context == FilterContext.ANY || this.context == FilterContext.INPUT)
&& matchPositionedStack(handler.getIngredientStacks(recipeIndex), this.anyMatch)) {
&& matchPositionedStack(handler.getSearchStacks(recipeIndex, RecipeRole.INPUT), this.anyMatch)) {
return this.anyMatch;
}
if ((this.context == FilterContext.ANY || this.context == FilterContext.OUTPUT)
&& matchPositionedStack(handler.getResultStacks(recipeIndex), this.anyMatch)) {
&& matchPositionedStack(handler.getSearchStacks(recipeIndex, RecipeRole.OUTPUT), this.anyMatch)) {
return this.anyMatch;
}
if ((this.context == FilterContext.ANY || this.context == FilterContext.AUXILIARY)
&& matchPositionedStack(handler.getAuxiliaryStacks(recipeIndex), this.anyMatch)) {
&& matchPositionedStack(handler.getSearchStacks(recipeIndex, RecipeRole.AUXILIARY), this.anyMatch)) {
return this.anyMatch;
}
@@ -0,0 +1,32 @@
package codechicken.nei.filter;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.recipe.IRecipeHandler;
public class RecipeTextFilter implements IRecipeFilter {
private final Predicate<List<String>> lines;
public RecipeTextFilter(Predicate<List<String>> lines) {
this.lines = lines;
}
public static Predicate<List<String>> matching(Pattern pattern) {
return lines -> {
for (String line : lines) {
if (pattern.matcher(line).find()) return true;
}
return false;
};
}
@Override
public boolean matches(IRecipeHandler handler, int recipeIndex) {
final List<String> text = handler.getSearchText(recipeIndex);
return !text.isEmpty() && this.lines.test(text);
}
}
@@ -640,7 +640,7 @@ public class GuiContainerManager {
tooltip = handler.handleTooltip(window, mousex, mousey, tooltip);
}
ItemStack stack = getStackMouseOver(window);
ItemStack stack = tooltip.isEmpty() ? getStackMouseOver(window) : null;
boolean showTooltip = shouldShowTooltip(window);
if (tooltip.isEmpty() && showTooltip) { // mouseover tip, not holding an item
font = getFontRenderer(stack);
@@ -937,9 +937,11 @@ public class GuiContainerManager {
}
public void keyTyped(char c, int k) {
if (firstKeyTyped(c, k)) return;
KeyManager.handleKeyEvent(k, () -> {
if (firstKeyTyped(c, k)) return;
callKeyTyped(window, c, k);
callKeyTyped(window, c, k);
});
}
private static void callKeyTyped(GuiContainer window, char c, int k) {
@@ -0,0 +1,65 @@
package codechicken.nei.moboverlay;
import net.minecraft.client.renderer.GLAllocation;
import org.lwjgl.opengl.GL11;
/** The mob spawn overlay quads, compiled into a GL display list. */
public final class MobOverlayDisplayList {
private int listId = -1;
private int modesVersion;
private MobOverlayStyle style;
private int minX;
private int minY;
private int minZ;
private long compiledTicks;
/**
* Compiles after a {@link MobOverlayScan#getModesVersion} change are debounced to one per {@code MIN_COMPILE_TICKS}
* ticks, because the version changes several times per second while the player moves fast, and a compile runs for a
* millisecond or more.
*/
public boolean isCompileDue(int currentModesVersion, MobOverlayStyle currentStyle, long worldTicks) {
final int MIN_COMPILE_TICKS = 5;
if (listId < 0 || style != currentStyle) return true;
// after a dimension change or a server switch, `worldTicks` can be lower than `compiledTicks`
final boolean isWaitOver = worldTicks - compiledTicks >= MIN_COMPILE_TICKS || worldTicks < compiledTicks;
return modesVersion != currentModesVersion && isWaitOver;
}
/**
* Quad positions are relative to block ({@link MobOverlayScan#getMinX}, {@link MobOverlayScan#getMinY},
* {@link MobOverlayScan#getMinZ}) of {@code scan}.
*/
public void beginCompile(MobOverlayScan scan, MobOverlayStyle newStyle, long worldTicks) {
if (listId < 0) listId = GLAllocation.generateDisplayLists(1);
modesVersion = scan.getModesVersion();
style = newStyle;
minX = scan.getMinX();
minY = scan.getMinY();
minZ = scan.getMinZ();
compiledTicks = worldTicks;
GL11.glNewList(listId, GL11.GL_COMPILE);
}
public void endCompile() {
GL11.glEndList();
}
/** The model view matrix is relative to block ({@code cameraX}, {@code cameraY}, {@code cameraZ}). */
public void draw(int cameraX, int cameraY, int cameraZ) {
GL11.glPushMatrix();
GL11.glTranslated(minX - cameraX, minY - cameraY, minZ - cameraZ);
GL11.glCallList(listId);
GL11.glPopMatrix();
}
public void delete() {
if (listId < 0) return;
GLAllocation.deleteDisplayLists(listId);
listId = -1;
}
}
@@ -0,0 +1,88 @@
package codechicken.nei.moboverlay;
import net.minecraft.client.renderer.Tessellator;
/** Vertex builder for one block's top face in the mob spawn overlay. */
public final class MobOverlayFace {
public static final byte OUTSIDE_SCAN = -2;
private static final int NEIGHBOURHOOD_SIZE = 3;
private final byte[] neighbourModes = new byte[NEIGHBOURHOOD_SIZE * NEIGHBOURHOOD_SIZE];
private double x;
private double y;
private double z;
/** {@code (x, y, z)} is the north-west corner of the block's top face. */
public void moveTo(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public void setNeighbourMode(int offsetX, int offsetZ, byte spawnMode) {
neighbourModes[indexNeighbour(offsetX, offsetZ)] = spawnMode;
}
public void applyColor(MobOverlayStyle.Colouring colouring, float alpha) {
final boolean isNightOnly = neighbourModes[indexNeighbour(0, 0)] == MobOverlayScan.NIGHT_ONLY;
final int rgb = switch (colouring) {
case OVERLAY -> isNightOnly ? 0xFFFF00 : 0xFF0000;
case STICKER -> isNightOnly ? 0xFFFFFF : 0xFF7373;
};
Tessellator.instance.setColorRGBA_I(rgb, Math.round(alpha * 255));
}
public boolean isJoined(int offsetX, int offsetZ) {
final byte neighbourMode = neighbourModes[indexNeighbour(offsetX, offsetZ)];
// no outline along the edge of the scan
return neighbourMode == neighbourModes[indexNeighbour(0, 0)] || neighbourMode == OUTSIDE_SCAN;
}
public void addFullFace() {
addVertex(0, 0);
addVertex(0, 1);
addVertex(1, 1);
addVertex(1, 0);
}
/** Add one cell of a 3 x 3 grid over the face. The outer rows and columns of the grid are {@code width} wide. */
public void addCell(int offsetX, int offsetZ, double width) {
final double west = computeCellStart(offsetX, width);
final double east = 1 - computeCellStart(-offsetX, width);
final double north = computeCellStart(offsetZ, width);
final double south = 1 - computeCellStart(-offsetZ, width);
addVertex(west, north);
addVertex(west, south);
addVertex(east, south);
addVertex(east, north);
}
/** The texture is upright to a player facing north (-z). */
public void addTexturedFace() {
addTexturedVertex(0, 0);
addTexturedVertex(0, 1);
addTexturedVertex(1, 1);
addTexturedVertex(1, 0);
}
/** @param offsetX 0 at the west edge, 1 at the east edge */
public void addVertex(double offsetX, double offsetZ) {
Tessellator.instance.addVertex(x + offsetX, y, z + offsetZ);
}
private void addTexturedVertex(double offsetX, double offsetZ) {
Tessellator.instance.setTextureUV(offsetX, offsetZ);
addVertex(offsetX, offsetZ);
}
private static int indexNeighbour(int offsetX, int offsetZ) {
return (offsetX + 1) * NEIGHBOURHOOD_SIZE + offsetZ + 1;
}
private static double computeCellStart(int offset, double width) {
if (offset < 0) return 0;
return offset == 0 ? width : 1 - width;
}
}
@@ -0,0 +1,420 @@
package codechicken.nei.moboverlay;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.IWorldAccess;
import net.minecraft.world.SpawnerAnimals;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import codechicken.lib.math.MathHelper;
/**
* Spawn modes, and the tops of flat blocks such as carpets, in a box around the player. The spawn modes are from
* {@link Column#getSpawnMode}: 0 for no spawns, 1 for night only and 2 for any time. The box moves with the player once
* the player is a few blocks from the box's centre, and {@link #update} scans only the blocks that enter the box.
* {@link #update} rescans the column of a block or light change on the next tick. On each tick, {@link #update} also
* rescans a slice of the columns, for changes with no block update, such as a boat that moves into the box.
*/
public final class MobOverlayScan {
public static final byte NIGHT_ONLY = 1;
public static final int MIN_RADIUS = 8;
public static final int MAX_RADIUS = 64;
public static final int DEFAULT_RADIUS = 32;
public static final int MIN_VERTICAL_RADIUS = 4;
public static final int MAX_VERTICAL_RADIUS = 64;
public static final int DEFAULT_VERTICAL_RADIUS = 16;
private static final int RECENTRE_DISTANCE = 4;
private static final int VERTICAL_RECENTRE_DISTANCE = 2;
private static final int RESCAN_TICKS = 40;
private static final int SPAWN_MODE_MASK = 3;
private static final int COVER_TOP_SHIFT = 2;
private static final int COVER_TOP_STEPS = 32;
private final IWorldAccess changeListener = new ChangeListener();
private final Column column = new Column();
private int radius;
private int verticalRadius;
private int span;
private int height;
// a ring buffer over the box, indexed by `findCell()`. A cell has the spawn mode in the bits of `SPAWN_MODE_MASK`,
// and `Column.readCoverTop()` shifted left by `COVER_TOP_SHIFT`
private byte[] modes = new byte[0];
// indexed by `findColumn(x, z)`
private boolean[] dirty = new boolean[0];
private boolean hasDirtyColumns;
private int minX;
private int minY;
private int minZ;
// the slice rescan of `update()` continues from this column, numbered `(x - minX) * span + (z - minZ)`
private int nextRescanColumn;
private int modesVersion;
private boolean hasModes;
private long scannedTick;
// world of `modes`, with `changeListener` added
private World scannedWorld;
public void clear() {
if (scannedWorld == null && span == 0) return;
if (scannedWorld != null) scannedWorld.removeWorldAccess(changeListener);
radius = 0;
verticalRadius = 0;
span = 0;
height = 0;
modes = new byte[0];
dirty = new boolean[0];
hasModes = false;
scannedWorld = null;
// `Chunk.worldObj` references the world
column.chunk = null;
}
/**
* Scan every column in this call after {@link #clear}, a change of either radius, a world change, or a move of
* {@link #getSpan} blocks or more across or {@link #getHeight} blocks or more up or down. {@code newRadius} is
* clamped between {@link #MIN_RADIUS} and {@link #MAX_RADIUS}, and {@code newVerticalRadius} between
* {@link #MIN_VERTICAL_RADIUS} and {@link #MAX_VERTICAL_RADIUS}.
*/
public void update(Entity entity, int newRadius, int newVerticalRadius) {
final World world = entity.worldObj;
final int clampedRadius = (int) MathHelper.clip(newRadius, MIN_RADIUS, MAX_RADIUS);
final int clampedVerticalRadius = (int) MathHelper
.clip(newVerticalRadius, MIN_VERTICAL_RADIUS, MAX_VERTICAL_RADIUS);
if (radius != clampedRadius || verticalRadius != clampedVerticalRadius) {
resize(clampedRadius, clampedVerticalRadius);
}
final int centreX = MathHelper.floor_double(entity.posX);
final int centreY = (int) MathHelper.clip(entity.posY, verticalRadius, world.getHeight() - verticalRadius);
final int centreZ = MathHelper.floor_double(entity.posZ);
final boolean isNearBox = Math.abs(centreX - radius - minX) < span && Math.abs(centreZ - radius - minZ) < span
&& Math.abs(centreY - verticalRadius - minY) < height;
if (!(hasModes && world == scannedWorld && isNearBox)) {
if (world != scannedWorld) watchWorld(world);
scanFullBox(centreX, centreY, centreZ);
return;
}
final long worldTicks = world.getTotalWorldTime();
if (worldTicks == scannedTick) return;
scannedTick = worldTicks;
boolean isChanged = moveBox(centreX, centreY, centreZ);
if (hasDirtyColumns) isChanged |= rescanDirtyColumns();
isChanged |= rescanSlice();
if (isChanged) modesVersion++;
}
/** The version changes when a spawn mode or the top of a flat block changes, or the box moves. */
public int getModesVersion() {
return modesVersion;
}
public int getSpan() {
return span;
}
public int getHeight() {
return height;
}
public int getMinX() {
return minX;
}
public int getMinY() {
return minY;
}
public int getMinZ() {
return minZ;
}
/** {@code i} and {@code j} are from 0 to {@link #getSpan}, and {@code k} is from 0 to {@link #getHeight}. */
public byte readSpawnMode(int i, int k, int j) {
return (byte) (modes[findCell(minX + i, minY + k, minZ + j)] & SPAWN_MODE_MASK);
}
/**
* Height of the overlay above the bottom of the block, so that a flat block such as a carpet does not cover the
* overlay. The indices are those of {@link #readSpawnMode}.
*/
public double readOverlayYOffset(int i, int k, int j) {
final double OVERLAY_GAP = 0.02;
final int coverTopSteps = modes[findCell(minX + i, minY + k, minZ + j)] >> COVER_TOP_SHIFT;
return (double) coverTopSteps / COVER_TOP_STEPS + OVERLAY_GAP;
}
private void resize(int newRadius, int newVerticalRadius) {
radius = newRadius;
verticalRadius = newVerticalRadius;
span = 2 * newRadius + 1;
height = 2 * newVerticalRadius + 1;
modes = new byte[span * span * height];
dirty = new boolean[span * span];
hasModes = false;
nextRescanColumn = 0;
}
private void scanFullBox(int centreX, int centreY, int centreZ) {
minX = centreX - radius;
minY = centreY - verticalRadius;
minZ = centreZ - radius;
for (int x = minX; x < minX + span; x++) {
for (int z = minZ; z < minZ + span; z++) {
scanColumn(x, z);
}
}
hasModes = true;
modesVersion++;
scannedTick = scannedWorld.getTotalWorldTime();
}
private void watchWorld(World world) {
if (scannedWorld != null) scannedWorld.removeWorldAccess(changeListener);
world.addWorldAccess(changeListener);
scannedWorld = world;
}
/** @return whether the box moved */
private boolean moveBox(int centreX, int centreY, int centreZ) {
boolean isMoved = false;
final int offsetX = centreX - radius - minX;
if (Math.abs(offsetX) > RECENTRE_DISTANCE) {
final int enteringX = offsetX > 0 ? minX + span : minX + offsetX;
minX += offsetX;
for (int x = enteringX; x < enteringX + Math.abs(offsetX); x++) {
for (int z = minZ; z < minZ + span; z++) {
scanColumn(x, z);
}
}
isMoved = true;
}
final int offsetZ = centreZ - radius - minZ;
if (Math.abs(offsetZ) > RECENTRE_DISTANCE) {
final int enteringZ = offsetZ > 0 ? minZ + span : minZ + offsetZ;
minZ += offsetZ;
for (int x = minX; x < minX + span; x++) {
for (int z = enteringZ; z < enteringZ + Math.abs(offsetZ); z++) {
scanColumn(x, z);
}
}
isMoved = true;
}
final int offsetY = centreY - verticalRadius - minY;
if (Math.abs(offsetY) > VERTICAL_RECENTRE_DISTANCE) {
final int enteringY = offsetY > 0 ? minY + height : minY + offsetY;
minY += offsetY;
for (int x = minX; x < minX + span; x++) {
for (int z = minZ; z < minZ + span; z++) {
column.moveTo(x, z);
column.scan(enteringY, enteringY + Math.abs(offsetY));
}
}
isMoved = true;
}
return isMoved;
}
private boolean rescanDirtyColumns() {
hasDirtyColumns = false;
boolean isChanged = false;
for (int x = minX; x < minX + span; x++) {
for (int z = minZ; z < minZ + span; z++) {
if (dirty[findColumn(x, z)]) isChanged |= scanColumn(x, z);
}
}
return isChanged;
}
private boolean rescanSlice() {
final int columnCount = span * span;
final int sliceEnd = Math.min(columnCount, nextRescanColumn + (columnCount + RESCAN_TICKS - 1) / RESCAN_TICKS);
boolean isChanged = false;
for (; nextRescanColumn < sliceEnd; nextRescanColumn++) {
final int x = minX + nextRescanColumn / span;
final int z = minZ + nextRescanColumn % span;
isChanged |= scanColumn(x, z);
}
if (nextRescanColumn >= columnCount) nextRescanColumn = 0;
return isChanged;
}
/** @return whether a spawn mode or the top of a flat block changed */
private boolean scanColumn(int x, int z) {
column.moveTo(x, z);
dirty[findColumn(x, z)] = false;
return column.scan(minY, minY + height);
}
private int findColumn(int x, int z) {
return Math.floorMod(x, span) * span + Math.floorMod(z, span);
}
private int findCell(int x, int y, int z) {
return findColumn(x, z) * height + Math.floorMod(y, height);
}
/**
* {@link #moveTo} reads a column's chunk, biome and highest non-air block in the box, and {@link #scan} reads the
* column's blocks.
*/
private final class Column {
private final Entity dummyEntity = new EntityPig(null);
private final AxisAlignedBB spawnBox = AxisAlignedBB.getBoundingBox(0, 0, 0, 0, 0, 0);
private int x;
private int z;
private Chunk chunk;
private int topY;
private boolean canBiomeSpawn;
private void moveTo(int newX, int newZ) {
x = newX;
z = newZ;
final BiomeGenBase biome = scannedWorld.getBiomeGenForCoords(x, z);
canBiomeSpawn = !biome.getSpawnableList(EnumCreatureType.monster).isEmpty()
&& biome.getSpawningChance() > 0;
chunk = scannedWorld.getChunkFromBlockCoords(x, z);
// `getHeightValue()` is the height above the highest block with a light opacity above 0. A block with a
// light opacity of 0 can be higher: Tinkers' Construct slime grass, a hopper or a snow layer. A mob can
// spawn on top of slime grass, a hopper or a full snow block. Search the blocks for the highest non-air
// block
final int SECTION_HEIGHT = 16;
int y = Math.min(minY + height - 1, chunk.getTopFilledSegment() + SECTION_HEIGHT - 1);
while (y >= minY && chunk.getBlock(x & 15, y, z & 15).isAir(chunk.worldObj, x, y, z)) y--;
topY = y + 1;
}
/** @return whether a spawn mode or the top of a flat block changed */
private boolean scan(int fromY, int toY) {
boolean isChanged = false;
for (int y = fromY; y < toY; y++) {
final int spawnMode = canBiomeSpawn && y <= topY ? getSpawnMode(y) : 0;
final byte cellValue = (byte) (spawnMode == 0 ? 0 : spawnMode | (readCoverTop(y) << COVER_TOP_SHIFT));
final int cell = findCell(x, y, z);
isChanged |= modes[cell] != cellValue;
modes[cell] = cellValue;
}
return isChanged;
}
/** The spawn mode of the block at height {@code y} in this column. */
private byte getSpawnMode(int y) {
if (y >= chunk.worldObj.getHeight()) {
return 0;
}
if (chunk.getSavedLightValue(EnumSkyBlock.Block, x & 15, y, z & 15) >= 8 || !SpawnerAnimals
.canCreatureTypeSpawnAtLocation(EnumCreatureType.monster, chunk.worldObj, x, y, z)) {
return 0;
}
// the size of a zombie, a creeper and a skeleton that is not a wither skeleton. A taller or wider monster,
// such as an enderman or a spider, needs more room
final double MOB_WIDTH = 0.6;
final double MOB_HEIGHT = 1.8;
spawnBox.minX = x + 0.5 - MOB_WIDTH / 2;
spawnBox.maxX = x + 0.5 + MOB_WIDTH / 2;
spawnBox.minY = y;
spawnBox.maxY = y + MOB_HEIGHT;
spawnBox.minZ = z + 0.5 - MOB_WIDTH / 2;
spawnBox.maxZ = z + 0.5 + MOB_WIDTH / 2;
if (!chunk.worldObj.getCollidingBoundingBoxes(dummyEntity, spawnBox).isEmpty()
|| chunk.worldObj.isAnyLiquid(spawnBox)) {
return 0;
}
return (byte) (chunk.getSavedLightValue(EnumSkyBlock.Sky, x & 15, y, z & 15) >= 8 ? 1 : 2);
}
/**
* The top of the block at height {@code y}, in fractions of a block with {@link MobOverlayScan#COVER_TOP_STEPS}
* as the denominator, or 0 for a tall block.
*/
private int readCoverTop(int y) {
final double MAX_COVER_TOP = 0.25;
final Block block = chunk.getBlock(x & 15, y, z & 15);
block.setBlockBoundsBasedOnState(chunk.worldObj, x, y, z);
final double top = block.getBlockBoundsMaxY();
// a mark on the bounds of a plant or a sloped rail would float above most of the block. Keep the mark at
// the floor for a tall block
return top > MAX_COVER_TOP ? 0 : (int) Math.ceil(top * COVER_TOP_STEPS);
}
}
/** Marks the columns of the block and light changes in {@link #scannedWorld}. */
private final class ChangeListener implements IWorldAccess {
@Override
public void markBlockForUpdate(int x, int y, int z) {
markChanged(x, y, z);
}
@Override
public void markBlockForRenderUpdate(int x, int y, int z) {
markChanged(x, y, z);
}
@Override
public void markBlockRangeForRenderUpdate(int fromX, int fromY, int fromZ, int toX, int toY, int toZ) {
for (int x = Math.max(fromX, minX); x <= Math.min(toX, minX + span - 1); x++) {
for (int z = Math.max(fromZ, minZ); z <= Math.min(toZ, minZ + span - 1); z++) {
markColumn(x, z);
}
}
}
@Override
public void playSound(String soundName, double x, double y, double z, float volume, float pitch) {}
@Override
public void playSoundToNearExcept(EntityPlayer player, String soundName, double x, double y, double z,
float volume, float pitch) {}
@Override
public void spawnParticle(String particleName, double x, double y, double z, double velocityX, double velocityY,
double velocityZ) {}
@Override
public void onEntityCreate(Entity entity) {}
@Override
public void onEntityDestroy(Entity entity) {}
@Override
public void playRecord(String recordName, int x, int y, int z) {}
@Override
public void broadcastSound(int soundId, int x, int y, int z, int data) {}
@Override
public void playAuxSFX(EntityPlayer player, int sfxType, int x, int y, int z, int data) {}
@Override
public void destroyBlockPartially(int breakerId, int x, int y, int z, int progress) {}
@Override
public void onStaticEntitiesChanged() {}
private void markChanged(int x, int y, int z) {
// spawn modes depend on the block below and the block above
final boolean isInBox = x >= minX && x < minX + span && z >= minZ && z < minZ + span;
if (isInBox && y >= minY - 1 && y <= minY + height) markColumn(x, z);
}
private void markColumn(int x, int z) {
dirty[findColumn(x, z)] = true;
hasDirtyColumns = true;
}
}
}
@@ -0,0 +1,135 @@
package codechicken.nei.moboverlay;
import java.util.Locale;
import java.util.StringJoiner;
import javax.annotation.Nullable;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
/**
* Each style is a mark drawn on every block where mobs can spawn. {@code world.overlays.mobOverlayStyle} is saved as
* {@link #formatName()}.
*/
public enum MobOverlayStyle {
/** NEI's original cross from corner to corner. */
X(GL11.GL_LINES) {
@Override
public void addVertices(MobOverlayFace face) {
face.addVertex(0, 0);
face.addVertex(1, 1);
face.addVertex(1, 0);
face.addVertex(0, 1);
}
},
/**
* A light tint, with a stronger outline around each area of one spawn mode, like a connected texture.
*/
CONNECTED(GL11.GL_QUADS) {
@Override
public void addVertices(MobOverlayFace face) {
final double OUTLINE_WIDTH = 1.0 / 16;
face.addFullFace();
face.applyColor(Colouring.OVERLAY, MARK_ALPHA);
for (int offsetX = -1; offsetX <= 1; offsetX++) {
for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
// a corner cell is drawn when either edge next to the corner is outlined, and on an inside corner
final boolean isOutline = !(face.isJoined(offsetX, offsetZ) && face.isJoined(offsetX, 0)
&& face.isJoined(0, offsetZ));
if (isOutline) face.addCell(offsetX, offsetZ, OUTLINE_WIDTH);
}
}
}
},
/** A small square in the middle of the block, with no tint. */
SQUARE(GL11.GL_QUADS) {
@Override
public void addVertices(MobOverlayFace face) {
final double CENTRE = 0.5;
final double HALF_SIDE = 7.0 / 64;
face.addVertex(CENTRE - HALF_SIDE, CENTRE - HALF_SIDE);
face.addVertex(CENTRE - HALF_SIDE, CENTRE + HALF_SIDE);
face.addVertex(CENTRE + HALF_SIDE, CENTRE + HALF_SIDE);
face.addVertex(CENTRE + HALF_SIDE, CENTRE - HALF_SIDE);
}
},
/** The pufferfish sticker. */
PUFFERFISH("pufferfish", Colouring.STICKER) {
@Override
public void addVertices(MobOverlayFace face) {
face.addTexturedFace();
}
};
public static final MobOverlayStyle DEFAULT = CONNECTED;
private static final float TINT_ALPHA = 0.15F;
// the square and the outline cover a small part of the block and need more opacity than the tint to stay visible
private static final float MARK_ALPHA = 0.45F;
public final int glMode;
@Nullable
public final ResourceLocation texture;
public final Colouring colouring;
MobOverlayStyle(int glMode) {
this.glMode = glMode;
this.texture = null;
this.colouring = Colouring.OVERLAY;
}
MobOverlayStyle(String textureName, Colouring colouring) {
this.glMode = GL11.GL_QUADS;
this.texture = new ResourceLocation("nei", "textures/overlay/" + textureName + ".png");
this.colouring = colouring;
}
/** Case-insensitive. Returns {@link #DEFAULT} for an unknown name. */
public static MobOverlayStyle parseStyle(String rawStyle) {
for (MobOverlayStyle candidate : values()) {
if (candidate.formatName().equalsIgnoreCase(rawStyle)) return candidate;
}
return DEFAULT;
}
/** @return the {@link #formatName} of every style, separated by commas */
public static String formatAllNames() {
final StringJoiner names = new StringJoiner(", ");
for (MobOverlayStyle style : values()) {
names.add(style.formatName());
}
return names.toString();
}
public String formatName() {
return name().toLowerCase(Locale.ROOT);
}
public float computeAlpha() {
return switch (this) {
case CONNECTED -> TINT_ALPHA;
case SQUARE -> MARK_ALPHA;
// opaque lines for X, and the alpha of the PNG for PUFFERFISH
case X, PUFFERFISH -> 1.0F;
};
}
public abstract void addVertices(MobOverlayFace face);
public enum Colouring {
/** Yellow where mobs spawn only at night, red where mobs spawn at any time. */
OVERLAY,
/** The texture's colours, tinted red where mobs spawn at any time. */
STICKER
}
}
@@ -32,7 +32,7 @@ public class AutoCraftingManager {
public void execute() {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
final ItemStack[] layout = snapshotLayout(guiContainer);
final List<BookmarkItem> initialItems = prepareInitialItems(math, getInventoryItems(guiContainer));
final List<BookmarkItem> initialItems = prepareInitialItems(math, ItemStackAmount.of(guiContainer));
boolean processed = false;
boolean changed = false;
@@ -43,7 +43,7 @@ public class AutoCraftingManager {
changed = false;
RecipeChainIterator iterator = new RecipeChainIterator(math, initialItems);
iterator.updateInventory(getInventoryItems(guiContainer));
iterator.updateInventory(ItemStackAmount.of(guiContainer));
while (iterator.hasNext() && !interrupted(guiContainer)) {
final Map<RecipeId, Long> recipes = iterator.next();
@@ -69,7 +69,7 @@ public class AutoCraftingManager {
if (craft) {
changed = true;
processed = true;
iterator.updateInventory(getInventoryItems(guiContainer));
iterator.updateInventory(ItemStackAmount.of(guiContainer));
}
}
@@ -123,6 +123,11 @@ public class AutoCraftingManager {
AutoCraftingManager.math = math;
if (AutoCraftingManager.math != null) {
if (NEIClientUtils.getGuiContainer() instanceof GuiRecipe<?>gui && gui.firstGui != null) {
gui.mc.displayGuiScreen(gui.firstGui);
}
ItemPanels.bookmarkPanel.clearTooltips();
math.createMasterRoot();
task.restart();
@@ -133,18 +138,6 @@ public class AutoCraftingManager {
return AutoCraftingManager.math != null && !task.interrupted();
}
public static ItemStackAmount getInventoryItems(GuiContainer guiContainer) {
final ItemStackAmount inventory = new ItemStackAmount();
for (Slot slot : guiContainer.inventorySlots.inventorySlots) {
if (slot.getHasStack() && !(slot instanceof SlotCrafting) && slot.canTakeStack(guiContainer.mc.thePlayer)) {
inventory.add(slot.getStack());
}
}
return inventory;
}
private static ItemStack[] snapshotLayout(GuiContainer guiContainer) {
final List<Slot> slots = guiContainer.inventorySlots.inventorySlots;
final ItemStack[] layout = new ItemStack[slots.size()];
@@ -11,8 +11,6 @@ import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.FavoriteRecipes;
@@ -24,28 +22,18 @@ import codechicken.nei.LayoutManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.tree.GuiCraftingTree;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.util.NEIMouseUtils;
public class GuiFavoriteButton extends GuiRecipeButton {
private static final int BUTTON_ID_START = 14;
protected static final DrawableResource ICON_STATE_OFF = new DrawableBuilder(
"nei:textures/nei_sprites.png",
10,
76,
9,
10).build();
protected static final DrawableResource ICON_STATE_ON = new DrawableBuilder(
"nei:textures/nei_sprites.png",
19,
76,
9,
10).build();
protected static final DrawableResource ICON_STATE_OFF = UIRecipeTexture.ICON_FAVORITE_OFF;
protected static final DrawableResource ICON_STATE_ON = UIRecipeTexture.ICON_FAVORITE_ON;
protected final Recipe recipe;
protected boolean favorite = false;
@@ -94,17 +82,13 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
@Override
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
final DrawableResource icon = isFavorite() ? ICON_STATE_ON : ICON_STATE_OFF;
final int iconX = this.xPosition + (this.width - icon.width - 1) / 2;
final int iconY = this.yPosition + (this.height - icon.height) / 2;
protected DrawableResource getIcon() {
return isFavorite() ? ICON_STATE_ON : ICON_STATE_OFF;
}
GL11.glColor4f(1, 1, 1, this.enabled ? 1 : 0.5f);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
icon.draw(iconX, iconY);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
@Override
protected void drawContent(Minecraft minecraft, int mouseX, int mouseY, boolean mouseOver) {
super.drawContent(minecraft, mouseX, mouseY, mouseOver);
if (!mouseOver) {
this.selectedResult = null;
@@ -5,13 +5,10 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemsTooltipLineHandler;
@@ -23,20 +20,14 @@ import codechicken.nei.PositionedStack;
import codechicken.nei.api.IOverlayHandler;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkPayload;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.util.NEIMouseUtils;
public class GuiOverlayButton extends GuiRecipeButton {
protected static DrawableResource notPresent = new DrawableBuilder(
"nei:textures/nei_tabbed_sprites.png",
0,
40,
8,
8).build();
protected static DrawableResource present = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 8, 40, 8, 8)
.build();
protected static DrawableResource notPresent = UIRecipeTexture.ITEM_MISSING;
protected static DrawableResource present = UIRecipeTexture.ITEM_PRESENT;
public enum ItemOverlayFormat {
@@ -87,24 +78,9 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
}
protected static final DrawableResource ICON_FILL = new DrawableBuilder(
"nei:textures/nei_sprites.png",
28,
76,
9,
10).build();
protected static final DrawableResource ICON_FILL_ERROR = new DrawableBuilder(
"nei:textures/nei_sprites.png",
37,
76,
9,
10).build();
protected static final DrawableResource ICON_OVERLAY = new DrawableBuilder(
"nei:textures/nei_sprites.png",
46,
76,
9,
10).build();
protected static final DrawableResource ICON_FILL = UIRecipeTexture.ICON_OVERLAY_FILL;
protected static final DrawableResource ICON_FILL_ERROR = UIRecipeTexture.ICON_OVERLAY_FILL_ERROR;
protected static final DrawableResource ICON_OVERLAY = UIRecipeTexture.ICON_OVERLAY;
protected static final int BUTTON_ID_SHIFT = 4;
public final GuiContainer firstGui;
@@ -217,22 +193,12 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
@Override
protected void drawContent(Minecraft minecraft, int y, int x, boolean mouseOver) {
DrawableResource icon = ICON_OVERLAY;
protected DrawableResource getIcon() {
if (this.canFillCraftingGrid && (!requireShiftForOverlayRecipe() || NEIClientUtils.shiftKey())) {
icon = this.missedMaterialsTooltipLineHandler == null ? ICON_FILL : ICON_FILL_ERROR;
return this.missedMaterialsTooltipLineHandler == null ? ICON_FILL : ICON_FILL_ERROR;
}
final int iconX = this.xPosition + (this.width - icon.width - 1) / 2;
final int iconY = this.yPosition + (this.height - icon.height) / 2;
GL11.glColor4f(1, 1, 1, this.enabled ? 1 : 0.5f);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
icon.draw(iconX, iconY);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
return ICON_OVERLAY;
}
@Override
File diff suppressed because it is too large. Load diff
@@ -4,10 +4,14 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraftforge.client.event.GuiScreenEvent;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.GuiNEIButton;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.ButtonSkin;
import codechicken.nei.theme.UIWidgetTexture;
import cpw.mods.fml.common.eventhandler.Cancelable;
public abstract class GuiRecipeButton extends GuiNEIButton {
@@ -58,6 +62,26 @@ public abstract class GuiRecipeButton extends GuiNEIButton {
this.handlerRef = point;
}
protected DrawableResource getIcon() {
return null;
}
@Override
protected DrawableResource getBackground(int mouseX, int mouseY, boolean mouseOver) {
return UIWidgetTexture.BUTTON.background(this.enabled, false, mouseOver);
}
@Override
protected void drawContent(Minecraft minecraft, int mouseX, int mouseY, boolean mouseOver) {
final DrawableResource icon = getIcon();
if (icon != null) {
ButtonSkin.drawIcon(this.xPosition, this.yPosition, this.width, this.height, icon, this.enabled);
} else {
super.drawContent(minecraft, mouseX, mouseY, mouseOver);
}
}
public abstract List<String> handleTooltip(List<String> currenttip);
public abstract Map<String, String> handleHotkeys(int mousex, int mousey, Map<String, String> hotkeys);
@@ -1,6 +1,7 @@
package codechicken.nei.recipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.lwjgl.opengl.GL11;
@@ -12,11 +13,11 @@ 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;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.theme.UIWidgetTexture;
public class GuiRecipeCatalyst extends ScrollContainer {
@@ -49,43 +50,29 @@ public class GuiRecipeCatalyst extends ScrollContainer {
private static final int SLOT_SIZE = 16;
private static final int BORDER_PADDING = 6;
private static final int TRANSPARENCY_BORDER = 4;
private static final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/catalyst_tab.png",
0,
0,
28 + TRANSPARENCY_BORDER * 2,
28 + TRANSPARENCY_BORDER * 2)
.setTextureSize(28 + TRANSPARENCY_BORDER * 2, 28 + TRANSPARENCY_BORDER * 2)
.setSlices(
BORDER_PADDING + TRANSPARENCY_BORDER,
BORDER_PADDING + TRANSPARENCY_BORDER,
BORDER_PADDING + TRANSPARENCY_BORDER,
BORDER_PADDING + TRANSPARENCY_BORDER)
.build();
private static final int COLUMNS_BOTTOM_INSET = 5;
private static final DrawableResource FG_TEXTURE = new DrawableBuilder("nei:textures/slot.png", 0, 0, 18, 18)
.setTextureSize(18, 18).setSlices(1, 1, 1, 1).build();
private static final ScrollBar VERTICAL_SCROLLBAR = ScrollBar.defaultVerticalBar()
.setOverflowType(ScrollBar.OverflowType.AUTO).setTrackPadding(0, BORDER_PADDING, -13, BORDER_PADDING)
private static final ScrollBar VERTICAL_SCROLLBAR = UIWidgetTexture.verticalScrollBar()
.setOverflowType(ScrollBar.OverflowType.AUTO)
.setTrackPadding(0, BORDER_PADDING - 1, -13, BORDER_PADDING - 1)
.setScrollPlace(ScrollBar.ScrollPlace.START);
private PositionedStack[] items = new PositionedStack[0];
private List<PositionedStack> items = Collections.emptyList();
private boolean showWidget = false;
private int availableHeight = 0;
private int style = -1;
public GuiRecipeCatalyst() {
setPaddingBlock(BORDER_PADDING + 1, BORDER_PADDING + 1);
setPaddingBlock(BORDER_PADDING, BORDER_PADDING);
}
public void setCatalysts(List<PositionedStack> items) {
this.items = items.toArray(new PositionedStack[0]);
this.items = items;
createWidgets();
}
public void setAvailableHeight(int height) {
if (this.availableHeight != height) {
if (this.availableHeight != height || this.style != NEIClientConfig.getJEIStyleRecipeCatalysts()) {
this.availableHeight = height;
createWidgets();
}
@@ -95,21 +82,23 @@ public class GuiRecipeCatalyst extends ScrollContainer {
return this.availableHeight;
}
public boolean isShowWidget() {
return this.showWidget;
@Override
public boolean isVisible() {
return this.showWidget && NEIClientConfig.getJEIStyleRecipeCatalysts() != 0;
}
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;
final int maxItemsPerColumn = Math
.max(0, this.availableHeight - COLUMNS_BOTTOM_INSET - 2 - BORDER_PADDING * 2) / SLOT_SIZE;
return maxItemsPerColumn > 0 ? NEIServerUtils.divideCeil(this.items.size(), maxItemsPerColumn) : 0;
}
return 1;
}
public int getRowCount() {
final int columnCount = getColumnCount();
return columnCount > 0 ? NEIServerUtils.divideCeil(this.items.length, columnCount) : 0;
return columnCount > 0 ? NEIServerUtils.divideCeil(this.items.size(), columnCount) : 0;
}
protected void createWidgets() {
@@ -117,23 +106,25 @@ public class GuiRecipeCatalyst extends ScrollContainer {
final int rows = getRowCount();
setVerticalScroll(null);
setPaddingInline(BORDER_PADDING + 1, BORDER_PADDING - 3);
setPaddingInline(BORDER_PADDING, BORDER_PADDING - 3);
this.style = NEIClientConfig.getJEIStyleRecipeCatalysts();
this.h = rows * SLOT_SIZE + this.paddingBlockStart + this.paddingBlockEnd;
this.w = columns * SLOT_SIZE + this.paddingInlineStart + this.paddingInlineEnd;
if (NEIClientConfig.getJEIStyleRecipeCatalysts() == 2
if (this.style == 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);
setPaddingInline(this.paddingInlineStart + VERTICAL_SCROLLBAR.getTrackWidth(), this.paddingInlineEnd);
}
this.showWidget = rows * columns > 0;
if (rows == 0 || columns == 0) {
clear();
return;
}
@@ -157,12 +148,14 @@ public class GuiRecipeCatalyst extends ScrollContainer {
if (!this.showWidget) return;
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(
this.x - TRANSPARENCY_BORDER,
this.y - TRANSPARENCY_BORDER,
this.w + TRANSPARENCY_BORDER * 2,
this.h + TRANSPARENCY_BORDER * 2);
FG_TEXTURE.draw(
if (this.h < this.availableHeight) {
UIRecipeTexture.CATALYST_TAB_JOINED.draw(this.x, this.y, this.w, this.h);
} else {
UIRecipeTexture.CATALYST_TAB.draw(this.x, this.y, this.w, this.h);
}
UIRecipeTexture.CATALYST_SLOT.draw(
this.x + this.paddingInlineStart - 1,
this.y + this.paddingBlockStart - 1,
this.w - this.paddingInlineStart - this.paddingInlineEnd + 2,
@@ -10,7 +10,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.common.MinecraftForge;
@@ -26,11 +25,11 @@ import codechicken.nei.ColorUtils;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.Widget;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.event.NEIRegisterHandlerInfosEvent;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.debug.DebugHandlerWidget;
import codechicken.nei.theme.UIRecipeTexture;
import cpw.mods.fml.common.Loader;
public abstract class GuiRecipeTab extends Widget {
@@ -44,29 +43,14 @@ public abstract class GuiRecipeTab extends Widget {
protected final String handlerName;
protected final String handlerID;
public static final int TAB_WIDTH = 24;
public static final int TAB_HEIGHT = 24;
private static final DrawableResource selectedTabImage = new DrawableBuilder(
"nei:textures/nei_tabbed_sprites.png",
0,
16,
24,
24).build();
private static final DrawableResource unselectedTabImage = new DrawableBuilder(
"nei:textures/nei_tabbed_sprites.png",
24,
16,
24,
24).build();
private boolean selected;
public GuiRecipeTab(IRecipeHandler handler, int x, int y) {
super();
this.x = x;
this.y = y;
this.w = TAB_WIDTH;
this.h = TAB_HEIGHT;
this.w = UIRecipeTexture.TAB_UNSELECTED.getWidth();
this.h = UIRecipeTexture.TAB_UNSELECTED.getHeight();
this.handler = handler;
this.handlerName = handler.getHandlerId();
this.selected = false;
@@ -84,21 +68,20 @@ public abstract class GuiRecipeTab extends Widget {
drawForeground(mouseX, mouseY);
}
public void drawBackground(int mouseX, int mouseY) {
private void drawBackground(int mouseX, int mouseY) {
final DrawableResource image = this.selected ? UIRecipeTexture.TAB_SELECTED : UIRecipeTexture.TAB_UNSELECTED;
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glColor4f(1, 1, 1, 1);
final DrawableResource image = this.selected ? selectedTabImage : unselectedTabImage;
image.draw(this.x, this.y);
image.draw(this.x, this.y, this.w, this.h);
}
public void drawForeground(int mouseX, int mouseY) {
final int iconX = this.x + 4;
final int iconY = this.y + 4;
final FontRenderer fontRenderer = GuiDraw.fontRenderer;
private void drawForeground(int mouseX, int mouseY) {
final HandlerInfo handlerInfo = getHandlerInfo(this.handlerName, this.handlerID);
final DrawableResource icon = handlerInfo != null ? handlerInfo.getImage() : null;
final ItemStack itemStack = handlerInfo != null ? handlerInfo.getItemStack() : null;
final int iconX = this.x + (this.w - 16) / 2;
final int iconY = this.y + this.h - 16 - 6;
if (icon != null) {
icon.draw(iconX + 1, iconY + 1);
@@ -111,24 +94,17 @@ public abstract class GuiRecipeTab extends Widget {
if (!isEnabled) GL11.glDisable(GL12.GL_RESCALE_NORMAL);
} else {
// Text fallback
final int color = this.selected ? ColorUtils.buttonLabelHover.getColor()
: ColorUtils.buttonLabelNormal.getColor();
String text = this.handler.getRecipeName();
if (text != null && text.length() > 0) {
if (text.length() > 2) {
text = text.substring(0, 2);
}
} else {
if (text == null || text.length() == 0) {
text = "??";
} else if (text.length() > 2) {
text = text.substring(0, 2);
}
int textCenterX = this.x + (int) (this.w / 2f);
int textCenterY = this.y + (int) (this.h / 2f) - 3;
int color = this.selected ? ColorUtils.buttonLabelHover.getColor()
: ColorUtils.buttonLabelNormal.getColor();
fontRenderer.drawStringWithShadow(
text,
textCenterX - (int) (fontRenderer.getStringWidth(text) / 2f),
textCenterY,
color);
GuiDraw.drawStringC(text, iconX + 8, iconY + 4, color);
GL11.glColor4f(1, 1, 1, 1);
}
}
@@ -2,19 +2,23 @@ package codechicken.nei.recipe;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.BooleanSupplier;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.Button;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.theme.UIWidgetTexture;
public class GuiRecipeTabs {
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 List<? extends IRecipeHandler> currenthandlers = Collections.emptyList();
private int pageCount = 1;
private int pageNumber = 0;
@@ -22,56 +26,78 @@ public class GuiRecipeTabs {
private int numHandlers = 1;
private int recipetype;
private final Button prevTab = new Button("<") {
private static class TabArrowButton extends Button {
private final DrawableResource icon;
private final BooleanSupplier action;
private TabArrowButton(DrawableResource icon, BooleanSupplier action) {
this.icon = icon;
this.action = action;
this.w = 8;
this.h = 20;
}
@Override
public boolean onButtonPress(boolean rightClick) {
if (!rightClick) {
NEIClientUtils.playClickSound();
return previousPage();
} else return false;
return !rightClick && this.action.getAsBoolean();
}
};
private final Button nextTab = new Button(">") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
NEIClientUtils.playClickSound();
return nextPage();
} else return false;
public void draw(int mouseX, int mouseY) {
UIWidgetTexture.BUTTON
.draw(this.x, this.y, this.w, this.h, this.icon, true, false, contains(mouseX, mouseY));
}
}
};
private final Button prevTab = new TabArrowButton(UIRecipeTexture.ICON_PREV, this::previousPage);
private final Button nextTab = new TabArrowButton(UIRecipeTexture.ICON_NEXT, this::nextPage);
public static int getTabWidth() {
return GuiRecipeTab.TAB_WIDTH;
return UIRecipeTexture.TAB_UNSELECTED.getWidth() - 1;
}
public static int getTabHeight() {
return GuiRecipeTab.TAB_HEIGHT;
return UIRecipeTexture.TAB_UNSELECTED.getHeight();
}
public void update(GuiRecipe<?> guiRecipe) {
public void place(int navLeft, int navWidth, int guiTop) {
final int tabWidth = getTabWidth();
final int tabHeight = getTabHeight();
final int perPage = (navWidth - 4) / tabWidth;
this.recipetype = guiRecipe.recipetype;
this.currenthandlers = guiRecipe.currenthandlers;
this.area.width = perPage * tabWidth;
this.area.height = tabHeight;
this.area.x = navLeft + (navWidth - this.area.width) / 2;
this.area.y = guiTop - tabHeight + 4;
this.prevTab.y = this.nextTab.y = guiTop - this.prevTab.h + 1;
this.prevTab.x = this.area.x - this.prevTab.w + 1;
this.nextTab.x = this.area.x + this.area.width - 1;
if (this.categoriesPerPage != perPage) {
this.categoriesPerPage = perPage;
rebuild();
} else {
refreshPage();
}
}
public void update(List<? extends IRecipeHandler> handlers, int recipetype) {
this.currenthandlers = handlers;
this.recipetype = recipetype;
rebuild();
}
private void rebuild() {
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);
refreshArrows();
}
public void refreshPage() {
@@ -97,17 +123,10 @@ public class GuiRecipeTabs {
}
}
private void updateArrows(int tabHeight) {
private void refreshArrows() {
this.buttons.clear();
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;
this.prevTab.x = this.area.x - this.prevTab.w + 1;
this.nextTab.x = this.area.x + this.area.width - 1;
this.buttons.add(this.prevTab);
this.buttons.add(this.nextTab);
}
@@ -144,14 +163,17 @@ public class GuiRecipeTabs {
public void handleTooltip(int mousex, int mousey, List<String> tooltips) {
if (!NEIClientConfig.areJEIStyleTabsVisible()) return;
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(mousex, mousey)) {
tab.addTooltips(tooltips);
}
}
for (Button button : this.buttons) {
if (button.contains(mousex, mousey)) {
button.addTooltips(tooltips);
return;
}
}
for (GuiRecipeTab tab : this.tabs) {
if (tab.contains(mousex, mousey)) {
tab.addTooltips(tooltips);
return;
}
}
}
@@ -161,7 +183,7 @@ public class GuiRecipeTabs {
for (Button button : this.buttons) {
if (button.contains(x, y)) {
return button.onButtonPress(mouseButton == 1);
return button.handleClick(x, y, mouseButton);
}
}
@@ -36,6 +36,9 @@ public class HandlerInfo {
private boolean allowOverflowX = true;
private boolean allowOverflowY = false;
private int windowWidth = 0;
private boolean recipeSpacing = false;
private ItemStack itemStack = null;
private DrawableResource image = null;
@@ -189,6 +192,22 @@ public class HandlerInfo {
this.allowOverflowY = allowOverflowY;
}
public int getWindowWidth() {
return this.windowWidth;
}
public void setWindowWidth(int windowWidth) {
this.windowWidth = windowWidth;
}
public boolean isRecipeSpacing() {
return this.recipeSpacing;
}
public void setRecipeSpacing(boolean recipeSpacing) {
this.recipeSpacing = recipeSpacing;
}
public static class Builder {
private final HandlerInfo info;
@@ -296,6 +315,16 @@ public class HandlerInfo {
return this;
}
public Builder setWindowWidth(int windowWidth) {
this.info.windowWidth = windowWidth;
return this;
}
public Builder setRecipeSpacing(boolean recipeSpacing) {
this.info.recipeSpacing = recipeSpacing;
return this;
}
public HandlerInfo build() {
return this.info;
}
@@ -45,6 +45,10 @@ public interface IRecipeHandler {
return getRecipeName();
}
default int getRecipeWidth(int recipe) {
return 0;
}
default int getRecipeHeight(int recipe) {
return 0;
}
@@ -121,6 +125,26 @@ public interface IRecipeHandler {
return getResultStack(recipe) != null ? getOtherStacks(recipe) : Collections.emptyList();
}
/**
* Override it to let the recipe search see stacks that the recipe doesn't draw and doesn't give to the overlay.
*
* @return The stacks of the role the recipe search looks at; called from the search threads.
*/
default List<PositionedStack> getSearchStacks(int recipe, RecipeRole role) {
return switch (role) {
case INPUT -> getIngredientStacks(recipe);
case OUTPUT -> getResultStacks(recipe);
case AUXILIARY -> getAuxiliaryStacks(recipe);
};
}
/**
* @return The text the recipe text search looks at, none by default; called from the search threads.
*/
default List<String> getSearchText(int recipe) {
return Collections.emptyList();
}
/**
* @param recipe The recipe index to get the group id for.
* @return An id shared by every recipe in this recipe's group, or {@code null} if this recipe isn't grouped.
@@ -0,0 +1,170 @@
package codechicken.nei.recipe;
import java.util.List;
import java.util.function.BooleanSupplier;
import net.minecraft.client.gui.FontRenderer;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.Button;
import codechicken.nei.ColorUtils;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.Widget;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.theme.UIWidgetTexture;
class NavigationBar extends Widget {
protected class NavButton extends Button {
private final DrawableResource icon;
private final Runnable action;
private final BooleanSupplier isEnabled;
protected NavButton(DrawableResource icon, BooleanSupplier isEnabled, Runnable action) {
this.icon = icon;
this.action = action;
this.isEnabled = isEnabled;
this.w = BUTTON_SIZE;
this.h = BUTTON_SIZE;
}
@Override
public void draw(int mx, int my) {
final boolean enabled = this.isEnabled.getAsBoolean();
final boolean active = (this.state & 0x3) == 2;
UIWidgetTexture.BUTTON.draw(this.x, this.y, this.w, this.h, this.icon, enabled, active, contains(mx, my));
}
@Override
public boolean onButtonPress(boolean rightclick) {
if (rightclick) return false;
this.action.run();
return true;
}
}
protected static final int BUTTON_SIZE = 12;
protected static final int GAP = 2;
private final NavButton prev;
private final NavButton next;
protected boolean enabled = true;
protected String label = "";
protected int color = 0xffffff;
protected int hoverColor = 0xffffff;
protected int insetLeft;
protected Runnable labelAction;
public String labelTooltip;
private String croppedLabel;
private int croppedLabelWidth;
private String croppedLabelSource;
private int croppedLabelMaxWidth;
public NavigationBar(Runnable labelAction, Runnable onPrev, Runnable onNext) {
this.prev = new NavButton(UIRecipeTexture.ICON_PREV, () -> NavigationBar.this.enabled, onPrev);
this.next = new NavButton(UIRecipeTexture.ICON_NEXT, () -> NavigationBar.this.enabled, onNext);
this.labelAction = labelAction;
this.h = BUTTON_SIZE;
}
protected int plateX() {
return this.x + BUTTON_SIZE + GAP;
}
protected int plateWidth() {
return this.w - (BUTTON_SIZE + GAP) * 2;
}
public void place(int x, int y, int w) {
this.x = x;
this.y = y;
this.w = w;
this.prev.x = x;
this.prev.y = y;
this.next.x = x + w - BUTTON_SIZE;
this.next.y = y;
}
@Override
public void draw(int mx, int my) {
GuiDraw.drawRect(
plateX() + this.insetLeft,
this.y,
plateWidth() - this.insetLeft,
this.h,
ColorUtils.recipeTitleBG.getColor());
this.prev.draw(mx, my);
this.next.draw(mx, my);
if (!this.label.isEmpty()) {
final FontRenderer font = NEIClientUtils.mc().fontRenderer;
updateCroppedLabel(font);
font.drawStringWithShadow(
this.croppedLabel,
labelX(),
labelY(font),
isLabelHovered(mx, my) ? this.hoverColor : this.color);
}
}
private void updateCroppedLabel(FontRenderer font) {
final int maxWidth = plateWidth() - this.insetLeft;
if (!this.label.equals(this.croppedLabelSource) || maxWidth != this.croppedLabelMaxWidth) {
this.croppedLabel = NEIClientUtils.cropText(font, this.label, maxWidth - 2);
this.croppedLabelSource = this.label;
this.croppedLabelMaxWidth = maxWidth;
this.croppedLabelWidth = font.getStringWidth(this.croppedLabel);
}
}
private int labelX() {
return plateX() + this.insetLeft + (plateWidth() - this.insetLeft) / 2 - this.croppedLabelWidth / 2;
}
private int labelY(FontRenderer font) {
return this.y + (this.h - font.FONT_HEIGHT) / 2 + 1;
}
private boolean isLabelHovered(int mx, int my) {
if (this.labelAction == null || this.label.isEmpty()) return false;
final FontRenderer font = NEIClientUtils.mc().fontRenderer;
updateCroppedLabel(font);
final int textX = labelX();
final int textY = labelY(font);
return mx >= textX && mx < textX + this.croppedLabelWidth && my >= textY && my < textY + font.FONT_HEIGHT;
}
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (tooltip.isEmpty() && this.labelTooltip != null && isLabelHovered(mx, my)) {
tooltip.add(this.labelTooltip);
}
return tooltip;
}
@Override
public boolean handleClick(int mx, int my, int button) {
if (button == 0 && isLabelHovered(mx, my)) {
this.labelAction.run();
return true;
}
if (!this.enabled) return false;
if (this.prev.contains(mx, my)) return this.prev.handleClick(mx, my, button);
if (this.next.contains(mx, my)) return this.next.handleClick(mx, my, button);
return false;
}
}
@@ -36,6 +36,11 @@ public class RecipeCatalysts {
public static final Map<String, List<ItemStack>> catalystsRemoverFromIMC = new HashMap<>();
private static final Map<String, List<PositionedStack>> recipeCatalystMap = new HashMap<>();
private static final List<String> forceClassNameList = new ArrayList<>();
private static int version = 0;
public static int getVersion() {
return version;
}
public static void addRecipeCatalyst(String handlerID, CatalystInfo catalystInfo) {
if (handlerID == null || handlerID.isEmpty() || catalystInfo.getStack() == null) return;
@@ -69,6 +74,7 @@ public class RecipeCatalysts {
if (handlerID == null || handlerID.isEmpty()) return;
catalystsAdderFromAPI.put(handlerID, catalystInfoList);
recipeCatalystMap.put(handlerID, convertToPositionedStackList(catalystInfoList));
version++;
}
public static List<PositionedStack> getRecipeCatalysts(IRecipeHandler handler) {
@@ -176,6 +182,7 @@ public class RecipeCatalysts {
recipeCatalystMap.put(entry.getKey(), convertToPositionedStackList(entry.getValue()));
}
version++;
}
private static void resolveAdderQueue(Map<String, CatalystInfoList> recipeCatalystMap) {
@@ -149,6 +149,7 @@ public class RecipeHandlerRef {
if (overlayHandler != null && overlayHandler.canCraft(firstGui, this.handler, this.recipeIndex)) {
if (!firstGui.equals(firstGui.mc.currentScreen)) {
if (!firstGui.mc.func_152345_ab()) return false;
firstGui.mc.displayGuiScreen(firstGui);
}
@@ -19,12 +19,21 @@ import codechicken.nei.recipe.Recipe.RecipeId;
public class RecipeItemInputHandler implements IContainerInputHandler, IContainerTooltipHandler {
public static final RecipeItemInputHandler instance = new RecipeItemInputHandler();
protected RecipeTooltipLineHandler recipeTooltipLineHandler = null;
protected RecipeItemInputHandler() {
}
public static void load() {
RecipeItemInputHandler recipeHandler = new RecipeItemInputHandler();
GuiContainerManager.addInputHandler(recipeHandler);
GuiContainerManager.addTooltipHandler(recipeHandler);
GuiContainerManager.addInputHandler(instance);
GuiContainerManager.addTooltipHandler(instance);
}
public void clearTooltipCache() {
this.recipeTooltipLineHandler = null;
}
@Override
@@ -64,16 +73,17 @@ public class RecipeItemInputHandler implements IContainerInputHandler, IContaine
: null;
if (recipeId == null) {
recipeTooltipLineHandler = null;
} else if (recipeTooltipLineHandler == null || !recipeTooltipLineHandler.getRecipeId().equals(recipeId)) {
recipeTooltipLineHandler = new RecipeTooltipLineHandler(recipeId);
}
clearTooltipCache();
} else if (this.recipeTooltipLineHandler == null
|| !this.recipeTooltipLineHandler.getRecipeId().equals(recipeId)) {
this.recipeTooltipLineHandler = new RecipeTooltipLineHandler(recipeId);
}
if (recipeTooltipLineHandler != null) {
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(recipeTooltipLineHandler));
if (this.recipeTooltipLineHandler != null) {
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.recipeTooltipLineHandler));
}
} else {
recipeTooltipLineHandler = null;
clearTooltipCache();
}
return currenttip;
@@ -271,7 +271,7 @@ public class RecipeItemsTooltipLineHandler extends CompositeTooltipLineHandler {
}
if (screen instanceof GuiContainer container) {
return AutoCraftingManager.getInventoryItems(container);
return ItemStackAmount.of(container);
}
return new ItemStackAmount();
@@ -125,7 +125,7 @@ public class RecipeJsonWriter {
}
private static List<Integer> filteredRecipes(IRecipeHandler handler) {
return new SearchRecipeHandler<>(handler).getFilteredRecipes();
return new SearchRecipeHandler<>(handler, GuiRecipe.getRecipeListFilter()).getFilteredRecipes();
}
private void writeFile(File file, List<? extends IRecipeHandler> handlers,
@@ -11,60 +11,100 @@ import net.minecraft.item.ItemStack;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.Widget;
import codechicken.nei.recipe.widget.RecipeWidget;
import codechicken.nei.recipe.widget.ViewStates;
import codechicken.nei.scroll.ScrollContainer;
public class RecipePageManager {
private static final int RECIPE_GAP = 4;
private static final class Page {
private final List<Widget> widgets;
private final int width;
private final boolean overflowY;
private int top;
private int gap;
private Page(List<Widget> widgets, int width, boolean overflowY, int gap) {
this.widgets = widgets;
this.width = width;
this.overflowY = overflowY;
this.gap = gap;
}
}
private SearchRecipeHandler<?> handler;
private ScrollContainer container;
private HandlerInfo handlerInfo;
private String cacheKey = "";
private int numRecipes = -1;
private int searchVersion = -1;
private int visibleHeight = -1;
private int currentPageIndex = -1;
private List<List<Widget>> pageWidgets = new ArrayList<>();
private final List<RecipeWidget> recipeWidgets = new ArrayList<>();
private final List<Page> pages = new ArrayList<>();
private final ViewStates viewStates;
private int maxRecipeWidth;
private boolean overflowY;
private final int recipeGap;
public RecipePageManager(SearchRecipeHandler<?> handler, HandlerInfo handlerInfo, ScrollContainer container) {
public RecipePageManager(SearchRecipeHandler<?> handler, HandlerInfo handlerInfo, ScrollContainer container,
ViewStates viewStates) {
this.handler = handler;
this.handlerInfo = handlerInfo;
this.container = container;
this.viewStates = viewStates;
this.recipeGap = handlerInfo.isRecipeSpacing() ? RECIPE_GAP : 0;
rebuildPages();
rebuildWidgets();
}
public boolean rebuildPages() {
final String cacheKey = handlerInfo.getHandlerName() + ":"
+ getNumRecipes()
+ ":"
+ this.container.getVisibleHeight()
+ ":"
+ GuiRecipe.searchField.text();
final boolean widgetsChanged = this.numRecipes != getNumRecipes()
|| this.searchVersion != this.handler.getSearchVersion();
final int visibleHeight = this.container.getVisibleHeight();
if (cacheKey.equals(this.cacheKey)) {
if (!widgetsChanged && visibleHeight == this.visibleHeight) {
return false;
}
this.cacheKey = cacheKey;
this.visibleHeight = visibleHeight;
final List<RecipeWidget> pausedWidgets = getPausedWidgets();
this.pageWidgets.clear();
if (widgetsChanged) {
rebuildWidgets();
}
final boolean allowOverflowY = this.handlerInfo.isAllowOverflowY();
final int handlerHeight = this.handlerInfo.getHeight() + this.handlerInfo.getYShift();
final boolean multipleWidgetsAllowed = !allowOverflowY && handlerInfo.isMultipleWidgetsAllowed();
final boolean infiniteScroll = !allowOverflowY
&& NEIClientConfig.getBooleanSetting("inventory.guirecipe.infiniteScroll");
this.pages.clear();
this.overflowY = false;
final int heightAvailable = this.container.getVisibleHeight();
final int width = Math.max(166, this.handlerInfo.getWidth());
buildPages();
buildSpreadGaps();
changePage(0);
return true;
}
private void rebuildWidgets() {
this.numRecipes = getNumRecipes();
this.searchVersion = this.handler.getSearchVersion();
this.recipeWidgets.clear();
for (List<Integer> group : groupRecipes()) {
this.recipeWidgets.add(
new RecipeWidget(this.handler.original, group, this.viewStates.get(this.handler.original, group)));
}
this.maxRecipeWidth = this.recipeWidgets.stream().mapToInt(widget -> widget.w).max()
.orElse(this.handlerInfo.getWidth());
}
private List<List<Integer>> groupRecipes() {
final List<Integer> searchRecipes = this.handler.getFilteredRecipes();
final int numRecipes = searchRecipes.size();
final List<List<Integer>> groupedRecipes = new ArrayList<>();
final Map<Object, Integer> groupEndIndices = new HashMap<>();
List<Widget> widgets = new ArrayList<>();
int shiftY = 0;
for (int i = 0; i < numRecipes; i++) {
final int recipeIndex = searchRecipes.get(i);
for (int recipeIndex : searchRecipes) {
final Object groupId = this.handler.original.getRecipeGroupId(recipeIndex);
final int groupIndex = groupId != null
? groupEndIndices.computeIfAbsent(groupId, k -> groupedRecipes.size())
@@ -77,42 +117,121 @@ public class RecipePageManager {
groupedRecipes.get(groupIndex).add(recipeIndex);
}
for (int groupIndex = 0; groupIndex < groupedRecipes.size(); groupIndex++) {
final RecipeWidget widget = new RecipeWidget(this.handler.original, groupedRecipes.get(groupIndex));
return groupedRecipes;
}
// keep the pause of the rebuilt widgets
for (RecipeWidget paused : pausedWidgets) {
final int pausedIndex = paused.getRecipeHandlerRef().recipeIndex;
private void buildPages() {
final boolean multipleWidgetsAllowed = isMultipleWidgetsAllowed();
final boolean infiniteScroll = isInfiniteScroll();
final int heightAvailable = this.container.getVisibleHeight();
List<Widget> widgets = new ArrayList<>();
int shiftY = 0;
if (widget.containsRecipeIndex(pausedIndex)) {
widget.pinRecipe(pausedIndex, paused.getPinnedIngredients());
}
for (RecipeWidget widget : this.recipeWidgets) {
if (this.handlerInfo.isAllowOverflowY()) {
widget.setHeight(Math.min(widget.getContentHeight(), heightAvailable));
}
widget.w = width;
if (allowOverflowY) {
widget.h = Math.min(handlerHeight, heightAvailable);
}
if (!widgets.isEmpty()
&& (!multipleWidgetsAllowed || !infiniteScroll && shiftY + widget.h > heightAvailable)) {
this.pageWidgets.add(widgets);
if (!widgets.isEmpty() && (!multipleWidgetsAllowed
|| !infiniteScroll && shiftY + this.recipeGap + widget.h > heightAvailable)) {
addPage(widgets);
widgets = new ArrayList<>();
shiftY = 0;
}
if (!widgets.isEmpty()) {
shiftY += this.recipeGap;
}
widgets.add(widget);
shiftY += widget.h;
}
if (!widgets.isEmpty()) {
this.pageWidgets.add(widgets);
addPage(widgets);
}
}
private void addPage(List<Widget> widgets) {
final int pageWidth = widgets.stream().mapToInt(widget -> widget.w).max().orElse(0);
final int pageHeight = widgets.stream().mapToInt(widget -> widget.h).sum()
+ this.recipeGap * (widgets.size() - 1);
final boolean pageOverflowsY = pageHeight > this.container.getVisibleHeight();
this.overflowY |= pageOverflowsY;
this.pages.add(new Page(widgets, pageWidth, pageOverflowsY, this.recipeGap));
}
public boolean needsVerticalScroll() {
return this.overflowY;
}
private Page getCurrentPage() {
return this.currentPageIndex >= 0 && this.currentPageIndex < this.pages.size()
? this.pages.get(this.currentPageIndex)
: null;
}
public boolean currentPageNeedsVerticalScroll() {
final Page page = getCurrentPage();
return page != null && page.overflowY;
}
private void buildSpreadGaps() {
if (!isMultipleWidgetsAllowed() || isInfiniteScroll()
|| !NEIClientConfig.getBooleanSetting("inventory.guirecipe.evenRecipeSpacing")) {
return;
}
changePage(0);
final int heightAvailable = this.container.getVisibleHeight();
int maxHeight = 0;
return true;
for (Page page : this.pages) {
for (Widget widget : page.widgets) {
maxHeight = Math.max(maxHeight, widget.h);
}
}
final int slots = maxHeight > 0 ? (heightAvailable + this.recipeGap) / (maxHeight + this.recipeGap) : 0;
// a page that fits a single recipe has nothing to spread
if (slots <= 1) {
return;
}
for (int index = 0; index < this.pages.size(); index++) {
final Page page = this.pages.get(index);
int totalHeight = 0;
for (Widget widget : page.widgets) {
totalHeight += widget.h;
}
int spreadGap = (heightAvailable - totalHeight) / (page.widgets.size() + 1);
if (index == this.pages.size() - 1) {
final int fullPageGap;
if (index > 0) {
fullPageGap = this.pages.get(index - 1).top;
} else {
fullPageGap = (heightAvailable - slots * maxHeight) / (slots + 1);
}
spreadGap = Math.min(spreadGap, fullPageGap);
}
if (spreadGap >= this.recipeGap) {
page.top = spreadGap;
page.gap = spreadGap;
}
}
}
private boolean isInfiniteScroll() {
return !this.handlerInfo.isAllowOverflowY()
&& NEIClientConfig.getBooleanSetting("inventory.guirecipe.infiniteScroll");
}
public boolean isMultipleWidgetsAllowed() {
@@ -128,7 +247,16 @@ public class RecipePageManager {
}
public int getNumPages() {
return this.pageWidgets.size();
return this.pages.size();
}
public int getMaxRecipeWidth() {
return this.maxRecipeWidth;
}
public int getCurrentPageWidth() {
final Page page = getCurrentPage();
return page != null ? page.width : 0;
}
public void changePage(int delta) {
@@ -145,8 +273,8 @@ public class RecipePageManager {
public boolean gotoRecipeIndex(int recipeIndex) {
for (int page = 0; page < this.pageWidgets.size(); page++) {
for (Widget widget : this.pageWidgets.get(page)) {
for (int page = 0; page < this.pages.size(); page++) {
for (Widget widget : this.pages.get(page).widgets) {
if (widget instanceof RecipeWidget recipeWidget && recipeWidget.containsRecipeIndex(recipeIndex)) {
changePage(page - this.currentPageIndex);
return true;
@@ -157,24 +285,10 @@ public class RecipePageManager {
return false;
}
private List<RecipeWidget> getPausedWidgets() {
final List<RecipeWidget> paused = new ArrayList<>();
for (List<Widget> widgets : this.pageWidgets) {
for (Widget widget : widgets) {
if (widget instanceof RecipeWidget recipeWidget && recipeWidget.isPaused()) {
paused.add(recipeWidget);
}
}
}
return paused;
}
public boolean pinRecipe(int recipeIndex, List<ItemStack> ingredients) {
for (List<Widget> widgets : this.pageWidgets) {
for (Widget widget : widgets) {
for (Page page : this.pages) {
for (Widget widget : page.widgets) {
if (widget instanceof RecipeWidget recipeWidget && recipeWidget.containsRecipeIndex(recipeIndex)) {
return recipeWidget.pinRecipe(recipeIndex, ingredients);
}
@@ -185,32 +299,35 @@ public class RecipePageManager {
}
public List<Widget> getCurrentPageWidgets() {
if (this.pageWidgets.isEmpty()) {
if (this.pages.isEmpty()) {
return Collections.emptyList();
}
List<Widget> currentWidgets = this.pageWidgets.get(this.currentPageIndex);
int shiftY = 0;
final Page page = this.pages.get(this.currentPageIndex);
final int placeWidth = Math.max(this.container.w, page.width);
int shiftY = page.top;
for (Widget widget : currentWidgets) {
for (Widget widget : page.widgets) {
if (widget instanceof RecipeWidget recipeWidget) {
recipeWidget.setLocation(2, shiftY);
final int offsetX = (placeWidth - widget.w) / 2;
recipeWidget.setLocation(offsetX, shiftY, placeWidth - widget.w - offsetX);
}
shiftY += widget.h;
shiftY += widget.h + page.gap;
}
return currentWidgets;
return page.widgets;
}
public List<Integer> getRecipeIndices() {
if (this.pageWidgets.isEmpty()) {
if (this.pages.isEmpty()) {
return Collections.emptyList();
}
final List<Integer> recipeIndices = new ArrayList<>();
for (Widget widget : this.pageWidgets.get(this.currentPageIndex)) {
for (Widget widget : this.pages.get(this.currentPageIndex).widgets) {
if (widget instanceof RecipeWidget recipeWidget) {
recipeIndices.add(recipeWidget.getRecipeHandlerRef().recipeIndex);
}
@@ -0,0 +1,7 @@
package codechicken.nei.recipe;
public enum RecipeRole {
INPUT,
OUTPUT,
AUXILIARY
}
@@ -0,0 +1,327 @@
package codechicken.nei.recipe;
import java.util.List;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.RecipeSearchField;
import codechicken.nei.RestartableTask;
import codechicken.nei.SearchField;
import codechicken.nei.SearchTokenParser.ISearchParserProvider;
import codechicken.nei.SearchTokenParser.SearchMode;
import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.search.SearchExpressionUtils;
import codechicken.nei.theme.UIRecipeTexture;
class RecipeSearchBar extends NavigationBar {
private static final int FIELD_MARGIN = 40;
private final RestartableTask updateFilter = new RestartableTask("NEI Recipe Filtering") {
@Override
public void execute() {
if (!(NEIClientUtils.mc().currentScreen instanceof GuiRecipe<?>guiRecipe)) return;
final SearchRecipeHandler<?> searchHandler = guiRecipe.getSearchHandler();
if (searchHandler == null) return;
final IRecipeFilter filter = getRecipeFilter();
final List<Integer> found = filter != null ? searchHandler.getSearchResult(filter) : null;
if (interrupted() || filter != null && found == null) return;
searchHandler.setSearchIndices(found);
}
};
private final RecipeSearchField field = new RecipeSearchField("") {
@Override
protected boolean noResults() {
final GuiScreen currentScreen = NEIClientUtils.mc().currentScreen;
return !(currentScreen instanceof GuiRecipe<?>guiRecipe) || guiRecipe.getNumRecipes() > 0;
}
@Override
public void onTextChange(String oldText) {
if (!text().equals(oldText)) {
RecipeSearchBar.this.updateFilter.restart();
}
}
};
private final NavButton toggle = new NavButton(UIRecipeTexture.ICON_SEARCH, () -> true, this::toggleField) {
@Override
public void addTooltips(List<String> tooltip) {
tooltip.add(NEIClientUtils.translate("recipe.search.tooltip.name") + GuiDraw.TOOLTIP_LINESPACE);
if (NEIClientUtils.shiftKey()) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.input",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "<"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.output",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + ">"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.text",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "~"));
final int patternMode = NEIClientConfig.getIntSetting("inventory.search.patternMode");
if (patternMode != 2) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.auxiliary",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "^"));
}
if (patternMode == 3) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.all",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "<&"));
}
for (ISearchParserProvider provider : SearchField.searchParser.getProviders()) {
if (provider.getSearchMode() == SearchMode.PREFIX) {
addPrefixTooltip(tooltip, provider);
}
}
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exclude",
SearchExpressionUtils.HIGHLIGHTS.NEGATE + "-"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exclude_recipe",
SearchExpressionUtils.HIGHLIGHTS.NEGATE + "!"));
tooltip.add(
NEIClientUtils
.translate("recipe.search.tooltip.or", SearchExpressionUtils.HIGHLIGHTS.OR.f + "|"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exact",
SearchExpressionUtils.HIGHLIGHTS.QUOTED + "\"",
SearchExpressionUtils.HIGHLIGHTS.QUOTED + "\""));
if (patternMode == 1 || patternMode == 3) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.regex",
SearchExpressionUtils.HIGHLIGHTS.REGEX + "r/",
SearchExpressionUtils.HIGHLIGHTS.REGEX + "/"));
}
} else {
tooltip.add(NEIClientUtils.translate("recipe.search.tooltip.shift"));
}
}
private void addPrefixTooltip(List<String> tooltip, ISearchParserProvider provider) {
final char prefix = SearchField.searchParser.getRedefinedPrefix(provider.getPrefix());
final String modeName = NEIClientUtils.translate("recipe.search.tooltip.prefix." + provider.getName());
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.prefix",
provider.getHighlightedColor() + String.valueOf(prefix),
modeName));
}
};
private boolean available = false;
private String pageInfo = "";
private String pageCounter = "";
private boolean pageInfoCropped;
private String pageLabel = "";
public RecipeSearchBar(Runnable onPrev, Runnable onNext) {
super(null, onPrev, onNext);
}
public void setPages(int current, int total) {
this.pageInfo = current + "/" + total;
this.pageLabel = NEIClientUtils.translate("recipe.page", current, total);
updateCounter();
updateLabel();
}
private void updateCounter() {
this.pageCounter = NEIClientUtils.cropText(GuiDraw.fontRenderer, this.pageInfo, FIELD_MARGIN - GAP);
this.pageInfoCropped = !this.pageCounter.equals(this.pageInfo);
}
private void updateLabel() {
this.label = this.field.isVisible() ? "" : this.pageLabel;
}
private void toggleField() {
if (this.field.isVisible()) {
this.field.setText("");
this.field.setFocus(false);
this.field.setVisible(false);
this.toggle.state = 0;
} else {
this.field.setVisible(true);
this.field.setFocus(true);
this.toggle.state = 2;
}
updateLabel();
}
public void setAvailable(boolean available) {
this.available = available;
this.insetLeft = available ? this.toggle.w + GAP : 0;
}
public void place(int x, int y, int w) {
super.place(x, y, w);
this.toggle.x = plateX();
this.toggle.y = y;
this.field.x = this.toggle.x + this.toggle.w + 1;
this.field.y = y - 1;
this.field.w = plateWidth() - this.toggle.w - FIELD_MARGIN;
this.field.h = 14;
updateCounter();
}
public ItemFilter getFilter() {
return this.field.getFilter();
}
public IRecipeFilter getRecipeFilter() {
return this.field.text().isEmpty() ? null : this.field.getRecipeFilter();
}
public RecipeSearchField getSearchField() {
return this.field;
}
public void updateFilter() {
this.updateFilter.restart();
}
public void reset() {
this.field.setText("");
this.field.setVisible(false);
this.toggle.state = 0;
updateLabel();
updateFilter();
}
public boolean overSearch(int px, int py) {
return this.available && this.toggle.contains(px, py) || this.field.isVisible() && this.field.contains(px, py);
}
@Override
public boolean contains(int px, int py) {
return super.contains(px, py) || overSearch(px, py);
}
@Override
public void draw(int mx, int my) {
super.draw(mx, my);
if (this.available) {
this.toggle.draw(mx, my);
}
if (this.field.isVisible()) {
this.field.draw(mx, my);
final FontRenderer font = GuiDraw.fontRenderer;
final int textY = this.y + (this.h - font.FONT_HEIGHT) / 2 + 1;
GuiDraw.drawStringC(this.pageCounter, this.field.x + this.field.w + FIELD_MARGIN / 2, textY, 0xffffff);
}
}
@Override
public boolean handleClick(int mx, int my, int button) {
if (this.available) {
if (this.toggle.contains(mx, my)) {
return this.toggle.handleClick(mx, my, button);
} else if (this.field.isVisible() && this.field.contains(mx, my)) {
return this.field.handleClick(mx, my, button);
}
this.field.onGuiClick(mx, my);
}
return super.handleClick(mx, my, button);
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
return isFocused() && this.field.handleKeyPress(keyID, keyChar);
}
@Override
public boolean isFocused() {
return this.field.isVisible() && this.field.focused();
}
@Override
public void loseFocus() {
this.field.setFocus(false);
}
@Override
public void lastKeyTyped(int keyID, char keyChar) {
if (isFocused()) {
this.field.lastKeyTyped(keyID, keyChar);
}
}
@Override
public boolean onHotkeyPressed() {
return this.field.isVisible() && this.field.onHotkeyPressed();
}
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (this.available) {
tooltip = this.toggle.handleTooltip(mx, my, tooltip);
}
if (tooltip.isEmpty() && this.field.isVisible()
&& mx >= this.field.x + this.field.w
&& mx < plateX() + plateWidth()
&& my >= this.y
&& my < this.y + this.h
&& this.pageInfoCropped) {
tooltip.add(this.pageInfo);
}
return tooltip;
}
public boolean handleDragNDrop(int mx, int my, ItemStack draggedStack) {
if (this.field.isVisible() && this.field.contains(mx, my)) {
this.field.setText(SearchField.getEscapedSearchText(draggedStack));
return true;
}
return false;
}
}
@@ -8,34 +8,20 @@ import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.gui.GuiDraw.ITooltipLineHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.ColorUtils;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.widget.RecipeWidget;
import codechicken.nei.scroll.GuiHelper;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.util.ReadableNumberConverter;
public class RecipeTooltipLineHandler implements ITooltipLineHandler {
private static final int BG_PADDING = 5;
private static final int TRANSPARENCY_BORDER = 4;
private final DrawableResource BG_TEXTURE = new DrawableBuilder(
"nei:textures/gui/recipebg.png",
0,
0,
176 + TRANSPARENCY_BORDER * 2,
166 + TRANSPARENCY_BORDER * 2)
.setSlices(
BG_PADDING + TRANSPARENCY_BORDER,
BG_PADDING + TRANSPARENCY_BORDER,
BG_PADDING + TRANSPARENCY_BORDER,
BG_PADDING + TRANSPARENCY_BORDER)
.build();
protected long lastUpdate = System.currentTimeMillis();
protected String recipeName = "";
protected GuiRecipe<?> gui = null;
protected RecipeHandlerRef handlerRef = null;
protected RecipeWidget widget = null;
protected RecipeId recipeId = null;
@@ -81,12 +67,16 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
}
if (this.widget != null) {
return new Dimension(this.widget.w + BG_PADDING * 2, this.widget.h + BG_PADDING * 2 + 12);
return new Dimension(getContentWidth() + BG_PADDING * 2, this.widget.h + BG_PADDING * 2 + 12);
}
return new Dimension(0, 0);
}
private int getContentWidth() {
return Math.max(this.widget.w, GuiDraw.getStringWidth(this.recipeName));
}
@Override
public void draw(int x, int y) {
if (this.widget == null) return;
@@ -107,25 +97,24 @@ public class RecipeTooltipLineHandler implements ITooltipLineHandler {
GuiContainerManager.enable2DRender();
GL11.glColor4f(1, 1, 1, 1);
BG_TEXTURE.draw(
-TRANSPARENCY_BORDER,
-TRANSPARENCY_BORDER,
size.width + TRANSPARENCY_BORDER * 2,
size.height + TRANSPARENCY_BORDER * 2);
UIRecipeTexture.WIDGET.draw(0, 0, size.width, size.height);
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);
final int titleColor = ColorUtils.recipeTitle.getColor();
GuiDraw.drawRect(BG_PADDING, BG_PADDING, size.width - BG_PADDING * 2, 12, ColorUtils.recipeTitleBG.getColor());
GuiDraw.drawStringC(this.recipeName, size.width / 2, BG_PADDING + 2, titleColor);
if (this.multiplier > 0) {
GuiDraw.drawString(
"x" + ReadableNumberConverter.INSTANCE.toWideReadableForm(this.multiplier),
BG_PADDING + 2,
BG_PADDING + 2,
0xffffff);
titleColor);
}
this.widget.x = BG_PADDING + (getContentWidth() - this.widget.w) / 2;
GuiHelper.useScissor(
this.widget.x,
this.widget.y,
@@ -3,6 +3,7 @@ package codechicken.nei.recipe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.function.IntPredicate;
import java.util.stream.Collectors;
@@ -18,18 +19,19 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
private List<Integer> filteredRecipes;
private List<Integer> searchRecipes;
private volatile List<Integer> searchRecipes;
public SearchRecipeHandler(H handler) {
private volatile int searchVersion;
public SearchRecipeHandler(H handler, IRecipeFilter filter) {
this.original = handler;
if (this.original.numRecipes() == 0) {
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) {
if (filter == null || !this.searchingAvailable()) {
this.filteredRecipes = items.collect(Collectors.toList());
} else {
this.filteredRecipes = items.filter(recipe -> mathRecipe(this.original, recipe, filter))
@@ -64,39 +66,43 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
public List<Integer> getSearchResult(IRecipeFilter filter) {
if (filteredRecipes.isEmpty() || !this.searchingAvailable()) {
if (this.filteredRecipes.isEmpty() || !this.searchingAvailable()) {
return null;
}
List<Integer> filtered = null;
final List<Integer> recipes = IntStream.range(0, filteredRecipes.size()).boxed().collect(Collectors.toList());
final List<Integer> positions = IntStream.range(0, this.filteredRecipes.size()).boxed()
.collect(Collectors.toList());
try {
filtered = ItemList.forkJoinPool.submit(
() -> recipes.parallelStream()
.filter(recipe -> mathRecipe(this.original, filteredRecipes.get(recipe), filter))
return ItemList.forkJoinPool.submit(
() -> positions.parallelStream()
.filter(position -> mathRecipe(this.original, this.filteredRecipes.get(position), filter))
.collect(Collectors.toList()))
.get();
filtered.sort((a, b) -> a - b);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return filtered;
return null;
}
public void setSearchIndices(List<Integer> searchRecipes) {
if (Objects.equals(this.searchRecipes, searchRecipes)) return;
this.searchRecipes = searchRecipes;
this.searchVersion++;
}
public int getSearchVersion() {
return this.searchVersion;
}
public List<Integer> getFilteredRecipes() {
final List<Integer> search = this.searchRecipes;
if (this.searchRecipes == null) {
if (search == null) {
return this.filteredRecipes;
}
final List<Integer> search = this.searchRecipes;
final List<Integer> resolved = new ArrayList<>(search.size());
for (int idx : search) {
@@ -107,21 +113,18 @@ class SearchRecipeHandler<H extends IRecipeHandler> {
}
public int ref(int index) {
final List<Integer> search = this.searchRecipes;
if (searchRecipes != null) {
index = searchRecipes.get(index);
if (search != null) {
index = search.get(index);
}
return filteredRecipes.get(index);
return this.filteredRecipes.get(index);
}
public int numRecipes() {
if (searchRecipes != null) {
return searchRecipes.size();
}
return filteredRecipes.size();
final List<Integer> search = this.searchRecipes;
return search != null ? search.size() : this.filteredRecipes.size();
}
}
@@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
@@ -16,7 +17,7 @@ import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import codechicken.nei.ClientHandler;
import codechicken.nei.ItemStackMap;
import codechicken.nei.ItemStackMap.StackMetaKey;
import codechicken.nei.LRUCache;
import codechicken.nei.api.IStackStringifyHandler;
import codechicken.nei.api.ItemInfo;
@@ -31,7 +32,7 @@ public class StackInfo {
private static final FluidStack NULL_FLUID = new FluidStack(FluidRegistry.WATER, 0);
public static final List<IStackStringifyHandler> stackStringifyHandlers = new ArrayList<>();
private static final Map<String, HashMap<String, String[]>> guidfilters = new HashMap<>();
private static final ItemStackMap<String> guidcache = new ItemStackMap<>();
private static final Map<Item, Map<StackMetaKey, String>> guidcache = new ConcurrentHashMap<>();
private static final LRUCache<ItemStackKey, FluidStack> fluidcache = new LRUCache<>(200);
private static boolean isPausedItemDamageSound = false;
@@ -182,7 +183,9 @@ public class StackInfo {
}
public static String getItemStackGUID(ItemStack stack) {
String guid = guidcache.get(stack);
final Item stackItem = stack.getItem();
final Map<StackMetaKey, String> itemGuids = stackItem != null ? guidcache.get(stackItem) : null;
String guid = itemGuids != null ? itemGuids.get(new StackMetaKey(stack)) : null;
if (guid != null) {
return guid;
@@ -190,7 +193,7 @@ public class StackInfo {
final NBTTagCompound nbTag = itemStackToNBT(stack, false);
if (nbTag == null) {
if (nbTag == null || stack.getItem() == null) {
return "unknown";
}
@@ -239,16 +242,15 @@ public class StackInfo {
}
});
synchronized (guidcache) {
guidcache.put(stack, keys.toString());
}
guid = keys.toString();
} else {
synchronized (guidcache) {
guidcache.put(stack, NBTHelper.toString(nbTag));
}
guid = NBTHelper.toString(nbTag);
}
return guidcache.get(stack);
guidcache.computeIfAbsent(stack.getItem(), item -> new ConcurrentHashMap<>())
.put(new StackMetaKey(stack.copy()), guid);
return guid;
}
public static void loadGuidFilters() {
@@ -27,7 +27,6 @@ import codechicken.nei.NEIClientUtils;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.HandlerInfo;
@@ -137,7 +136,7 @@ public class RecipeChainTooltipLineHandler extends CompositeTooltipLineHandler {
final GuiContainer currentGui = NEIClientUtils.getGuiContainer();
if (this.lastShiftKey && currentGui != null && !(currentGui instanceof GuiRecipe<?>)) {
inventory.putAll(AutoCraftingManager.getInventoryItems(currentGui));
inventory.putAll(ItemStackAmount.of(currentGui));
}
if (!this.outputRecipes.isEmpty()) {
@@ -64,6 +64,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
public boolean showFavorites;
public boolean showOverlay;
public boolean showBadge;
public int windowWidth;
public boolean recipeSpacing;
private String csvLine;
@@ -80,6 +82,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.showFavorites = info.getShowFavoritesButton();
this.showOverlay = info.getShowOverlayButton();
this.showBadge = info.getShowBadge();
this.windowWidth = info.getWindowWidth();
this.recipeSpacing = info.isRecipeSpacing();
this.csvLine = toCsvLine();
}
@@ -92,6 +96,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.info.setShowFavoritesButton(this.showFavorites);
this.info.setShowOverlayButton(this.showOverlay);
this.info.setShowBadge(this.showBadge);
this.info.setWindowWidth(this.windowWidth);
this.info.setRecipeSpacing(this.recipeSpacing);
NEIClientConfig.handlerOrdering.put(this.handlerKey, this.order);
}
@@ -108,6 +114,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.showFavorites = intOrDefault(parts[8], this.showFavorites ? 1 : 0) == 1;
this.showOverlay = intOrDefault(parts[9], this.showOverlay ? 1 : 0) == 1;
this.showBadge = intOrDefault(parts[10], this.showBadge ? 1 : 0) == 1;
this.windowWidth = intOrDefault(parts[11], this.windowWidth);
this.recipeSpacing = intOrDefault(parts[12], this.recipeSpacing ? 1 : 0) == 1;
apply();
}
@@ -125,7 +133,9 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
String.valueOf(this.allowOverflowY ? 1 : 0),
String.valueOf(this.showFavorites ? 1 : 0),
String.valueOf(this.showOverlay ? 1 : 0),
String.valueOf(this.showBadge ? 1 : 0));
String.valueOf(this.showBadge ? 1 : 0),
String.valueOf(this.windowWidth),
String.valueOf(this.recipeSpacing ? 1 : 0));
}
public boolean isUnmodified() {
@@ -148,7 +158,7 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
private static final int LABEL_WIDTH = 50;
private static final String TOOLTIP_PREFIX = "debug.RecipeHandler.";
private static final String HEADER = "HandlerId,YShift,Height,Width,MultiWidgets,Order,AllowOverflowX,AllowOverflowY,ShowFavorites,ShowOverlay,ShowBadge";
private static final String HEADER = "HandlerId,YShift,Height,Width,MultiWidgets,Order,AllowOverflowX,AllowOverflowY,ShowFavorites,ShowOverlay,ShowBadge,WindowWidth,RecipeSpacing";
private final int[] COLORS = new int[] { 0x2200FF00, 0x22FF0000, 0x220000FF, 0x2200FFFF, 0x22FF00FF, 0x22FFFF00 };
public static DebugHandlerWidget instance = new DebugHandlerWidget();
@@ -217,6 +227,11 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
saveHandlerInfoPatch();
}, y);
y = addCheckboxWidget("RecipeSpacing", button -> {
record.recipeSpacing = button.value;
saveHandlerInfoPatch();
}, y);
final LabelWidget readonly = new LabelWidget(0xffffff, true);
readonly.y = y;
@@ -232,7 +247,12 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
y = addTextFieldWidget("Width", HandlerInfo.DEFAULT_WIDTH, (field, oldText) -> {
record.width = field.getInteger();
saveHandlerInfoPatch();
}, newValue -> newValue >= HandlerInfo.DEFAULT_WIDTH, y);
}, newValue -> newValue > 0, y);
y = addTextFieldWidget("WindowWidth", 0, (field, oldText) -> {
record.windowWidth = field.getInteger();
saveHandlerInfoPatch();
}, newValue -> newValue >= 0, y);
y = addCheckboxWidget("AllowOverflowX", button -> {
record.allowOverflowX = button.value;
@@ -474,6 +494,8 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
this.values.get("height").updateValue(String.valueOf(this.record.height));
this.values.get("height_readonly").updateValue(String.valueOf(this.record.height));
this.values.get("width").updateValue(String.valueOf(this.record.width));
this.values.get("windowwidth").updateValue(String.valueOf(this.record.windowWidth));
this.values.get("recipespacing").updateValue(String.valueOf(this.record.recipeSpacing));
this.values.get("multiwidgets").updateValue(String.valueOf(this.record.multiWidgets));
this.values.get("allowoverflowx").updateValue(String.valueOf(this.record.allowOverflowX));
@@ -536,11 +558,7 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && keyID == Keyboard.KEY_D
&& NEIClientUtils.shiftKey()) {
this.showWidget = !this.showWidget;
return true;
} else if (this.record != null) {
if (this.record != null) {
if (this.container.handleKeyPress(keyID, keyChar)) {
return true;
@@ -556,6 +574,13 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
@Override
public boolean onHotkeyPressed() {
if (NEIClientConfig.getBooleanSetting("inventory.guirecipe.handlerInfo") && Keyboard.isKeyDown(Keyboard.KEY_D)
&& NEIClientUtils.shiftKey()) {
this.showWidget = !this.showWidget;
return true;
}
return this.record != null && this.container.onHotkeyPressed();
}
@@ -733,12 +758,17 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
});
}
public void clearGuiReferences() {
this.hoveredRecipe = null;
}
public void loadHandlerInfoPatch() {
ClientHandler.loadSettingsFile("handlers.patch", lines -> {
final List<String> linesList = lines.collect(Collectors.toCollection(ArrayList::new));
if (linesList.isEmpty() || !HEADER.equals(linesList.get(0))) {
// files saved before new columns were appended have a prefix of the current header
if (linesList.isEmpty() || linesList.get(0).isEmpty() || !HEADER.startsWith(linesList.get(0))) {
return;
}
@@ -752,7 +782,7 @@ public class DebugHandlerWidget extends Widget implements IContainerTooltipHandl
key -> new HandlerInfoRecord(
key,
GuiRecipeTab.handlerMap.getOrDefault(key, GuiRecipeTab.DEFAULT_HANDLER_INFO)));
record.apply((line + ",null,null,null,null,null,null,null,null,null,null"));
record.apply((line + ",null,null,null,null,null,null,null,null,null,null,null,null"));
}
});
@@ -10,6 +10,9 @@ import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import codechicken.nei.api.IStackStringifyHandler;
import codechicken.nei.item.ItemFluidDisplay;
import cpw.mods.fml.common.registry.GameRegistry;
@@ -22,6 +25,11 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
protected static Class<?> gtMetaGeneratedTool = null;
protected static Field playSound = null;
private static final Supplier<Item> AE2FC_FLUID_PACKET = Suppliers
.memoize(() -> GameRegistry.findItem("ae2fc", "fluid_packet"));
private static final Supplier<Item> AE2FC_FLUID_DROP = Suppliers
.memoize(() -> GameRegistry.findItem("ae2fc", "fluid_drop"));
static {
try {
final ClassLoader loader = GTFluidStackStringifyHandler.class.getClassLoader();
@@ -94,11 +102,11 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
return new FluidStack(fluid, 0);
}
} else if (item == GameRegistry.findItem("ae2fc", "fluid_packet")) {
} else if (item == AE2FC_FLUID_PACKET.get()) {
NBTTagCompound nbtTag = stack.getTagCompound();
return FluidStack.loadFluidStackFromNBT((NBTTagCompound) nbtTag.getTag("FluidStack"));
} else if (item == GameRegistry.findItem("ae2fc", "fluid_drop")) {
} else if (item == AE2FC_FLUID_DROP.get()) {
NBTTagCompound nbtTag = stack.getTagCompound();
Fluid fluid = FluidRegistry.getFluid(nbtTag.getString("Fluid").toLowerCase());
@@ -113,9 +121,9 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
@Override
public ItemStack normalizeRecipeQueryStack(ItemStack stack) {
final Item item = stack.getItem();
if (stack.getItem() == GameRegistry.findItem("ae2fc", "fluid_drop")
|| stack.getItem() == GameRegistry.findItem("ae2fc", "fluid_packet")) {
if (item == AE2FC_FLUID_DROP.get() || item == AE2FC_FLUID_PACKET.get()) {
final FluidStack fluidStack = getFluid(stack);
if (fluidStack != null) {
@@ -139,8 +147,7 @@ public class GTFluidStackStringifyHandler implements IStackStringifyHandler {
@Override
public boolean isFluidDisplayItem(ItemStack stack) {
final Item item = stack.getItem();
return (itemFluidDisplay != null && itemFluidDisplay.isInstance(item))
|| item == GameRegistry.findItem("ae2fc", "fluid_packet");
return (itemFluidDisplay != null && itemFluidDisplay.isInstance(item)) || item == AE2FC_FLUID_PACKET.get();
}
}
@@ -29,7 +29,6 @@ import codechicken.nei.PositionedStack;
import codechicken.nei.Widget;
import codechicken.nei.api.IGuiContainerOverlay;
import codechicken.nei.api.ShortcutInputHandler;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.AcceptsFollowingTooltipLineHandler;
@@ -44,39 +43,41 @@ import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeHandlerRef;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.recipe.debug.DebugHandlerWidget;
import codechicken.nei.theme.UIRecipeTexture;
import codechicken.nei.util.NEIMouseUtils;
public class RecipeWidget extends Widget {
protected static final int TICKS_PER_CYCLE = 20;
protected static final DrawableResource PAUSE_MARKER = new DrawableBuilder(
"nei:textures/pinned_pause.png",
0,
0,
8,
8).setTextureSize(8, 8).build();
protected static final DrawableResource PAUSE_MARKER = UIRecipeTexture.ICON_PAUSE;
protected static final int PAUSE_MARKER_OFFSET = 1;
protected static final int BUTTON_GAP = 2;
protected static final int BUTTON_SPACING = 2;
protected static final int BUTTON_BOTTOM_OFFSET = 6;
protected final RecipeGroup group;
protected final IRecipeHandler handler;
protected final HandlerInfo handlerInfo;
protected final Map<PositionedStack, List<Badge>> badgeCache = new WeakHashMap<>();
protected final Map<Integer, List<GuiRecipeButton>> buttonCache = new HashMap<>();
protected final Map<Integer, List<GuiRecipeButton>> layoutCache = new HashMap<>();
protected AcceptsFollowingTooltipLineHandler acceptsTooltip;
protected int recipeHeight = 0;
protected int spaceRight = 0;
protected final ViewState state;
protected int activeMember = 0;
// single state counter: member = allowed[cycle % size], permutation index = cycle / size
protected int cycle = 0;
protected int cycleticks = 0;
protected int lastcycle = -1;
protected int favoriteRevision = FavoriteRecipes.getRevision();
protected boolean showAsWidget = false;
protected boolean update = true;
protected boolean paused = false;
protected List<ItemStack> pinnedIngredients = null;
protected Map<Point, ItemStack> pinnedSlots = Collections.emptyMap();
public RecipeWidget(RecipeHandlerRef handlerRef) {
@@ -84,14 +85,24 @@ public class RecipeWidget extends Widget {
}
public RecipeWidget(IRecipeHandler handler, List<Integer> recipeIndices) {
this(new RecipeGroup(handler, recipeIndices));
this(handler, recipeIndices, null);
}
public RecipeWidget(IRecipeHandler handler, List<Integer> recipeIndices, ViewState state) {
this(new RecipeGroup(handler, recipeIndices), state);
}
public RecipeWidget(RecipeGroup group) {
this(group, null);
}
public RecipeWidget(RecipeGroup group, ViewState state) {
this.group = group;
this.handler = group.getHandler();
this.handlerInfo = group.getHandlerInfo();
this.state = state != null ? state : new ViewState();
update();
restore();
}
public RecipeHandlerRef getRecipeHandlerRef() {
@@ -106,33 +117,81 @@ public class RecipeWidget extends Widget {
return this.group.contains(recipeIndex);
}
// the state may come from a group with other members, then its cycle no longer fits
private void restore() {
final int member = this.group.indexOf(this.state.recipeIndex);
if (member < 0 || this.state.groupSize != this.group.size()) {
this.state.cycle = 0;
}
this.state.groupSize = this.group.size();
// a pause on a recipe hidden by the search stays in the state until the recipe is shown again
if (this.state.pausedRecipeIndex >= 0
&& pinRecipe(this.state.pausedRecipeIndex, this.state.pinnedIngredients)) {
return;
}
setActiveMember(Math.max(member, 0));
syncCycle();
}
public HandlerInfo getHandlerInfo() {
return this.handlerInfo;
}
public void setLocation(int x, int y) {
public void setLocation(int x, int y, int spaceRight) {
this.x = x;
this.y = y;
if (this.spaceRight != spaceRight) {
this.spaceRight = spaceRight;
relayoutButtons();
}
}
public void setHeight(int h) {
if (this.h != h) {
this.h = h;
relayoutButtons();
}
}
public void showAsWidget(boolean show) {
this.showAsWidget = show;
}
@Override
public boolean contains(int px, int py) {
return super.contains(px, py) || isOverButton(px, py);
}
private boolean isOverButton(int px, int py) {
for (GuiRecipeButton button : getRecipeButtonsIfInit()) {
if (button.contains(px - this.x, py - this.y)) {
return true;
}
}
return false;
}
public boolean isPaused() {
return this.paused;
}
public List<ItemStack> getPinnedIngredients() {
return this.pinnedIngredients;
return this.state.pinnedIngredients;
}
public void setPaused(boolean paused) {
final boolean wasPaused = this.paused;
this.paused = paused && this.group.canCycle();
this.state.pausedRecipeIndex = this.paused ? this.state.recipeIndex : -1;
if (!this.paused) {
this.pinnedIngredients = null;
this.state.pinnedIngredients = null;
this.pinnedSlots = Collections.emptyMap();
if (wasPaused) {
@@ -160,9 +219,10 @@ public class RecipeWidget extends Widget {
return false;
}
this.pinnedIngredients = ingredients;
this.state.pinnedIngredients = ingredients;
this.pinnedSlots = slots;
this.paused = true;
this.state.pausedRecipeIndex = recipeIndex;
setActiveMember(member);
updatePermutations();
@@ -219,25 +279,39 @@ public class RecipeWidget extends Widget {
@Override
public void update() {
final int prevW = this.w;
final int prevH = this.h;
int recipeWidth = 0;
this.recipeHeight = 0;
for (int member = 0; member < this.group.size(); member++) {
final int recipe = this.group.getRecipeIndex(member);
recipeWidth = Math.max(recipeWidth, this.handler.getRecipeWidth(recipe));
this.recipeHeight = Math.max(this.recipeHeight, this.handler.getRecipeHeight(recipe));
}
this.w = recipeWidth > 0 ? recipeWidth : this.handlerInfo.getWidth();
if (this.showAsWidget || !this.handlerInfo.isAllowOverflowY()) {
int maxHeight = 0;
this.h = getContentHeight();
}
for (int member = 0; member < this.group.size(); member++) {
final int recipeHeight = this.handler.getRecipeHeight(this.group.getRecipeIndex(member));
if (recipeHeight > 0) {
maxHeight = Math.max(maxHeight, recipeHeight);
}
}
this.w = Math.max(166, this.handlerInfo.getWidth());
this.h = (maxHeight > 0 ? maxHeight : this.handlerInfo.getHeight()) + this.handlerInfo.getYShift();
if (this.w != prevW || this.h != prevH) {
relayoutButtons();
}
this.update = true;
}
public int getContentHeight() {
return (this.recipeHeight > 0 ? this.recipeHeight : this.handlerInfo.getHeight())
+ this.handlerInfo.getYShift();
}
private boolean showFavoritesButton() {
return NEIClientConfig.favoritesEnabled() && this.handlerInfo.getShowFavoritesButton();
}
public List<GuiRecipeButton> getRecipeButtons() {
return this.buttonCache.computeIfAbsent(this.activeMember, this::createButtons);
}
@@ -252,8 +326,55 @@ public class RecipeWidget extends Widget {
return Collections.emptyList();
}
return Collections
.unmodifiableList(initButtons(RecipeHandlerRef.of(this.handler, this.group.getRecipeIndex(member))));
final List<GuiRecipeButton> buttons = initButtons(
RecipeHandlerRef.of(this.handler, this.group.getRecipeIndex(member)));
final List<GuiRecipeButton> unplaced = new ArrayList<>();
// NEI creates its buttons at (0, 0), so anything else was placed by a mod and keeps its position.
for (GuiRecipeButton button : buttons) {
if (button.xPosition == 0 && button.yPosition == 0) {
unplaced.add(button);
}
}
this.layoutCache.put(member, unplaced);
layoutButtons(unplaced);
return Collections.unmodifiableList(buttons);
}
private void relayoutButtons() {
for (List<GuiRecipeButton> buttons : this.layoutCache.values()) {
layoutButtons(buttons);
}
}
private void layoutButtons(List<GuiRecipeButton> buttons) {
final int top = this.handlerInfo.getYShift();
final int bottom = this.h - BUTTON_BOTTOM_OFFSET;
int columnX = 0;
int columnWidth = 0;
int y = bottom;
for (GuiRecipeButton button : buttons) {
if (y != bottom && y - button.height < top) {
columnX += columnWidth + BUTTON_SPACING;
columnWidth = 0;
y = bottom;
}
y -= button.height;
button.xPosition = columnX;
button.yPosition = y;
y -= BUTTON_SPACING;
columnWidth = Math.max(columnWidth, button.width);
}
final int left = this.w + Math.min(BUTTON_GAP, this.spaceRight - columnX - columnWidth);
for (GuiRecipeButton button : buttons) {
button.xPosition += left;
}
}
private List<GuiRecipeButton> initButtons(RecipeHandlerRef ref) {
@@ -289,22 +410,17 @@ public class RecipeWidget extends Widget {
private List<GuiRecipeButton> getDefaultButtons(RecipeHandlerRef ref) {
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(166, 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, ref, x, y));
y -= GuiRecipeButton.BUTTON_HEIGHT + 1;
if (this.handlerInfo.getShowOverlayButton()) {
buttons.add(new GuiOverlayButton(guiContainer, ref, 0, 0));
}
if (showFavorites) {
buttons.add(new GuiFavoriteButton(ref, x, y));
if (showFavoritesButton()) {
buttons.add(new GuiFavoriteButton(ref, 0, 0));
}
return buttons;
@@ -318,10 +434,10 @@ public class RecipeWidget extends Widget {
this.update = false;
if (this.lastcycle == -1) {
this.lastcycle = 0;
this.lastcycle = this.state.cycleticks / TICKS_PER_CYCLE;
applyCycle();
} else if (tickCycle() && !isCycleFrozen(mouseX, mouseY)) {
this.cycle++;
this.state.cycle++;
applyCycle();
} else if (this.favoriteRevision != FavoriteRecipes.getRevision()) {
this.favoriteRevision = FavoriteRecipes.getRevision();
@@ -733,8 +849,8 @@ public class RecipeWidget extends Widget {
private boolean tickCycle() {
if ((this.cycleticks++ / TICKS_PER_CYCLE) != this.lastcycle) {
this.lastcycle = this.cycleticks / TICKS_PER_CYCLE;
if ((this.state.cycleticks++ / TICKS_PER_CYCLE) != this.lastcycle) {
this.lastcycle = this.state.cycleticks / TICKS_PER_CYCLE;
return true;
}
@@ -749,15 +865,14 @@ public class RecipeWidget extends Widget {
return NEIClientConfig.freezeCycleOnHover() && !this.showAsWidget
&& contains(mouseX, mouseY)
&& (getPositionedStackMouseOver(mouseX, mouseY) != null
|| forEachButtons(button -> button.contains(mouseX, mouseY) ? true : null, false));
&& (getPositionedStackMouseOver(mouseX, mouseY) != null || isOverButton(mouseX, mouseY));
}
private void applyCycle() {
if (!this.paused) {
final List<Integer> allowed = this.group.getAllowedMembers();
setActiveMember(allowed.get(this.cycle % allowed.size()));
setActiveMember(allowed.get(this.state.cycle % allowed.size()));
}
this.group.refresh(this.activeMember);
@@ -765,7 +880,7 @@ public class RecipeWidget extends Widget {
}
private int getPermutationIndex() {
return this.cycle / this.group.getAllowedMembers().size();
return this.state.cycle / this.group.getAllowedMembers().size();
}
// keep the permutation index, move the member part of the counter to the active member
@@ -774,7 +889,7 @@ public class RecipeWidget extends Widget {
final int allowedIndex = allowed.indexOf(this.activeMember);
if (allowedIndex >= 0) {
this.cycle = this.cycle / allowed.size() * allowed.size() + allowedIndex;
this.state.cycle = this.state.cycle / allowed.size() * allowed.size() + allowedIndex;
}
}
@@ -823,6 +938,7 @@ public class RecipeWidget extends Widget {
}
}
this.state.recipeIndex = this.group.getRecipeIndex(member);
}
private boolean containsStack(PositionedStack pStack, ItemStack stack) {
@@ -0,0 +1,17 @@
package codechicken.nei.recipe.widget;
import java.util.List;
import net.minecraft.item.ItemStack;
public final class ViewState {
public int recipeIndex = -1;
public int groupSize = 0;
// single state counter: member = allowed[cycle % size], permutation index = cycle / size
public int cycle = 0;
public int cycleticks = 0;
public int pausedRecipeIndex = -1;
public List<ItemStack> pinnedIngredients = null;
}
@@ -0,0 +1,22 @@
package codechicken.nei.recipe.widget;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import codechicken.nei.recipe.IRecipeHandler;
public final class ViewStates {
private final Map<Object, ViewState> groupStates = new HashMap<>();
private final Map<Integer, ViewState> recipeStates = new HashMap<>();
// a group keeps its state while a search hides some of its recipes, a search can't split or merge groups
public ViewState get(IRecipeHandler handler, List<Integer> group) {
final int firstRecipe = group.get(0);
final Object groupId = handler.getRecipeGroupId(firstRecipe);
return groupId != null ? this.groupStates.computeIfAbsent(groupId, k -> new ViewState())
: this.recipeStates.computeIfAbsent(firstRecipe, k -> new ViewState());
}
}
@@ -6,8 +6,8 @@ import org.lwjgl.opengl.GL11;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.theme.UIWidgetTexture;
public class ScrollBar {
@@ -59,21 +59,14 @@ public class ScrollBar {
return new ScrollBar();
}
@Deprecated
public static ScrollBar defaultVerticalBar() {
return new ScrollBar().setTrackWidth(8).setTrackTexture(
new DrawableBuilder("nei:textures/nei_sprites.png", 29, 95, 8, 11).setSlices(0, 0, 3, 4).build())
.setThumbTexture(
new DrawableBuilder("nei:textures/nei_sprites.png", 22, 96, 6, 9).setSlices(0, 0, 3, 2).build())
.setThumbPadding(1, 1, 1, 1);
return UIWidgetTexture.verticalScrollBar();
}
@Deprecated
public static ScrollBar defaultHorizontalBar() {
return new ScrollBar().setTrackWidth(8).setOverflowType(OverflowType.SCROLL)
.setTrackTexture(
new DrawableBuilder("nei:textures/nei_sprites.png", 0, 97, 11, 8).setSlices(3, 4, 0, 0).build())
.setThumbTexture(
new DrawableBuilder("nei:textures/nei_sprites.png", 12, 98, 9, 6).setSlices(3, 2, 0, 0).build())
.setThumbPadding(1, 1, 1, 1);
return UIWidgetTexture.horizontalScrollBar();
}
/**
@@ -3,6 +3,7 @@ package codechicken.nei.scroll;
import java.awt.Point;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
@@ -80,6 +81,16 @@ public class ScrollContainer extends WidgetContainer {
getVisibleHeight());
}
@Override
public void setWidgets(List<Widget> widgets) {
for (Widget widget : widgets) {
this.relativePosition.remove(widget);
}
super.setWidgets(widgets);
}
@Override
public void clear() {
@@ -3,7 +3,6 @@ package codechicken.nei.search;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
@@ -13,17 +12,11 @@ import codechicken.nei.ItemList.AllMultiItemFilter;
import codechicken.nei.ItemList.AnyMultiItemFilter;
import codechicken.nei.ItemList.NegatedItemFilter;
import codechicken.nei.ItemList.NothingItemFilter;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.SearchTokenParser;
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 ESCAPED_SYMBOL_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
private static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
public ItemFilterVisitor(SearchTokenParser searchParser) {
super(searchParser);
}
@@ -69,7 +62,7 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
@Override
public ItemFilter visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
if (ctx.token() != null) {
final String cleanPattern = getCleanPattern(ctx.token());
final String cleanPattern = SearchExpressionUtils.getCleanPattern(ctx.token());
final SearchTokenParser.ISearchParserProvider provider = searchParser.getProvider(ctx.token().prefix);
if (cleanPattern == null || provider == null) {
return defaultResult();
@@ -81,7 +74,7 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
@Override
public ItemFilter visitToken(SearchExpressionParser.TokenContext ctx) {
final String cleanPattern = getCleanPattern(ctx);
final String cleanPattern = SearchExpressionUtils.getCleanPattern(ctx);
if (cleanPattern != null) {
return getAlwaysProvidersFilter(cleanPattern);
}
@@ -118,38 +111,6 @@ public class ItemFilterVisitor extends AbstractSearchExpressionVisitor<ItemFilte
return constructFilter(filters, AllMultiItemFilter::new);
}
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) {
cleanPattern = ctx.regex().REGEX_CONTENT().getSymbol().getText();
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll("$1 ");
}
}
} else if (ctx.quoted() != null) {
if (ctx.quoted().QUOTED_CONTENT() != null) {
cleanPattern = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
// Unescape quotes
cleanPattern = ESCAPED_QUOTE_PATTERN.matcher(cleanPattern).replaceAll("\"");
cleanPattern = Pattern.quote(cleanPattern);
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll(" ");
}
}
}
return cleanPattern;
}
private ItemFilter visitChildren(ParserRuleContext node, Function<List<ItemFilter>, ItemFilter> filterConstructor) {
if (node.children != null && !node.children.isEmpty()) {
// By default return any found rule child filter (there should be only one)
@@ -2,6 +2,7 @@ package codechicken.nei.search;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import codechicken.nei.ItemList.EverythingItemFilter;
import codechicken.nei.SearchTokenParser;
@@ -10,6 +11,7 @@ import codechicken.nei.api.ItemFilter;
import codechicken.nei.filter.AllMultiRecipeFilter;
import codechicken.nei.filter.RecipeFilter;
import codechicken.nei.filter.RecipeFilter.FilterContext;
import codechicken.nei.filter.RecipeTextFilter;
public class RecipeFilterVisitor extends AbstractSearchExpressionVisitor<IRecipeFilter> {
@@ -41,6 +43,10 @@ public class RecipeFilterVisitor extends AbstractSearchExpressionVisitor<IRecipe
if (ctx == null) {
return defaultResult();
}
if (ctx.type == 4) {
final Predicate<List<String>> text = new RecipeTextVisitor(this.searchParser).visitSearchExpression(ctx);
return text == null ? defaultResult() : new RecipeTextFilter(text);
}
final ItemFilter itemFilter = itemFilterVisitor.visitSearchExpression(ctx);
switch (ctx.type) {
case 0:
@@ -0,0 +1,86 @@
package codechicken.nei.search;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.RuleNode;
import codechicken.nei.SearchField;
import codechicken.nei.SearchTokenParser;
import codechicken.nei.filter.RecipeTextFilter;
public class RecipeTextVisitor extends AbstractSearchExpressionVisitor<Predicate<List<String>>> {
public RecipeTextVisitor(SearchTokenParser searchParser) {
super(searchParser);
}
@Override
public Predicate<List<String>> visitChildren(RuleNode node) {
if (!(node instanceof ParserRuleContext context) || context.children == null) return null;
for (ParseTree child : context.children) {
if (child instanceof RuleNode) return visit(child);
}
return null;
}
@Override
public Predicate<List<String>> visitOrExpression(SearchExpressionParser.OrExpressionContext ctx) {
final List<Predicate<List<String>>> parts = children(ctx);
return parts == null ? null : lines -> parts.stream().anyMatch(part -> part.test(lines));
}
@Override
public Predicate<List<String>> visitSequenceExpression(SearchExpressionParser.SequenceExpressionContext ctx) {
final List<Predicate<List<String>>> parts = children(ctx);
return parts == null ? null : lines -> parts.stream().allMatch(part -> part.test(lines));
}
@Override
public Predicate<List<String>> visitNegateExpression(SearchExpressionParser.NegateExpressionContext ctx) {
final Predicate<List<String>> inner = visitChildren(ctx);
return inner == null ? null : inner.negate();
}
@Override
public Predicate<List<String>> visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
final String prefix = Pattern.quote(String.valueOf(ctx.prefix));
final String cleanPattern = ctx.token() != null ? SearchExpressionUtils.getCleanPattern(ctx.token()) : null;
return matcher(cleanPattern == null ? prefix : prefix + cleanPattern);
}
@Override
public Predicate<List<String>> visitToken(SearchExpressionParser.TokenContext ctx) {
return matcher(SearchExpressionUtils.getCleanPattern(ctx));
}
@Override
protected Predicate<List<String>> defaultResult() {
return null;
}
private static Predicate<List<String>> matcher(String cleanPattern) {
final Pattern pattern = cleanPattern != null ? SearchField.getPattern(cleanPattern) : null;
return pattern == null ? null : RecipeTextFilter.matching(pattern);
}
private List<Predicate<List<String>>> children(ParserRuleContext ctx) {
if (ctx.children == null) return null;
final List<Predicate<List<String>>> parts = new ArrayList<>();
for (ParseTree child : ctx.children) {
if (!(child instanceof RuleNode)) continue;
final Predicate<List<String>> part = visit(child);
if (part == null) return null;
parts.add(part);
}
return parts.isEmpty() ? null : parts;
}
}
@@ -1,7 +1,6 @@
package codechicken.nei.search;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import net.minecraft.util.EnumChatFormatting;
@@ -17,9 +16,6 @@ import codechicken.nei.SearchTokenParser.ISearchParserProvider;
public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisitor<String> {
private static final Pattern REGEX_ESCAPED_SPACE_PATTERN = Pattern.compile("([^\\\\](?:\\\\\\\\)+)?\\\\ ");
private static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
public SearchExpressionFormatVisitor(SearchTokenParser searchParser) {
super(searchParser);
}
@@ -35,7 +31,7 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
@Override
public String visitPrefixedExpression(SearchExpressionParser.PrefixedExpressionContext ctx) {
final EnumChatFormatting format = getFormatting(ctx.prefix, null);
final EnumChatFormatting format = getFormatting(ctx, ctx.prefix, null);
return format + String.valueOf(ctx.prefix) + visitToken(ctx.token());
}
@@ -66,19 +62,19 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
cleanText = ctx.plainText().getText();
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
cleanText = SearchExpressionUtils.ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
}
final EnumChatFormatting format = getFormatting(prefix, EnumChatFormatting.RESET);
final EnumChatFormatting format = getFormatting(ctx, prefix, EnumChatFormatting.RESET);
return format + cleanText;
} else if (ctx.regex() != null) {
cleanText = visitRegex(ctx.regex());
if (spaceModeEnabled == 1) {
cleanText = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll("$1 ");
cleanText = SearchExpressionUtils.REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll("$1 ");
}
} else if (ctx.quoted() != null) {
cleanText = visitQuoted(ctx.quoted());
if (spaceModeEnabled == 1) {
cleanText = ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
cleanText = SearchExpressionUtils.ESCAPED_SPACE_PATTERN.matcher(cleanText).replaceAll(" ");
}
}
return cleanText;
@@ -91,7 +87,7 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
// check if highlight is defined for the token
Optional.ofNullable(SearchExpressionUtils.getHighlight(type))
// check if highlight is defined for the prefix
.orElse(getFormatting(prefix, null))
.orElse(getFormatting(child, prefix, null))
// use default highlight otherwise
).map(EnumChatFormatting::toString).orElse("");
@@ -108,9 +104,16 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
return defaultResult();
}
private EnumChatFormatting getFormatting(Character prefix, EnumChatFormatting defaultFormatting) {
private static boolean isRecipeText(ParseTree node) {
while (node != null && !(node instanceof SearchExpressionParser.SearchExpressionContext)) {
node = node.getParent();
}
return node != null && ((SearchExpressionParser.SearchExpressionContext) node).type == 4;
}
private EnumChatFormatting getFormatting(ParseTree node, Character prefix, EnumChatFormatting defaultFormatting) {
if (prefix != null) {
if (prefix == '\0') {
if (prefix == '\0' || isRecipeText(node)) {
return EnumChatFormatting.RESET;
}
final ISearchParserProvider provider = searchParser.getProvider(prefix);
@@ -2,6 +2,7 @@ package codechicken.nei.search;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import net.minecraft.util.EnumChatFormatting;
@@ -14,6 +15,11 @@ import codechicken.nei.SearchTokenParser;
public class SearchExpressionUtils {
static final Pattern REGEX_ESCAPED_SPACE_PATTERN = Pattern.compile("([^\\\\](?:\\\\\\\\)+)?\\\\ ");
private static final Pattern ESCAPED_SYMBOL_PATTERN = Pattern.compile("\\\\(.)");
private static final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\\\\\"");
static final Pattern ESCAPED_SPACE_PATTERN = Pattern.compile("\\\\ ");
private static final Map<Integer, EnumChatFormatting> HIGHLIGHT_MAP = new HashMap<>();
static {
for (HIGHLIGHTS elem : HIGHLIGHTS.values()) {
@@ -26,7 +32,8 @@ public class SearchExpressionUtils {
public static enum HIGHLIGHTS {
RECIPE(EnumChatFormatting.GREEN, SearchExpressionParser.RECIPE_INGREDIENTS,
SearchExpressionParser.RECIPE_RESULT, SearchExpressionParser.RECIPE_OTHERS),
SearchExpressionParser.RECIPE_RESULT, SearchExpressionParser.RECIPE_OTHERS,
SearchExpressionParser.RECIPE_TEXT),
OR(EnumChatFormatting.GRAY, SearchExpressionParser.OR),
BRACKETS(EnumChatFormatting.GRAY, SearchExpressionParser.LEFT_BRACKET, SearchExpressionParser.RIGHT_BRACKET),
NEGATE(EnumChatFormatting.BLUE, SearchExpressionParser.DASH),
@@ -67,6 +74,38 @@ public class SearchExpressionUtils {
return visitor.visitRecipeSearchExpression(parser.recipeSearchExpression());
}
public static 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) {
cleanPattern = ctx.regex().REGEX_CONTENT().getSymbol().getText();
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = REGEX_ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll("$1 ");
}
}
} else if (ctx.quoted() != null) {
if (ctx.quoted().QUOTED_CONTENT() != null) {
cleanPattern = ctx.quoted().QUOTED_CONTENT().getSymbol().getText();
// Unescape quotes
cleanPattern = ESCAPED_QUOTE_PATTERN.matcher(cleanPattern).replaceAll("\"");
cleanPattern = Pattern.quote(cleanPattern);
final int spaceModeEnabled = NEIClientConfig.getIntSetting("inventory.search.spaceMode");
// Unescape spaces
if (spaceModeEnabled == 1) {
cleanPattern = ESCAPED_SPACE_PATTERN.matcher(cleanPattern).replaceAll(" ");
}
}
}
return cleanPattern;
}
private static <T> SearchExpressionParser createSearchExpressionParser(String text, SearchTokenParser searchParser,
SearchExpressionParserBaseVisitor<T> visitor) {
final boolean doLogExceptions = NEIClientConfig.getBooleanSetting("inventory.search.logSearchExceptions");
@@ -0,0 +1,44 @@
package codechicken.nei.theme;
import org.lwjgl.opengl.GL11;
import codechicken.nei.drawable.DrawableResource;
public final class ButtonSkin {
private final DrawableResource normal;
private final DrawableResource hover;
private final DrawableResource active;
private final DrawableResource disabled;
public ButtonSkin(DrawableResource normal, DrawableResource hover, DrawableResource active,
DrawableResource disabled) {
this.normal = normal;
this.hover = hover;
this.active = active;
this.disabled = disabled;
}
public DrawableResource background(boolean enabled, boolean active, boolean hovered) {
if (!enabled) return this.disabled;
if (active) return this.active;
return hovered ? this.hover : this.normal;
}
public void draw(int x, int y, int w, int h, DrawableResource icon, boolean enabled, boolean active,
boolean hovered) {
GL11.glColor4f(1, 1, 1, 1);
background(enabled, active, hovered).draw(x, y, w, h);
drawIcon(x, y, w, h, icon, enabled);
}
public static void drawIcon(int x, int y, int w, int h, DrawableResource icon, boolean enabled) {
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1, 1, 1, enabled ? 1 : 0.5f);
icon.draw(x + (w - icon.getWidth()) / 2, y + (h - icon.getHeight()) / 2);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1, 1, 1, 1);
}
}
@@ -0,0 +1,47 @@
package codechicken.nei.theme;
import codechicken.nei.drawable.DrawableResource;
public final class UIRecipeTexture {
public static final DrawableResource WINDOW = UISprite
.of("recipe/window", 176, 109, new int[] { 6, 6, 6, 6 }, new int[] { 5, 33, 5, 5 });
public static final DrawableResource WIDGET = UISprite
.of("recipe/widget", 176, 95, new int[] { 6, 6, 6, 6 }, new int[] { 5, 19, 5, 5 });
private static final DrawableResource[] TAB = UISprite.frames("recipe/tab", 24, 27, 2);
private static final DrawableResource[] NAV = UISprite.frames("recipe/icon_nav", 12, 12, 2);
private static final DrawableResource[] FAVORITE = UISprite.frames("recipe/icon_favorite", 12, 12, 2);
private static final DrawableResource[] OVERLAY = UISprite.frames("recipe/icon_overlay", 12, 12, 3);
private static final DrawableResource[] ITEM_STATUS = UISprite.frames("recipe/item_status", 12, 12, 2);
public static final DrawableResource TAB_SELECTED = TAB[0];
public static final DrawableResource TAB_UNSELECTED = TAB[1];
private static final DrawableResource[] CATALYST = UISprite
.frames("recipe/catalyst_tab", 23, 28, 2, new int[] { 6, 6, 0, 6 }, new int[] { 5, 5, 5, 5 });
public static final DrawableResource CATALYST_TAB = CATALYST[0];
public static final DrawableResource CATALYST_TAB_JOINED = CATALYST[1];
public static final DrawableResource CATALYST_SLOT = UISprite
.of("recipe/catalyst_slot", 18, 18, UISprite.DEFAULT_SPACE, new int[] { 1, 1, 1, 1 });
public static final DrawableResource ICON_PREV = NAV[0];
public static final DrawableResource ICON_NEXT = NAV[1];
public static final DrawableResource ICON_SEARCH = UISprite.of("recipe/icon_search", 12, 12);
public static final DrawableResource ICON_PAUSE = UISprite.of("recipe/icon_pause", 12, 12);
public static final DrawableResource ICON_FAVORITE_OFF = FAVORITE[0];
public static final DrawableResource ICON_FAVORITE_ON = FAVORITE[1];
public static final DrawableResource ICON_OVERLAY = OVERLAY[0];
public static final DrawableResource ICON_OVERLAY_FILL = OVERLAY[1];
public static final DrawableResource ICON_OVERLAY_FILL_ERROR = OVERLAY[2];
public static final DrawableResource ITEM_MISSING = ITEM_STATUS[0];
public static final DrawableResource ITEM_PRESENT = ITEM_STATUS[1];
private UIRecipeTexture() {}
}
@@ -0,0 +1,58 @@
package codechicken.nei.theme;
import net.minecraft.util.ResourceLocation;
import codechicken.nei.drawable.DrawableResource;
public final class UISprite {
public static final int[] DEFAULT_SPACE = new int[] { 0, 0, 0, 0 };
private UISprite() {}
public static DrawableResource of(String name, int w, int h, int[] margin, int[] slice) {
return frames(name, w, h, 1, margin, slice)[0];
}
public static DrawableResource of(String name, int w, int h) {
return of(name, w, h, DEFAULT_SPACE, DEFAULT_SPACE);
}
public static DrawableResource[] frames(String name, int w, int h, int count) {
return frames(name, w, h, count, DEFAULT_SPACE, DEFAULT_SPACE);
}
// frames are stacked top to bottom and each includes the margin; {left, top, right, bottom}
public static DrawableResource[] frames(String name, int w, int h, int count, int[] margin, int[] slice) {
final ResourceLocation texture = new ResourceLocation("nei", "textures/gui/" + name + ".png");
final int frameWidth = w + margin[0] + margin[2];
final int frameHeight = h + margin[1] + margin[3];
final DrawableResource[] frames = new DrawableResource[count];
for (int i = 0; i < count; i++) {
frames[i] = new DrawableResource(
texture,
0,
i * frameHeight,
frameWidth,
frameHeight,
-margin[1],
-margin[3],
-margin[0],
-margin[2],
frameWidth,
frameHeight * count,
slice[0] + margin[0],
slice[2] + margin[2],
slice[1] + margin[1],
slice[3] + margin[3]);
}
return frames;
}
}
@@ -0,0 +1,45 @@
package codechicken.nei.theme;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.scroll.ScrollBar;
import codechicken.nei.scroll.ScrollBar.ScrollType;
public final class UIWidgetTexture {
private static final DrawableResource[] BTN = UISprite
.frames("widgets/button", 12, 12, 4, UISprite.DEFAULT_SPACE, new int[] { 2, 2, 2, 3 });
public static final DrawableResource BTN_NORMAL = BTN[0];
public static final DrawableResource BTN_HOVER = BTN[1];
public static final DrawableResource BTN_ACTIVE = BTN[2];
public static final DrawableResource BTN_DISABLED = BTN[3];
public static final ButtonSkin BUTTON = new ButtonSkin(BTN_NORMAL, BTN_HOVER, BTN_ACTIVE, BTN_DISABLED);
private static final int[] THUMB_INSET = new int[] { 1, 1, 1, 1 };
// frame 0 is the track, frame 1 the thumb drawn inside a transparent THUMB_INSET border of the same frame size
public static final DrawableResource SCROLL_V_TRACK = UISprite
.frames("widgets/scroll_v", 8, 11, 2, UISprite.DEFAULT_SPACE, new int[] { 1, 1, 1, 1 })[0];
public static final DrawableResource SCROLL_V_THUMB = UISprite
.frames("widgets/scroll_v", 6, 9, 2, THUMB_INSET, new int[] { 1, 1, 1, 2 })[1];
public static final DrawableResource SCROLL_H_TRACK = UISprite
.frames("widgets/scroll_h", 11, 8, 2, UISprite.DEFAULT_SPACE, new int[] { 1, 1, 1, 1 })[0];
public static final DrawableResource SCROLL_H_THUMB = UISprite
.frames("widgets/scroll_h", 9, 6, 2, THUMB_INSET, new int[] { 1, 1, 2, 1 })[1];
public static final int SCROLL_TRACK_WIDTH = 8;
private UIWidgetTexture() {}
public static ScrollBar verticalScrollBar() {
return new ScrollBar().setTrackWidth(SCROLL_TRACK_WIDTH).setTrackTexture(SCROLL_V_TRACK)
.setThumbTexture(SCROLL_V_THUMB).setThumbPadding(1, 1, 1, 1);
}
public static ScrollBar horizontalScrollBar() {
return new ScrollBar().setScrollType(ScrollType.HORIZONTAL).setTrackWidth(SCROLL_TRACK_WIDTH)
.setTrackTexture(SCROLL_H_TRACK).setThumbTexture(SCROLL_H_THUMB).setThumbPadding(1, 1, 1, 1);
}
}
@@ -26,6 +26,9 @@ public class FavoriteStorage {
protected final Map<RecipeId, Long> recipeIdToItemHash = new HashMap<>();
protected final Map<Long, ItemStack> itemHashToItemStack = new HashMap<>();
/** The key of the last looked up stack. Its NBT copies the whole stack, which is looked up every frame. */
private static volatile LookupKey lastLookupKey = null;
public void clear() {
this.itemStackToRecipeId.clear();
this.fluidToRecipeId.clear();
@@ -95,7 +98,7 @@ public class FavoriteStorage {
RecipeId recipeId = this.itemHashToRecipeId.get(getItemKey(stack));
if (recipeId == null) {
recipeId = this.itemStackToRecipeId.get(StackInfo.itemStackToNBT(stack, false));
recipeId = this.itemStackToRecipeId.get(getLookupKey(stack));
}
if (recipeId == null) {
@@ -105,6 +108,28 @@ public class FavoriteStorage {
return recipeId;
}
private static NBTTagCompound getLookupKey(ItemStack stack) {
LookupKey key = lastLookupKey;
if (key == null || !key.stack.isItemEqual(stack) || !ItemStack.areItemStackTagsEqual(key.stack, stack)) {
key = new LookupKey(stack.copy(), StackInfo.itemStackToNBT(stack, false));
lastLookupKey = key;
}
return key.nbt;
}
private static class LookupKey {
private final ItemStack stack;
private final NBTTagCompound nbt;
private LookupKey(ItemStack stack, NBTTagCompound nbt) {
this.stack = stack;
this.nbt = nbt;
}
}
public ItemStack getItemStack(RecipeId recipeId) {
NBTTagCompound itemStackNBT = this.recipeIdToItemStack.get(recipeId);
@@ -10,6 +10,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import net.minecraft.creativetab.CreativeTabs;
@@ -128,8 +129,8 @@ public class ItemUntranslator {
private static final String CONFIG_FILE = "untranslator.cfg";
private static final ItemUntranslator instance = new ItemUntranslator();
private final Map<String, String> secondNames = new HashMap<>();
private final Map<String, String> processedNames = new HashMap<>();
private final Map<String, String> secondNames = new ConcurrentHashMap<>();
private final Map<String, String> processedNames = new ConcurrentHashMap<>();
private ItemUntranslator() {}
@@ -241,14 +242,19 @@ public class ItemUntranslator {
return EnumChatFormatting.getTextWithoutFormattingCodes(name).trim();
}
public synchronized String getItemStackDisplayName(ItemStack stack) {
public String getItemStackDisplayName(ItemStack stack) {
if (stack == null || this.secondNames.isEmpty()) {
return "";
}
final String guidKey = StackInfo.getItemStackGUID(stack);
final String displayName = this.processedNames.get(guidKey);
return displayName != null ? displayName : processDisplayName(stack, guidKey);
}
private synchronized String processDisplayName(ItemStack stack, String guidKey) {
return this.processedNames.computeIfAbsent(guidKey, stackKey -> {
String displayName = this.secondNames.get(stackKey);
@@ -346,10 +346,10 @@ moze_intel.projecte.integration.NEI.NEIAlchBagHandler,ProjectE,ProjectE:item.pe_
de.katzenpapst.amunra.nei.recipehandler.ARCircuitFab,Pra's Galacticraft Mod,GalacticraftCore:tile.machine2:4,,GalacticraftAmunRa,TRUE,,,,,,,,,,,,
de.katzenpapst.amunra.nei.recipehandler.ARNasaWorkbenchShuttle,Pra's Galacticraft Mod,GalacticraftAmunRa:item.itemShuttle,,GalacticraftAmunRa,TRUE,,,130,168,16,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerFloatingFlowers,Botania,Botania:miniIsland,,Botania,TRUE,,,,,5,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,137,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,137,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,137,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,130,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerBrewery,Botania,Botania:brewery,,Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerPureDaisy,Botania,Botania:specialFlower,"{type:puredaisy}",Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.recipe.RecipeHandlerLexicaBotania,Botania,Botania:lexicon,,Botania,TRUE,,,,,,,,,,,,
@@ -523,10 +523,10 @@ de.ellpeck.actuallyadditions.mod.nei.NEICompostRecipe,Actually Additions,Actuall
de.ellpeck.actuallyadditions.mod.nei.NEIReconstructorRecipe,Actually Additions,ActuallyAdditions:blockAtomicReconstructor,,ActuallyAdditions,TRUE,,,,,,,,,,,,
de.ellpeck.actuallyadditions.mod.nei.NEITreasureChestRecipe,Actually Additions,ActuallyAdditions:blockTreasureChest,,ActuallyAdditions,TRUE,,,,,,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerFloatingFlowers,Botania,Botania:miniIsland,,Botania,TRUE,,,,,5,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,137,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,137,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,137,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,130,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerPetalApothecary,Botania,Botania:altar,,Botania,TRUE,,,102,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerRunicAltar,Botania,Botania:runeAltar,,Botania,TRUE,,,122,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerManaPool,Botania,Botania:pool,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerElvenTrade,Botania,Botania:alfheimPortal,,Botania,TRUE,,,90,166,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerBrewery,Botania,Botania:brewery,,Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerPureDaisy,Botania,Botania:specialFlower,"{type:puredaisy}",Botania,TRUE,,,,,4,,,,,,,
vazkii.botania.client.integration.nei.RecipeHandlerLexicaBotania,Botania,Botania:lexicon,,Botania,TRUE,,,,,,,,,,,,
1 handler modName itemName nbtInfo modId modRequired excludedModId yShift handlerHeight handlerWidth maxRecipesPerPage imageResource imageX imageY imageWidth imageHeight itemNotes useCustomScroll
346 de.katzenpapst.amunra.nei.recipehandler.ARCircuitFab Pra's Galacticraft Mod GalacticraftCore:tile.machine2:4 GalacticraftAmunRa TRUE
347 de.katzenpapst.amunra.nei.recipehandler.ARNasaWorkbenchShuttle Pra's Galacticraft Mod GalacticraftAmunRa:item.itemShuttle GalacticraftAmunRa TRUE 130 168 16
348 vazkii.botania.client.integration.nei.recipe.RecipeHandlerFloatingFlowers Botania Botania:miniIsland Botania TRUE 5
349 vazkii.botania.client.integration.nei.recipe.RecipeHandlerPetalApothecary Botania Botania:altar Botania TRUE 102 137 166 4
350 vazkii.botania.client.integration.nei.recipe.RecipeHandlerRunicAltar Botania Botania:runeAltar Botania TRUE 122 137 166 4
351 vazkii.botania.client.integration.nei.recipe.RecipeHandlerManaPool Botania Botania:pool Botania TRUE 90 137 166 4
352 vazkii.botania.client.integration.nei.recipe.RecipeHandlerElvenTrade Botania Botania:alfheimPortal Botania TRUE 90 130 166 4
353 vazkii.botania.client.integration.nei.recipe.RecipeHandlerBrewery Botania Botania:brewery Botania TRUE 4
354 vazkii.botania.client.integration.nei.recipe.RecipeHandlerPureDaisy Botania Botania:specialFlower {type:puredaisy} Botania TRUE 4
355 vazkii.botania.client.integration.nei.recipe.RecipeHandlerLexicaBotania Botania Botania:lexicon Botania TRUE
523 de.ellpeck.actuallyadditions.mod.nei.NEIReconstructorRecipe Actually Additions ActuallyAdditions:blockAtomicReconstructor ActuallyAdditions TRUE
524 de.ellpeck.actuallyadditions.mod.nei.NEITreasureChestRecipe Actually Additions ActuallyAdditions:blockTreasureChest ActuallyAdditions TRUE
525 vazkii.botania.client.integration.nei.RecipeHandlerFloatingFlowers Botania Botania:miniIsland Botania TRUE 5
526 vazkii.botania.client.integration.nei.RecipeHandlerPetalApothecary Botania Botania:altar Botania TRUE 102 137 166 4
527 vazkii.botania.client.integration.nei.RecipeHandlerRunicAltar Botania Botania:runeAltar Botania TRUE 122 137 166 4
528 vazkii.botania.client.integration.nei.RecipeHandlerManaPool Botania Botania:pool Botania TRUE 90 137 166 4
529 vazkii.botania.client.integration.nei.RecipeHandlerElvenTrade Botania Botania:alfheimPortal Botania TRUE 90 130 166 4
530 vazkii.botania.client.integration.nei.RecipeHandlerBrewery Botania Botania:brewery Botania TRUE 4
531 vazkii.botania.client.integration.nei.RecipeHandlerPureDaisy Botania Botania:specialFlower {type:puredaisy} Botania TRUE 4
532 vazkii.botania.client.integration.nei.RecipeHandlerLexicaBotania Botania Botania:lexicon Botania TRUE
+18 -4
View File
@@ -343,6 +343,9 @@ nei.options.inventory.guirecipe.slotHighlightPresent.false=No
nei.options.inventory.guirecipe.infiniteScroll=Use Infinite Scroll
nei.options.inventory.guirecipe.infiniteScroll.true=Yes
nei.options.inventory.guirecipe.infiniteScroll.false=No
nei.options.inventory.guirecipe.evenRecipeSpacing=Spread Recipes Evenly
nei.options.inventory.guirecipe.evenRecipeSpacing.true=Yes
nei.options.inventory.guirecipe.evenRecipeSpacing.false=No
nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst=JEI Style Recipe Catalysts
nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst.0=None
nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst.1=Grid
@@ -360,6 +363,8 @@ nei.options.inventory.guirecipe.scrollPages.true=Enabled
nei.options.inventory.guirecipe.scrollPages.false=Disabled
nei.options.inventory.guirecipe.maxHeight=Max Height
nei.options.inventory.guirecipe.minWidth=Minimum Recipe Screen Width
nei.options.inventory.guirecipe.topMargin=Recipe Screen Top Margin
nei.options.inventory.showItemQuantityWidget=Show Item Quantity Widget
nei.options.inventory.showItemQuantityWidget.true=Yes
nei.options.inventory.showItemQuantityWidget.false=No
@@ -412,9 +417,6 @@ nei.options.inventory.search.subsetsSearchMode=Item Subsets Search
nei.options.inventory.search.subsetsSearchMode.0=Always
nei.options.inventory.search.subsetsSearchMode.1=Prefix: %s
nei.options.inventory.search.subsetsSearchMode.2=Never
nei.options.inventory.optimize_gui_overlap_computation=Optimize computation for GUI overlap
nei.options.inventory.optimize_gui_overlap_computation.true=Yes
nei.options.inventory.optimize_gui_overlap_computation.false=No
nei.options.inventory.autocrafting=Autocrafting
nei.options.inventory.autocrafting.true=Enabled
nei.options.inventory.autocrafting.false=Disabled
@@ -566,6 +568,15 @@ nei.options.world.overlays=Overlays Settings
nei.options.world.overlays.lock=Lock overlays between dimensions
nei.options.world.overlays.lock.true=Enabled
nei.options.world.overlays.lock.false=Disabled
nei.options.world.overlays.mobOverlayStyle=Mob Spawn Overlay Style
nei.options.world.overlays.mobOverlayStyle.x=X
nei.options.world.overlays.mobOverlayStyle.connected=Connected
nei.options.world.overlays.mobOverlayStyle.square=Square
nei.options.world.overlays.mobOverlayStyle.pufferfish=Pufferfish
nei.options.world.overlays.mobOverlayRadius=Mob Spawn Overlay Horizontal Radius
nei.options.world.overlays.mobOverlayRadius.tip=Horizontal block radius scanned around you. Range 8-64 blocks
nei.options.world.overlays.mobOverlayVerticalRadius=Mob Spawn Overlay Vertical Radius
nei.options.world.overlays.mobOverlayVerticalRadius.tip=Blocks scanned above and below you. Range 4-64 blocks
nei.options.tools=Tools
nei.options.tools.export_configs=Default Config Files
@@ -624,6 +635,8 @@ nei.debug.RecipeHandler.yShift=yShift
nei.debug.RecipeHandler.MultiWidgets=Multi Widgets
nei.debug.RecipeHandler.Height=Height
nei.debug.RecipeHandler.Width=Width
nei.debug.RecipeHandler.WindowWidth=Window Width
nei.debug.RecipeHandler.RecipeSpacing=Recipe Spacing
nei.debug.RecipeHandler.ShowFavorites=Show Favorites
nei.debug.RecipeHandler.ShowOverlay=Show Overlays
nei.debug.RecipeHandler.ShowBadge=Show Badge
@@ -649,7 +662,8 @@ nei.recipe.search.tooltip.name=Filter Syntax
nei.recipe.search.tooltip.shift=§7Hold §6Shift§7 for more info
nei.recipe.search.tooltip.input=%s§ftext§8 - §7search in inputs
nei.recipe.search.tooltip.output=%s§ftext§8 - §7search in outputs
nei.recipe.search.tooltip.auxiliary=%s§ftext§8 - §7search in other stacks (fuel, catalysts)
nei.recipe.search.tooltip.text=%s§ftext§8 - §7search in recipe text
nei.recipe.search.tooltip.auxiliary=%s§ftext§8 - §7search in other stacks
nei.recipe.search.tooltip.all=%s§ftext§8 - §7all inputs must match (same with > and ^)
nei.recipe.search.tooltip.prefix=%stext§8 - §7%s
@@ -213,6 +213,8 @@ nei.options.inventory.guirecipe.jeiStyleRecipeCatalyst.2=Скролл
nei.options.inventory.guirecipe.cycledIngredientsTooltip=Подсказка циклических ингредиентов
nei.options.inventory.guirecipe.cycledIngredientsTooltip.true=Показывать
nei.options.inventory.guirecipe.cycledIngredientsTooltip.false=Скрыть
nei.options.inventory.guirecipe.minWidth=Минимальная ширина окна рецептов
nei.options.inventory.guirecipe.topMargin=Верхний отступ окна рецептов
nei.options.inventory.showItemQuantityWidget=Показывать виджет количества предметов
nei.options.inventory.showItemQuantityWidget.true=Да
nei.options.inventory.showItemQuantityWidget.false=Нет
@@ -251,15 +253,15 @@ nei.options.inventory.search.subsetsSearchMode=Поиск по подмноже
nei.options.inventory.search.subsetsSearchMode.0=Всегда
nei.options.inventory.search.subsetsSearchMode.1=Префикс: %s
nei.options.inventory.search.subsetsSearchMode.2=Никогда
nei.options.inventory.optimize_gui_overlap_computation=Оптимизация вычислений при перекрытии GUI
nei.options.inventory.optimize_gui_overlap_computation.true=Да
nei.options.inventory.optimize_gui_overlap_computation.false=Нет
nei.options.inventory.guirecipe.shiftOverlayRecipe=Требовать удержание Shift для перемещения предметов при отображении рецепта
nei.options.inventory.guirecipe.shiftOverlayRecipe.true=Да
nei.options.inventory.guirecipe.shiftOverlayRecipe.false=Нет
nei.options.inventory.guirecipe.freezeCycleOnHover=Останавливать перелистывание рецепта при наведении на предмет или кнопку
nei.options.inventory.guirecipe.freezeCycleOnHover.true=Да
nei.options.inventory.guirecipe.freezeCycleOnHover.false=Нет
nei.options.inventory.guirecipe.evenRecipeSpacing=Равномерно распределять рецепты по высоте
nei.options.inventory.guirecipe.evenRecipeSpacing.true=Да
nei.options.inventory.guirecipe.evenRecipeSpacing.false=Нет
nei.options.inventory.widgetsenabled.true=NEI включен
nei.options.inventory.widgetsenabled.false=NEI выключен
nei.options.inventory.cheatmode.0=Режим рецептов
@@ -359,9 +359,6 @@ nei.options.inventory.search.subsetsSearchMode=Пошук у підгрупах
nei.options.inventory.search.subsetsSearchMode.0=Завжди
nei.options.inventory.search.subsetsSearchMode.1=Префікс: %s
nei.options.inventory.search.subsetsSearchMode.2=Ніколи
nei.options.inventory.optimize_gui_overlap_computation=Оптимізувати обчислення перекриття інтерфейсів
nei.options.inventory.optimize_gui_overlap_computation.true=Так
nei.options.inventory.optimize_gui_overlap_computation.false=Ні
nei.options.inventory.autocrafting=Автокрафт
nei.options.inventory.autocrafting.true=Увімкнено
nei.options.inventory.autocrafting.false=Вимкнено
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 312 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 B

Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more