Compare commits

...
4 Commits
Author SHA1 Message Date
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
33 changed files with 1268 additions and 247 deletions

No files matched your search

+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]
;
@@ -447,6 +447,7 @@ public class ClientHandler {
if (event.world == mc.theWorld) {
NEIClientConfig.unloadWorld();
ItemMobSpawner.clearEntityReferences();
WorldOverlayRenderer.onWorldUnload();
RecipeItemInputHandler.instance.clearTooltipCache();
RecipeHandlerRef.clearCache();
ItemPanels.itemPanel.craftablesPanel.clearGuiReferences();
+1 -1
View File
@@ -131,7 +131,7 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
final boolean sameStack = this.stack != null && this.stack.isItemEqual(stack)
&& ItemStack.areItemStackTagsEqual(this.stack, stack);
if (!sameStack) {
this.stack = StackInfo.loadFromNBT(StackInfo.itemStackToNBT(stack), 0);
this.stack = StackInfo.withAmount(stack, 0);
}
} else {
this.stack = null;
@@ -57,6 +57,8 @@ 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.IRecipeHandler;
import codechicken.nei.recipe.InformationHandler;
import codechicken.nei.recipe.RecipeCatalysts;
@@ -442,6 +444,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) {
@@ -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;
@@ -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();
}
@@ -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);
}
}
@@ -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,421 @@
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 the chunk, the height map and the biome of a column, 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);
// on the client, `Chunk.generateHeightMap()` never tests the top layer of the highest non-empty section.
// `getHeightValue()` can then be below a block on that layer, so test that layer here
final int topLayerY = chunk.getTopFilledSegment() + 15;
final boolean isTopLayerFilled = !chunk.isEmpty() && chunk.func_150808_b(x & 15, topLayerY, z & 15) != 0;
final int heightValue = isTopLayerFilled ? topLayerY + 1 : scannedWorld.getHeightValue(x, z);
// `getHeightValue()` is the height above the highest block with a light opacity above 0. A snow layer and a
// hopper have a light opacity of 0, and a mob can spawn on top of a full snow block or a hopper, so scan
// one block above the height value
topY = Math.min(scannedWorld.getHeight() - 1, heightValue + 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
}
}
@@ -199,6 +199,10 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
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");
@@ -121,6 +121,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,7 @@
package codechicken.nei.recipe;
public enum RecipeRole {
INPUT,
OUTPUT,
AUXILIARY
}
@@ -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() {
@@ -536,11 +536,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 +552,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();
}
@@ -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();
}
}
@@ -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");
@@ -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);
+11 -1
View File
@@ -563,6 +563,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
@@ -646,7 +655,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
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -0,0 +1,6 @@
{
"texture": {
"blur": false,
"clamp": true
}
}
@@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Named.named;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@@ -35,6 +36,7 @@ import codechicken.nei.SearchField.SearchParserProvider;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeRole;
import codechicken.nei.search.IdentifierFilter;
@DisplayName("Search expression")
@@ -152,6 +154,10 @@ public class SearchTokenParserTest {
spaceModes,
nonRegexPatternModes);
private static final List<Arguments> regexAllSpaceModesTestProvider = combinationsProvider(
spaceModes,
new ModeValue[] { patternModes[2] });
private static final List<Arguments> spaceIsAndExtendedPlusModeTestProvider = combinationsProvider(
spaceIsAndMode,
extendedPlusPatternMode);
@@ -379,9 +385,9 @@ public class SearchTokenParserTest {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = mock(IRecipeHandler.class);
when(handler.getIngredientStacks(0)).thenReturn(positionedStacks(itemA));
when(handler.getResultStacks(0)).thenReturn(positionedStacks(itemB));
when(handler.getAuxiliaryStacks(0)).thenReturn(positionedStacks(itemC));
when(handler.getSearchStacks(0, RecipeRole.INPUT)).thenReturn(positionedStacks(itemA));
when(handler.getSearchStacks(0, RecipeRole.OUTPUT)).thenReturn(positionedStacks(itemB));
when(handler.getSearchStacks(0, RecipeRole.AUXILIARY)).thenReturn(positionedStacks(itemC));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "<" + itemA.getDisplayName(), handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, ">" + itemB.getDisplayName(), handler));
@@ -390,6 +396,84 @@ public class SearchTokenParserTest {
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, ">" + itemC.getDisplayName(), handler));
}
@DisplayName("Recipe text")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("nonRegexAllSpaceModesTestProvider")
public void testRecipeText(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~foo", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~xyz", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~zzz", handler));
// the text search does not look at the stacks
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~a", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "a", handler));
// the plain search does not look at the text
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "foo", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~-foo", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~-zzz", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "<a~foo", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "<a~zzz", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "<b~foo", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, ">b~xyz", handler));
}
@DisplayName("Recipe text of a recipe without text")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("nonRegexAllSpaceModesTestProvider")
public void testRecipeTextWithoutText(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Collections.emptyList());
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~a", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~-a", handler));
}
@DisplayName("Recipe text with wildcards and regex in Extended mode")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("extendedOnlyAllSpaceModesTestProvider")
public void testRecipeTextExtended(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~f?o", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~x*z", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~x?z?", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~r/^fo+$/", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~r/^o+$/", handler));
}
@DisplayName("Recipe text in Regex mode")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("regexAllSpaceModesTestProvider")
public void testRecipeTextRegex(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~f.o", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~x[y]z", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~x[^y]z", handler));
}
@DisplayName("Recipe text with brackets in Extended+ mode")
@ParameterizedTest(name = "{argumentsWithNames}")
@FieldSource("extendedPlusAllSpaceModesTestProvider")
public void testRecipeTextBrackets(int spaceMode, int patternMode) {
SearchTokenParser searchParser = new SearchTokenParser();
searchParser.addProvider(defaultParserProvider);
IRecipeHandler handler = recipeTextHandler(Arrays.asList("Foo", "xyz"));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~{foo|zzz}", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~{zzz|qqq}", handler));
assertTrue(testRecipeFilter(spaceMode, patternMode, searchParser, "~-{zzz|qqq}", handler));
assertFalse(testRecipeFilter(spaceMode, patternMode, searchParser, "~-{foo|qqq}", handler));
}
// Extended+ specific tests
@DisplayName("Sequence")
@@ -488,6 +572,15 @@ public class SearchTokenParserTest {
return matchedItems;
}
private static IRecipeHandler recipeTextHandler(List<String> text) {
IRecipeHandler handler = mock(IRecipeHandler.class);
when(handler.getSearchStacks(0, RecipeRole.INPUT)).thenReturn(positionedStacks(itemA));
when(handler.getSearchStacks(0, RecipeRole.OUTPUT)).thenReturn(positionedStacks(itemB));
when(handler.getSearchStacks(0, RecipeRole.AUXILIARY)).thenReturn(Collections.emptyList());
when(handler.getSearchText(0)).thenReturn(text);
return handler;
}
private static boolean testRecipeFilter(int spaceMode, int patternMode, SearchTokenParser searchParser,
String search, IRecipeHandler handler) {
setModes(spaceMode, patternMode);