Compare commits

..
Author SHA1 Message Date
ABKQPO c582b1a82c add item and fluid name render 2026-11-22 02:19:36 +08:00
13 changed files with 997 additions and 250 deletions

No files matched your search

@@ -21,6 +21,8 @@ import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.item.ItemNameOverlayMode;
import codechicken.nei.item.ItemNameOverlayRenderer;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
@@ -29,6 +31,8 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
protected static class ScreenCapture {
private long nextCacheRefresh = 0;
private ItemNameOverlayMode itemNameOverlayMode;
private long itemNameOverlayRevision;
private final Framebuffer framebuffer;
public ScreenCapture() {
@@ -45,6 +49,8 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
final Minecraft minecraft = Minecraft.getMinecraft();
return this.nextCacheRefresh == 0 || this.framebuffer.framebufferWidth != minecraft.displayWidth
|| framebuffer.framebufferHeight != minecraft.displayHeight
|| this.itemNameOverlayMode != NEIClientConfig.getItemNameOverlayMode()
|| this.itemNameOverlayRevision != ItemNameOverlayRenderer.INSTANCE.getCacheRevision()
|| getGridRenderingCacheFPS(mode) > 0 && this.nextCacheRefresh < System.currentTimeMillis();
}
@@ -70,6 +76,9 @@ public abstract class ItemsGrid<T extends ItemsGrid.ItemsGridSlot, M extends Ite
callback.run();
this.itemNameOverlayMode = NEIClientConfig.getItemNameOverlayMode();
this.itemNameOverlayRevision = ItemNameOverlayRenderer.INSTANCE.getCacheRevision();
GL11.glPopAttrib();
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
@@ -47,6 +47,7 @@ import codechicken.nei.config.GuiPanelSettings;
import codechicken.nei.config.OptionButton;
import codechicken.nei.config.OptionCycled;
import codechicken.nei.config.OptionExportConfig;
import codechicken.nei.config.OptionFloatField;
import codechicken.nei.config.OptionGamemodes;
import codechicken.nei.config.OptionIntegerField;
import codechicken.nei.config.OptionList;
@@ -57,6 +58,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.item.ItemNameOverlayMode;
import codechicken.nei.item.ItemNameOverlayRenderer;
import codechicken.nei.item.ItemNameOverlaySettings;
import codechicken.nei.moboverlay.MobOverlayScan;
import codechicken.nei.moboverlay.MobOverlayStyle;
import codechicken.nei.recipe.IRecipeHandler;
@@ -72,6 +76,7 @@ public class NEIClientConfig {
private static boolean enabledOverride;
private static String worldPath;
private static final String CHEAT_MODE_KEY = "cheatmode";
private static ItemNameOverlaySettings itemNameOverlaySettings = ItemNameOverlaySettings.defaults();
public static Logger logger = LogManager.getLogger("NotEnoughItems");
public static File configDir = new File(CommonUtils.getMinecraftDir(), "config/NEI/");
@@ -422,6 +427,8 @@ public class NEIClientConfig {
tag.getTag("inventory.itemIDs").getIntValue(1);
API.addOption(new OptionCycled("inventory.itemIDs", 3, true));
setItemNameOverlayDefaults(tag);
tag.getTag("world.highlight_tips").getBooleanValue(false);
tag.getTag("world.highlight_tips.x").getIntValue(5000);
tag.getTag("world.highlight_tips.y").getIntValue(100);
@@ -591,6 +598,99 @@ public class NEIClientConfig {
setDefaultKeyBindings();
}
private static void setItemNameOverlayDefaults(ConfigTagParent tag) {
final ConfigTag overlay = tag.getTag("inventory.itemNameOverlay");
final int previousMode = overlay.getValue() != null ? overlay.getIntValue(3) : 3;
tag.getTag("inventory.itemNameOverlay.mode")
.setComment("Icon name labels: 0 = items, 1 = fluids, 2 = all, 3 = off").getIntValue(previousMode);
// Move the old scalar value into the new settings page without losing the selection.
if (overlay.getValue() != null) {
overlay.setValue(null);
}
API.addOption(new OptionCycled("inventory.itemNameOverlay.mode", 4, true) {
@Override
public void setValue(int value) {
super.setValue(value);
reloadItemNameOverlaySettings();
}
});
addItemNameScaleOption(tag, "fontScale", "Preferred scale for ordinary fonts", 0.5f);
addItemNameScaleOption(tag, "unicodeFontScale", "Preferred scale for Unicode text and fonts", 0.5625f);
addItemNameScaleOption(tag, "minimumScale", "Minimum scale for fitting a name into its label", 0.3f);
addItemNameIntegerOption(tag, "width", "Total label width in icon coordinates", 18, 4, 32);
addItemNameIntegerOption(tag, "maxCharacters", "Maximum characters per line; 0 means automatic", 0, 0, 256);
addItemNameIntegerOption(tag, "maxLines", "Maximum number of name lines", 2, 1, 4);
tag.getTag("inventory.itemNameOverlay.outline").setComment("Draw a one-screen-pixel outline around names")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.itemNameOverlay.outline", true) {
@Override
public boolean onClick(int button) {
final boolean changed = super.onClick(button);
reloadItemNameOverlaySettings();
return changed;
}
});
reloadItemNameOverlaySettings();
}
private static void addItemNameScaleOption(ConfigTagParent tag, String name, String comment, float defaultValue) {
final String path = "inventory.itemNameOverlay." + name;
tag.getTag(path).setComment(comment).setDefaultValue(Float.toString(defaultValue));
API.addOption(new OptionFloatField(path, 0.1f, 2f) {
@Override
public void onTextChange(String text) {
reloadItemNameOverlaySettings();
}
});
}
private static void addItemNameIntegerOption(ConfigTagParent tag, String name, String comment, int defaultValue,
int min, int max) {
final String path = "inventory.itemNameOverlay." + name;
tag.getTag(path).setComment(comment).getIntValue(defaultValue);
API.addOption(new OptionIntegerField(path, min, max) {
@Override
public void onTextChange(String text) {
reloadItemNameOverlaySettings();
}
});
}
private static float readItemNameScale(String name, float fallback) {
try {
final float value = Float
.parseFloat(getSetting("inventory.itemNameOverlay." + name).getValue(Float.toString(fallback)));
return Float.isFinite(value) ? value : fallback;
} catch (NumberFormatException ignored) {
return fallback;
}
}
public static void reloadItemNameOverlaySettings() {
itemNameOverlaySettings = new ItemNameOverlaySettings(
ItemNameOverlayMode.fromConfigValue(getIntSetting("inventory.itemNameOverlay.mode")),
readItemNameScale("fontScale", 0.5f),
readItemNameScale("unicodeFontScale", 0.5625f),
readItemNameScale("minimumScale", 0.3f),
getIntSetting("inventory.itemNameOverlay.width"),
getIntSetting("inventory.itemNameOverlay.maxCharacters"),
getIntSetting("inventory.itemNameOverlay.maxLines"),
getBooleanSetting("inventory.itemNameOverlay.outline"));
ItemNameOverlayRenderer.INSTANCE.setSettings(itemNameOverlaySettings);
}
private static void refreshItemNameOverlaySetting(String setting) {
if (setting.startsWith("inventory.itemNameOverlay.")) {
reloadItemNameOverlaySettings();
}
}
private static void linkOptionList() {
OptionList.setOptionList(new OptionList("nei.options") {
@@ -1273,11 +1373,13 @@ public class NEIClientConfig {
public static void toggleBooleanSetting(String setting) {
ConfigTag tag = getSetting(setting);
tag.setBooleanValue(!tag.getBooleanValue());
refreshItemNameOverlaySetting(setting);
}
public static void cycleSetting(String setting, int max) {
ConfigTag tag = getSetting(setting);
tag.setIntValue((tag.getIntValue() + 1) % max);
refreshItemNameOverlaySetting(setting);
}
public static int getIntSetting(String setting) {
@@ -1286,6 +1388,7 @@ public class NEIClientConfig {
public static void setIntSetting(String setting, int val) {
getSetting(setting).setIntValue(val);
refreshItemNameOverlaySetting(setting);
}
public static String getSearchExpression() {
@@ -1316,6 +1419,14 @@ public class NEIClientConfig {
return OpenGlHelper.framebufferSupported ? getIntSetting("inventory.gridRenderingCacheMode") : 0;
}
public static ItemNameOverlayMode getItemNameOverlayMode() {
return itemNameOverlaySettings.mode;
}
public static ItemNameOverlaySettings getItemNameOverlaySettings() {
return itemNameOverlaySettings;
}
public static boolean enableCollapsibleItems() {
return getBooleanSetting("inventory.collapsibleItems.enabled");
}
@@ -30,8 +30,6 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
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();
// the cells of one column, reused by each compile
private static final byte[] COLUMN_CELLS = new byte[2 * MobOverlayScan.MAX_VERTICAL_RADIUS + 1];
public static void reset() {
mobOverlay = 0;
@@ -113,58 +111,28 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
}
/**
* Add a marked face to {@link #MOB_OVERLAY_LIST} for each block of {@link #MOB_OVERLAY_SCAN} where mobs can spawn,
* in the chunk columns whose cells changed.
* 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 int minX = MOB_OVERLAY_SCAN.getMinX();
final int minZ = MOB_OVERLAY_SCAN.getMinZ();
final int span = MOB_OVERLAY_SCAN.getSpan();
final int toChunkX = (minX + span - 1) >> MobOverlayScan.CHUNK_SHIFT;
final int toChunkZ = (minZ + span - 1) >> MobOverlayScan.CHUNK_SHIFT;
for (int chunkX = minX >> MobOverlayScan.CHUNK_SHIFT; chunkX <= toChunkX; chunkX++) {
for (int chunkZ = minZ >> MobOverlayScan.CHUNK_SHIFT; chunkZ <= toChunkZ; chunkZ++) {
if (!MOB_OVERLAY_LIST.beginChunk(MOB_OVERLAY_SCAN, chunkX, chunkZ)) continue;
MOB_OVERLAY_LIST.endChunk(compileChunkFaces(style, chunkX, chunkZ));
}
}
MOB_OVERLAY_LIST.endCompile();
}
/** @return whether the chunk column has a marked face */
private static boolean compileChunkFaces(MobOverlayStyle style, int chunkX, int chunkZ) {
final int CHUNK_WIDTH = 1 << MobOverlayScan.CHUNK_SHIFT;
final float alpha = style.computeAlpha();
final Tessellator tess = Tessellator.instance;
final int cornerX = chunkX << MobOverlayScan.CHUNK_SHIFT;
final int cornerZ = chunkZ << MobOverlayScan.CHUNK_SHIFT;
final int minX = MOB_OVERLAY_SCAN.getMinX();
final int minZ = MOB_OVERLAY_SCAN.getMinZ();
final int span = MOB_OVERLAY_SCAN.getSpan();
final int height = MOB_OVERLAY_SCAN.getHeight();
boolean hasFaces = false;
tess.startDrawing(style.glMode);
for (int i = Math.max(cornerX - minX, 0); i < Math.min(cornerX + CHUNK_WIDTH - minX, span); i++) {
for (int j = Math.max(cornerZ - minZ, 0); j < Math.min(cornerZ + CHUNK_WIDTH - minZ, span); j++) {
MOB_OVERLAY_SCAN.readColumn(i, j, COLUMN_CELLS);
for (int k = 0; k < height; k++) {
if (MobOverlayScan.extractSpawnMode(COLUMN_CELLS[k]) == 0) continue;
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(
minX + i - cornerX,
k + MobOverlayScan.computeOverlayYOffset(COLUMN_CELLS[k]),
minZ + j - cornerZ);
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);
hasFaces = true;
}
}
}
tess.draw();
return hasFaces;
MOB_OVERLAY_LIST.endCompile();
}
private static void beginMobOverlayDraw(MobOverlayStyle style) {
@@ -0,0 +1,42 @@
package codechicken.nei.config;
import codechicken.lib.gui.GuiDraw;
public class OptionFloatField extends OptionTextField {
public final float min;
public final float max;
public OptionFloatField(String name, float min, float max) {
super(name);
this.min = min;
this.max = max;
}
@Override
protected int getMaxInputWidth() {
return GuiDraw.getStringWidth(Float.toString(max)) + 32;
}
@Override
public boolean isValidInput(String text) {
if (text.isEmpty() || text.equals(".")) {
return true;
}
try {
return Float.isFinite(Float.parseFloat(text));
} catch (NumberFormatException ignored) {
return false;
}
}
@Override
public boolean isValidValue(String text) {
try {
final float value = Float.parseFloat(text);
return Float.isFinite(value) && value >= min && value <= max;
} catch (NumberFormatException ignored) {
return false;
}
}
}
@@ -50,6 +50,8 @@ import codechicken.nei.KeyManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIModContainer;
import codechicken.nei.item.ItemNameOverlayMode;
import codechicken.nei.item.ItemNameOverlayRenderer;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.ItemUntranslator;
import codechicken.nei.util.ReadableNumberConverter;
@@ -62,6 +64,7 @@ public class GuiContainerManager {
@Override
public void onResourceManagerReload(IResourceManager p_110549_1_) {
renderingErrorItems.clear();
ItemNameOverlayRenderer.INSTANCE.clearCache();
ItemList.loadItems.restart();
if (NEIClientConfig.enableItemUntranslator()) {
@@ -348,12 +351,28 @@ public class GuiContainerManager {
drawItems.renderItemAndEffectIntoGUI(fontRenderer, renderEngine, itemstack, offsetX, offsetY);
final ItemNameOverlayMode nameMode = NEIClientConfig.getItemNameOverlayMode();
int nameHeight = 0;
if (nameMode != ItemNameOverlayMode.OFF) {
nameHeight = stackSize.isEmpty() ? 11
: Math.max(
0,
(int) (16
- (Math.max(fontRenderer.FONT_HEIGHT, GuiDraw.fontRenderer.FONT_HEIGHT) - 1)
* scale
- 1));
}
if (scale != 1f && !stackSize.isEmpty()) {
drawBigStackSize(offsetX, offsetY, stackSize, scale);
stackSize = "";
}
drawItems.renderItemOverlayIntoGUI(fontRenderer, renderEngine, itemstack, offsetX, offsetY, stackSize);
if (nameMode != ItemNameOverlayMode.OFF) {
ItemNameOverlayRenderer.INSTANCE
.render(nameMode, itemstack, fontRenderer, offsetX, offsetY, nameHeight);
}
});
}
@@ -620,6 +639,9 @@ public class GuiContainerManager {
* Called at the start of drawScreen
*/
public void preDraw() {
if (NEIClientConfig.getItemNameOverlayMode() != ItemNameOverlayMode.OFF) {
ItemNameOverlayRenderer.INSTANCE.refreshFontState();
}
for (IContainerDrawHandler drawHandler : drawHandlers) drawHandler.onPreDraw(window);
}
@@ -0,0 +1,30 @@
package codechicken.nei.item;
public enum ItemNameOverlayMode {
ITEMS(true, false),
FLUIDS(false, true),
ALL(true, true),
OFF(false, false);
private final boolean items;
private final boolean fluids;
private ItemNameOverlayMode(boolean items, boolean fluids) {
this.items = items;
this.fluids = fluids;
}
public boolean includes(boolean fluidDisplay) {
return fluidDisplay ? fluids : items;
}
public static ItemNameOverlayMode fromConfigValue(int value) {
return switch (value) {
case 0 -> ITEMS;
case 1 -> FLUIDS;
case 2 -> ALL;
default -> OFF;
};
}
}
@@ -0,0 +1,609 @@
package codechicken.nei.item;
import java.lang.reflect.Method;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import com.gtnewhorizon.gtnhlib.util.font.FontRendering;
import com.gtnewhorizon.gtnhlib.util.font.IFontParameters;
import codechicken.nei.LRUCache;
import codechicken.nei.recipe.StackInfo;
import cpw.mods.fml.common.Loader;
public class ItemNameOverlayRenderer {
public static final ItemNameOverlayRenderer INSTANCE = new ItemNameOverlayRenderer();
private static final int[] OUTLINE_STEPS = { -1, -1, 1, 0, 1, 0, 0, 1, 0, 1, -1, 0, -1, 0, 0, -1 };
private final FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);
private final LRUCache<LayoutKey, LabelLayout> layouts = new LRUCache<>(2048);
private final LayoutKey lookupKey = new LayoutKey(null, "", 0, 0, false);
private final GuiScaleCache guiScaleCache = new GuiScaleCache();
private ItemNameOverlaySettings settings = ItemNameOverlaySettings.defaults();
private Object fontState;
private long cacheRevision;
public void render(ItemNameOverlayMode mode, ItemStack stack, FontRenderer font, int x, int y,
int availableHeight) {
if (mode == ItemNameOverlayMode.OFF || stack == null || stack.getItem() == null) {
return;
}
final boolean fluidDisplay = StackInfo.isFluidDisplayItem(stack);
if (!mode.includes(fluidDisplay)) {
return;
}
final String name;
if (fluidDisplay) {
final FluidStack fluid = StackInfo.getFluid(stack);
name = fluid != null ? fluid.getLocalizedName() : stack.getDisplayName();
// Fluid renderers own their amount overlay, so reserve its bottom row.
availableHeight = Math.min(availableHeight, font.getUnicodeFlag() ? 8 : 11);
} else {
name = stack.getDisplayName();
}
final ItemNameOverlaySettings currentSettings = settings;
drawLabel(
font,
name,
x + (16 - currentSettings.width) / 2f,
(float) y,
currentSettings.width,
availableHeight,
currentSettings);
}
public void drawLabel(FontRenderer font, String text, int x, int y, int width, int height) {
drawLabel(font, text, (float) x, (float) y, width, height, settings);
}
private void drawLabel(FontRenderer font, String text, float x, float y, int width, int height,
ItemNameOverlaySettings currentSettings) {
if (text == null || text.isEmpty() || width <= 0 || height <= 0) {
return;
}
lookupKey.set(font, text, width, height, font.getUnicodeFlag());
LabelLayout layout = layouts.get(lookupKey);
if (layout == null) {
// Stored keys are copies; the reusable lookup key never enters the cache.
final LayoutKey key = new LayoutKey(lookupKey);
layout = createLayout(key, currentSettings);
layouts.put(key, layout);
}
if (layout.lines.length == 0) {
return;
}
final int guiScale = readRenderTransform();
final float scaleX = matrixBuffer.get(0);
final float scaleY = matrixBuffer.get(5);
final float translateX = matrixBuffer.get(12);
final float translateY = matrixBuffer.get(13);
final float pixelScaleX = Math.abs(scaleX) * guiScale;
final float pixelScaleY = Math.abs(scaleY) * guiScale;
if (pixelScaleX <= 0 || pixelScaleY <= 0) {
return;
}
final float inverseScale = 1f / layout.scale;
final float pixelWidth = inverseScale / pixelScaleX;
final float pixelHeight = inverseScale / pixelScaleY;
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_CURRENT_BIT | GL11.GL_COLOR_BUFFER_BIT);
GL11.glPushMatrix();
try {
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glTranslatef(x, y, 0);
GL11.glScalef(layout.scale, layout.scale, 1);
for (LabelLine line : layout.lines) {
final float alignedX = (alignToPixel(x + line.x, translateX, scaleX, guiScale) - x) * inverseScale;
final float alignedY = (alignToPixel(y + line.y, translateY, scaleY, guiScale) - y) * inverseScale;
GL11.glTranslatef(alignedX, alignedY, 0);
if (currentSettings.outline) {
drawOutlinedLine(font, line.text, pixelWidth, pixelHeight);
} else {
font.drawString(line.text, 0, 0, 0xFFFFFFFF);
}
GL11.glTranslatef(-alignedX, -alignedY, 0);
}
} finally {
GL11.glPopMatrix();
GL11.glPopAttrib();
}
}
public void setSettings(ItemNameOverlaySettings settings) {
Objects.requireNonNull(settings);
if (!this.settings.equals(settings)) {
this.settings = settings;
clearCache();
}
}
public void refreshFontState() {
final Object currentState = FontAccess.currentState();
if (!Objects.equals(fontState, currentState)) {
fontState = currentState;
clearCache();
}
}
public void clearCache() {
layouts.clear();
lookupKey.set(null, "", 0, 0, false);
cacheRevision++;
}
public long getCacheRevision() {
return cacheRevision;
}
private int readRenderTransform() {
final Minecraft minecraft = Minecraft.getMinecraft();
final int guiScale = guiScaleCache.getScaleFactor(minecraft);
matrixBuffer.clear();
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuffer);
return guiScale;
}
private float alignToPixel(float coordinate, float translation, float scale, int guiScale) {
final float screenPosition = (translation + coordinate * scale) * guiScale;
return (Math.round(screenPosition) / (float) guiScale - translation) / scale;
}
private LabelLayout createLayout(LayoutKey key, ItemNameOverlaySettings settings) {
final FontRenderer font = key.font;
final String text = sanitizeText(key.text);
final float minimumScale = settings.minimumScale;
if (text.isEmpty()) {
return new LabelLayout(font, key.width, Collections.emptyList(), minimumScale);
}
final boolean unicode = key.unicode || hasUnicodeCharacters(text);
final float preferredScale = Math.max(minimumScale, unicode ? settings.unicodeFontScale : settings.fontScale);
final float lineHeight = FontAccess.lineHeight(font);
final float singleLineScale = Math.min(
preferredScale,
Math.min(key.width / (float) Math.max(1, getTextWidth(font, text)), key.height / (lineHeight + 1)));
if (singleLineScale >= minimumScale && fitsCharacterLimit(text, settings.maxCharacters)) {
return new LabelLayout(font, key.width, Collections.singletonList(text), singleLineScale);
}
int availableLines = 1;
for (int lineCount = 2; lineCount <= settings.maxLines; lineCount++) {
final float wrappedScale = Math.min(preferredScale, key.height / (lineHeight * lineCount + 1));
if (wrappedScale < minimumScale) {
break;
}
availableLines = lineCount;
final int maximumWidth = (int) (key.width / minimumScale);
List<String> completeLines = wrapText(font, text, maximumWidth, lineCount, settings.maxCharacters);
if (fitsWidth(font, completeLines, maximumWidth, settings.maxCharacters)) {
// Find the narrowest complete split before reducing the configured multi-line scale.
int lowerWidth = 1;
int upperWidth = maximumWidth;
while (lowerWidth < upperWidth) {
final int candidateWidth = lowerWidth + (upperWidth - lowerWidth) / 2;
final List<String> candidateLines = wrapText(
font,
text,
candidateWidth,
lineCount,
settings.maxCharacters);
if (fitsWidth(font, candidateLines, candidateWidth, settings.maxCharacters)) {
upperWidth = candidateWidth;
completeLines = candidateLines;
} else {
lowerWidth = candidateWidth + 1;
}
}
int widestLine = 1;
for (String line : completeLines) {
widestLine = Math.max(widestLine, getTextWidth(font, line));
}
final float completeScale = Math.min(wrappedScale, key.width / (float) widestLine);
return new LabelLayout(font, key.width, completeLines, completeScale);
}
}
final float croppedScale = Math.min(preferredScale, key.height / (lineHeight * availableLines + 1));
if (croppedScale < minimumScale) {
return new LabelLayout(font, key.width, Collections.emptyList(), croppedScale);
}
final int textWidth = (int) (key.width / croppedScale);
final List<String> shortenedLines = new ArrayList<>(
wrapText(font, text, textWidth, availableLines, settings.maxCharacters));
if (shortenedLines.isEmpty()) {
final String line = ellipsize(font, text, textWidth, settings.maxCharacters);
if (!line.isEmpty()) {
shortenedLines.add(line);
}
} else {
final int lastLine = shortenedLines.size() - 1;
shortenedLines
.set(lastLine, ellipsize(font, shortenedLines.get(lastLine), textWidth, settings.maxCharacters));
}
return new LabelLayout(font, key.width, shortenedLines, croppedScale);
}
private List<String> wrapText(FontRenderer font, String text, int width, int maxLines, int maxCharacters) {
if (text.indexOf(' ') >= 0) {
final List<String> wordLines = wrapText(font, text, width, maxLines, maxCharacters, true);
if (fitsWidth(font, wordLines, width, maxCharacters)) {
return wordLines;
}
}
return wrapText(font, text, width, maxLines, maxCharacters, false);
}
private List<String> wrapText(FontRenderer font, String text, int width, int maxLines, int maxCharacters,
boolean wordBreaks) {
final List<String> lines = new ArrayList<>(maxLines);
String remainder = text;
while (!remainder.isEmpty()) {
if (lines.size() == maxLines - 1) {
lines.add(remainder);
break;
}
String prefix = trimToWidth(font, remainder, width);
if (maxCharacters > 0) {
prefix = trimCharacters(prefix, maxCharacters);
}
if (prefix.isEmpty()) {
return Collections.emptyList();
}
int split = prefix.length();
if (wordBreaks && split < remainder.length()) {
final int lastSpace = prefix.lastIndexOf(' ');
if (lastSpace > 0) {
split = lastSpace;
}
}
lines.add(remainder.substring(0, split).trim());
remainder = remainder.substring(split).trim();
}
return lines;
}
private boolean fitsWidth(FontRenderer font, List<String> lines, int width, int maxCharacters) {
if (lines.isEmpty()) {
return false;
}
for (String line : lines) {
if (getTextWidth(font, line) > width || !fitsCharacterLimit(line, maxCharacters)) {
return false;
}
}
return true;
}
private String sanitizeText(String text) {
text = FontAccess.preprocess(text);
if (text.indexOf('\u00a7') >= 0) {
final StringBuilder plain = new StringBuilder(text.length());
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) == '\u00a7' && index + 1 < text.length()) {
index++;
} else {
plain.append(text.charAt(index));
}
}
text = plain.toString();
}
return text.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').trim();
}
private String ellipsize(FontRenderer font, String text, int width, int maxCharacters) {
if (getTextWidth(font, text) <= width && fitsCharacterLimit(text, maxCharacters)) {
return text;
}
String suffix = trimToWidth(font, "...", width);
if (maxCharacters > 0) {
suffix = trimCharacters(suffix, maxCharacters);
}
String prefix = trimToWidth(font, text, width - getTextWidth(font, suffix)).trim();
if (maxCharacters > 0) {
prefix = trimCharacters(prefix, maxCharacters - suffix.codePointCount(0, suffix.length()));
}
String shortened = prefix + suffix;
// Custom glyph spacing at the join must be measured as part of the complete string.
while (!prefix.isEmpty() && getTextWidth(font, shortened) > width) {
prefix = prefix.substring(0, prefix.offsetByCodePoints(prefix.length(), -1)).trim();
shortened = prefix + suffix;
}
return shortened;
}
private String trimToWidth(FontRenderer font, String text, int width) {
if (width <= 0) {
return "";
}
final String trimmed = FontAccess.trimToWidth(font, text, width);
final int length = trimmed.length();
return length > 0 && Character.isHighSurrogate(trimmed.charAt(length - 1)) ? trimmed.substring(0, length - 1)
: trimmed;
}
private static int getTextWidth(FontRenderer font, String text) {
return FontAccess.width(font, text);
}
private static boolean fitsCharacterLimit(String text, int limit) {
return limit == 0 || text.codePointCount(0, text.length()) <= limit;
}
private static String trimCharacters(String text, int limit) {
final int count = Math.min(limit, text.codePointCount(0, text.length()));
return text.substring(0, text.offsetByCodePoints(0, count));
}
private boolean hasUnicodeCharacters(String text) {
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) > 255) {
return true;
}
}
return false;
}
private void drawOutlinedLine(FontRenderer font, String text, float pixelWidth, float pixelHeight) {
// Visit each neighboring screen pixel once, then return to the center.
for (int index = 0; index < OUTLINE_STEPS.length; index += 2) {
GL11.glTranslatef(OUTLINE_STEPS[index] * pixelWidth, OUTLINE_STEPS[index + 1] * pixelHeight, 0);
font.drawString(text, 0, 0, 0xFF000000);
}
GL11.glTranslatef(pixelWidth, 0, 0);
font.drawString(text, 0, 0, 0xFFFFFFFF);
}
private static class LabelLayout {
private final LabelLine[] lines;
private final float scale;
private LabelLayout(FontRenderer font, int width, List<String> texts, float scale) {
this.lines = new LabelLine[texts.size()];
this.scale = scale;
final float lineHeight = FontAccess.lineHeight(font);
final float anchorOffset = (lineHeight - font.FONT_HEIGHT) / 2f;
for (int index = 0; index < texts.size(); index++) {
final String text = texts.get(index);
this.lines[index] = new LabelLine(
text,
(width - getTextWidth(font, text) * scale) / 2f,
(1 + anchorOffset + index * lineHeight) * scale);
}
}
}
private static class LabelLine {
private final String text;
private final float x;
private final float y;
private LabelLine(String text, float x, float y) {
this.text = text;
this.x = x;
this.y = y;
}
}
private static class FontAccess {
private static final boolean GTNH_FONTS = hasFontAPI();
private static Method settingsMethod = findSettingsMethod();
private static boolean hasFontAPI() {
if (!Loader.isModLoaded("gtnhlib")) {
return false;
}
try {
FontRendering.class.getMethod("preprocessText", String.class);
IFontParameters.class.getMethod("getCharWidthFine", char.class);
IFontParameters.class.getMethod("getGlyphScaleX");
IFontParameters.class.getMethod("getGlyphScaleY");
IFontParameters.class.getMethod("getGlyphSpacing");
IFontParameters.class.getMethod("getWhitespaceScale");
return true;
} catch (ReflectiveOperationException | LinkageError ignored) {
return false;
}
}
private static Method findSettingsMethod() {
if (!Loader.isModLoaded("angelica")) {
return null;
}
try {
return Class.forName(
"com.gtnewhorizons.angelica.client.font.GlyphSettings",
false,
ItemNameOverlayRenderer.class.getClassLoader()).getMethod("current");
} catch (ReflectiveOperationException | LinkageError ignored) {
return null;
}
}
private static Object currentState() {
if (settingsMethod != null) {
try {
return settingsMethod.invoke(null, (Object[]) null);
} catch (ReflectiveOperationException | LinkageError ignored) {
settingsMethod = null;
}
}
return null;
}
private static String preprocess(String text) {
return GTNH_FONTS ? FontRendering.preprocessText(text) : text;
}
private static int width(FontRenderer font, String text) {
// Preserve custom FontRenderer subclasses' own measurement overrides.
return GTNH_FONTS && font.getClass() == FontRenderer.class && font instanceof IFontParameters
? FontRendering.getStringWidth(text, font)
: font.getStringWidth(text);
}
private static String trimToWidth(FontRenderer font, String text, int width) {
return GTNH_FONTS && font.getClass() == FontRenderer.class && font instanceof IFontParameters
? FontRendering.trimStringToWidth(text, width, false, font)
: font.trimStringToWidth(text, width);
}
private static float lineHeight(FontRenderer font) {
if (GTNH_FONTS && font instanceof IFontParameters parameters) {
final float scale = parameters.getGlyphScaleY();
if (Float.isFinite(scale) && scale > 0) {
return font.FONT_HEIGHT * scale;
}
}
return font.FONT_HEIGHT;
}
private static void applyMetrics(LayoutKey key, FontRenderer font) {
if (GTNH_FONTS && font instanceof IFontParameters parameters) {
key.glyphScaleX = parameters.getGlyphScaleX();
key.glyphScaleY = parameters.getGlyphScaleY();
key.glyphSpacing = parameters.getGlyphSpacing();
key.whitespaceScale = parameters.getWhitespaceScale();
} else {
key.glyphScaleX = 1;
key.glyphScaleY = 1;
key.glyphSpacing = 0;
key.whitespaceScale = 1;
}
}
}
private static class GuiScaleCache {
private int displayWidth = -1;
private int displayHeight = -1;
private int setting;
private boolean unicode;
private int scaleFactor;
private int getScaleFactor(Minecraft minecraft) {
final boolean currentUnicode = minecraft.func_152349_b();
if (displayWidth != minecraft.displayWidth || displayHeight != minecraft.displayHeight
|| setting != minecraft.gameSettings.guiScale
|| unicode != currentUnicode) {
displayWidth = minecraft.displayWidth;
displayHeight = minecraft.displayHeight;
setting = minecraft.gameSettings.guiScale;
unicode = currentUnicode;
scaleFactor = new ScaledResolution(minecraft, displayWidth, displayHeight).getScaleFactor();
}
return scaleFactor;
}
}
private static class LayoutKey {
private FontRenderer font;
private String text;
private int width;
private int height;
private int fontHeight;
private float glyphScaleX;
private float glyphScaleY;
private float glyphSpacing;
private float whitespaceScale;
private boolean unicode;
private int hash;
private LayoutKey(FontRenderer font, String text, int width, int height, boolean unicode) {
set(font, text, width, height, unicode);
}
private LayoutKey(LayoutKey key) {
this.font = key.font;
this.text = key.text;
this.width = key.width;
this.height = key.height;
this.fontHeight = key.fontHeight;
this.glyphScaleX = key.glyphScaleX;
this.glyphScaleY = key.glyphScaleY;
this.glyphSpacing = key.glyphSpacing;
this.whitespaceScale = key.whitespaceScale;
this.unicode = key.unicode;
this.hash = key.hash;
}
private void set(FontRenderer font, String text, int width, int height, boolean unicode) {
this.font = font;
this.text = text;
this.width = width;
this.height = height;
this.fontHeight = font != null ? font.FONT_HEIGHT : 0;
if (font != null) {
FontAccess.applyMetrics(this, font);
} else {
this.glyphScaleX = 1;
this.glyphScaleY = 1;
this.glyphSpacing = 0;
this.whitespaceScale = 1;
}
this.unicode = unicode;
int hash = System.identityHashCode(font);
hash = 31 * hash + text.hashCode();
hash = 31 * hash + width;
hash = 31 * hash + height;
hash = 31 * hash + fontHeight;
hash = 31 * hash + Float.floatToIntBits(glyphScaleX);
hash = 31 * hash + Float.floatToIntBits(glyphScaleY);
hash = 31 * hash + Float.floatToIntBits(glyphSpacing);
hash = 31 * hash + Float.floatToIntBits(whitespaceScale);
this.hash = 31 * hash + Boolean.hashCode(unicode);
}
@Override
public boolean equals(Object other) {
return other instanceof LayoutKey key && font == key.font
&& text.equals(key.text)
&& width == key.width
&& height == key.height
&& fontHeight == key.fontHeight
&& Float.compare(glyphScaleX, key.glyphScaleX) == 0
&& Float.compare(glyphScaleY, key.glyphScaleY) == 0
&& Float.compare(glyphSpacing, key.glyphSpacing) == 0
&& Float.compare(whitespaceScale, key.whitespaceScale) == 0
&& unicode == key.unicode;
}
@Override
public int hashCode() {
return hash;
}
}
}
@@ -0,0 +1,70 @@
package codechicken.nei.item;
import java.util.Objects;
public class ItemNameOverlaySettings {
private static final ItemNameOverlaySettings DEFAULT = new ItemNameOverlaySettings(
ItemNameOverlayMode.OFF,
0.5f,
0.5625f,
0.3f,
18,
0,
2,
true);
public final ItemNameOverlayMode mode;
public final float fontScale;
public final float unicodeFontScale;
public final float minimumScale;
public final int width;
public final int maxCharacters;
public final int maxLines;
public final boolean outline;
public ItemNameOverlaySettings(ItemNameOverlayMode mode, float fontScale, float unicodeFontScale,
float minimumScale, int width, int maxCharacters, int maxLines, boolean outline) {
this.mode = Objects.requireNonNull(mode);
this.fontScale = normalizeScale(fontScale, 0.5f);
this.unicodeFontScale = normalizeScale(unicodeFontScale, 0.5625f);
this.minimumScale = normalizeScale(minimumScale, 0.3f);
this.width = Math.max(4, Math.min(32, width));
this.maxCharacters = Math.max(0, Math.min(256, maxCharacters));
this.maxLines = Math.max(1, Math.min(4, maxLines));
this.outline = outline;
}
public static ItemNameOverlaySettings defaults() {
return DEFAULT;
}
private static float normalizeScale(float value, float fallback) {
return Float.isFinite(value) ? Math.max(0.1f, Math.min(2f, value)) : fallback;
}
@Override
public boolean equals(Object other) {
return other instanceof ItemNameOverlaySettings settings && getClass() == other.getClass()
&& mode == settings.mode
&& fontScale == settings.fontScale
&& unicodeFontScale == settings.unicodeFontScale
&& minimumScale == settings.minimumScale
&& width == settings.width
&& maxCharacters == settings.maxCharacters
&& maxLines == settings.maxLines
&& outline == settings.outline;
}
@Override
public int hashCode() {
int hash = mode.hashCode();
hash = 31 * hash + Float.floatToIntBits(fontScale);
hash = 31 * hash + Float.floatToIntBits(unicodeFontScale);
hash = 31 * hash + Float.floatToIntBits(minimumScale);
hash = 31 * hash + width;
hash = 31 * hash + maxCharacters;
hash = 31 * hash + maxLines;
return 31 * hash + Boolean.hashCode(outline);
}
}
@@ -1,40 +1,19 @@
package codechicken.nei.moboverlay;
import java.util.Arrays;
import net.minecraft.client.renderer.GLAllocation;
import org.lwjgl.opengl.GL11;
/**
* The mob spawn overlay quads, compiled into one GL display list for each chunk column that overlaps the box of a
* {@link MobOverlayScan}. A compile rebuilds only the lists of the chunk columns whose
* {@link MobOverlayScan#readChunkVersion} changed. A parent list calls the chunk-column lists, so a draw is one
* {@code glCallList()}.
*/
/** The mob spawn overlay quads, compiled into a GL display list. */
public final class MobOverlayDisplayList {
private static final int NO_LIST = -1;
// the first of `chunkSpan * chunkSpan` lists, in the order of the ring of `MobOverlayScan.readChunkVersion()`, then
// the parent list
private int firstListId = NO_LIST;
private int parentListId = NO_LIST;
private boolean hasParentList;
private int anchorX;
private int anchorY;
private int anchorZ;
private int chunkSpan;
private boolean[] isCompiled = new boolean[0];
private boolean[] hasFaces = new boolean[0];
private int[] compiledChunkX = new int[0];
private int[] compiledChunkZ = new int[0];
private int[] compiledMinY = new int[0];
private int[] compiledChunkVersion = new int[0];
private int listId = -1;
private int modesVersion;
private MobOverlayStyle style;
private int minX;
private int minY;
private int minZ;
private long compiledTicks;
private int compilingChunk;
/**
* Compiles after a {@link MobOverlayScan#getModesVersion} change are debounced to one per {@code MIN_COMPILE_TICKS}
@@ -43,7 +22,7 @@ public final class MobOverlayDisplayList {
*/
public boolean isCompileDue(int currentModesVersion, MobOverlayStyle currentStyle, long worldTicks) {
final int MIN_COMPILE_TICKS = 5;
if (firstListId == NO_LIST || style != currentStyle) return true;
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;
@@ -51,110 +30,36 @@ public final class MobOverlayDisplayList {
}
/**
* Start a compile of {@code scan}. After this call, {@link #beginChunk} and {@link #endChunk} compile each chunk
* column of the box, and {@link #endCompile} compiles the parent list. The lists of the chunk columns outside the
* box are not drawn.
* 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 (chunkSpan != scan.getChunkSpan()) resize(scan.getChunkSpan());
if (style != newStyle) Arrays.fill(isCompiled, false);
if (listId < 0) listId = GLAllocation.generateDisplayLists(1);
modesVersion = scan.getModesVersion();
style = newStyle;
minX = scan.getMinX();
minY = scan.getMinY();
minZ = scan.getMinZ();
compiledTicks = worldTicks;
anchorX = scan.getMinX();
anchorY = scan.getMinY();
anchorZ = scan.getMinZ();
final int fromChunkX = scan.getMinX() >> MobOverlayScan.CHUNK_SHIFT;
final int toChunkX = (scan.getMinX() + scan.getSpan() - 1) >> MobOverlayScan.CHUNK_SHIFT;
final int fromChunkZ = scan.getMinZ() >> MobOverlayScan.CHUNK_SHIFT;
final int toChunkZ = (scan.getMinZ() + scan.getSpan() - 1) >> MobOverlayScan.CHUNK_SHIFT;
for (int chunk = 0; chunk < isCompiled.length; chunk++) {
final boolean isInBox = compiledChunkX[chunk] >= fromChunkX && compiledChunkX[chunk] <= toChunkX
&& compiledChunkZ[chunk] >= fromChunkZ
&& compiledChunkZ[chunk] <= toChunkZ;
isCompiled[chunk] &= isInBox;
}
GL11.glNewList(listId, GL11.GL_COMPILE);
}
/**
* Start the list of chunk column ({@code chunkX}, {@code chunkZ}), with quad positions relative to block ({@code
* chunkX * 16}, {@link MobOverlayScan#getMinY}, {@code chunkZ * 16}) of {@code scan}.
*
* @return false, with no list started, when the list is compiled for the chunk column's version
*/
public boolean beginChunk(MobOverlayScan scan, int chunkX, int chunkZ) {
final int chunk = Math.floorMod(chunkX, chunkSpan) * chunkSpan + Math.floorMod(chunkZ, chunkSpan);
final int chunkVersion = scan.readChunkVersion(chunkX, chunkZ);
final boolean isCurrent = isCompiled[chunk] && compiledChunkX[chunk] == chunkX
&& compiledChunkZ[chunk] == chunkZ
&& compiledChunkVersion[chunk] == chunkVersion;
if (isCurrent) return false;
isCompiled[chunk] = true;
compiledChunkX[chunk] = chunkX;
compiledChunkZ[chunk] = chunkZ;
compiledMinY[chunk] = scan.getMinY();
compiledChunkVersion[chunk] = chunkVersion;
compilingChunk = chunk;
GL11.glNewList(firstListId + chunk, GL11.GL_COMPILE);
return true;
}
public void endChunk(boolean hasChunkFaces) {
GL11.glEndList();
hasFaces[compilingChunk] = hasChunkFaces;
}
/** Compile the parent list, with positions relative to the box's minimum corner at {@link #beginCompile}. */
public void endCompile() {
GL11.glNewList(parentListId, GL11.GL_COMPILE);
for (int chunk = 0; chunk < isCompiled.length; chunk++) {
if (!(isCompiled[chunk] && hasFaces[chunk])) continue;
GL11.glPushMatrix();
GL11.glTranslated(
(compiledChunkX[chunk] << MobOverlayScan.CHUNK_SHIFT) - anchorX,
compiledMinY[chunk] - anchorY,
(compiledChunkZ[chunk] << MobOverlayScan.CHUNK_SHIFT) - anchorZ);
GL11.glCallList(firstListId + chunk);
GL11.glPopMatrix();
}
GL11.glEndList();
hasParentList = true;
}
/** The model view matrix is relative to block ({@code cameraX}, {@code cameraY}, {@code cameraZ}). */
public void draw(int cameraX, int cameraY, int cameraZ) {
if (!hasParentList) return;
GL11.glPushMatrix();
GL11.glTranslated(anchorX - cameraX, anchorY - cameraY, anchorZ - cameraZ);
GL11.glCallList(parentListId);
GL11.glTranslated(minX - cameraX, minY - cameraY, minZ - cameraZ);
GL11.glCallList(listId);
GL11.glPopMatrix();
}
public void delete() {
if (firstListId == NO_LIST) return;
if (listId < 0) return;
GLAllocation.deleteDisplayLists(firstListId);
firstListId = NO_LIST;
parentListId = NO_LIST;
hasParentList = false;
chunkSpan = 0;
Arrays.fill(isCompiled, false);
}
private void resize(int newChunkSpan) {
delete();
chunkSpan = newChunkSpan;
final int chunkCount = newChunkSpan * newChunkSpan;
firstListId = GLAllocation.generateDisplayLists(chunkCount + 1);
parentListId = firstListId + chunkCount;
isCompiled = new boolean[chunkCount];
hasFaces = new boolean[chunkCount];
compiledChunkX = new int[chunkCount];
compiledChunkZ = new int[chunkCount];
compiledMinY = new int[chunkCount];
compiledChunkVersion = new int[chunkCount];
GLAllocation.deleteDisplayLists(listId);
listId = -1;
}
}
@@ -1,7 +1,5 @@
package codechicken.nei.moboverlay;
import java.util.Arrays;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EnumCreatureType;
@@ -33,7 +31,6 @@ public final class MobOverlayScan {
public static final int MIN_VERTICAL_RADIUS = 4;
public static final int MAX_VERTICAL_RADIUS = 64;
public static final int DEFAULT_VERTICAL_RADIUS = 16;
public static final int CHUNK_SHIFT = 4;
private static final int RECENTRE_DISTANCE = 4;
private static final int VERTICAL_RECENTRE_DISTANCE = 2;
private static final int RESCAN_TICKS = 40;
@@ -59,11 +56,6 @@ public final class MobOverlayScan {
// the slice rescan of `update()` continues from this column, numbered `(x - minX) * span + (z - minZ)`
private int nextRescanColumn;
private int modesVersion;
// chunk columns per side of the ring `chunkVersions`, enough for every chunk column that overlaps the box
private int chunkSpan;
// indexed by `findChunk()`
private int[] chunkVersions = new int[0];
private int chunkVersionCount;
private boolean hasModes;
private long scannedTick;
// world of `modes`, with `changeListener` added
@@ -79,8 +71,6 @@ public final class MobOverlayScan {
height = 0;
modes = new byte[0];
dirty = new boolean[0];
chunkSpan = 0;
chunkVersions = new int[0];
hasModes = false;
scannedWorld = null;
// `Chunk.worldObj` references the world
@@ -127,11 +117,6 @@ public final class MobOverlayScan {
return modesVersion;
}
/** Chunk columns per side of the ring of {@link #readChunkVersion}. */
public int getChunkSpan() {
return chunkSpan;
}
public int getSpan() {
return span;
}
@@ -152,42 +137,19 @@ public final class MobOverlayScan {
return minZ;
}
/**
* The version changes when a cell of the chunk column or of a column beside the chunk column changes, and when the
* box moves.
*/
public int readChunkVersion(int chunkX, int chunkZ) {
return chunkVersions[findChunk(chunkX, chunkZ)];
}
/** {@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 extractSpawnMode(modes[findCell(minX + i, minY + k, minZ + j)]);
}
/**
* Copy the cells of column ({@code i}, {@code j}) to {@code columnCells}, from the bottom of the box to the top.
* {@link #extractSpawnMode} and {@link #computeOverlayYOffset} read a cell. The indices are those of
* {@link #readSpawnMode}.
*/
public void readColumn(int i, int j, byte[] columnCells) {
final int columnStart = findColumn(minX + i, minZ + j) * height;
final int bottomCell = Math.floorMod(minY, height);
System.arraycopy(modes, columnStart + bottomCell, columnCells, 0, height - bottomCell);
System.arraycopy(modes, columnStart, columnCells, height - bottomCell, bottomCell);
}
public static byte extractSpawnMode(byte cell) {
return (byte) (cell & SPAWN_MODE_MASK);
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.
* overlay. The indices are those of {@link #readSpawnMode}.
*/
public static double computeOverlayYOffset(byte cell) {
public double readOverlayYOffset(int i, int k, int j) {
final double OVERLAY_GAP = 0.02;
return (double) (cell >> COVER_TOP_SHIFT) / COVER_TOP_STEPS + OVERLAY_GAP;
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) {
@@ -197,8 +159,6 @@ public final class MobOverlayScan {
height = 2 * newVerticalRadius + 1;
modes = new byte[span * span * height];
dirty = new boolean[span * span];
chunkSpan = ((span - 1) >> CHUNK_SHIFT) + 2;
chunkVersions = new int[chunkSpan * chunkSpan];
hasModes = false;
nextRescanColumn = 0;
}
@@ -212,7 +172,6 @@ public final class MobOverlayScan {
scanColumn(x, z);
}
}
markAllChunks();
hasModes = true;
modesVersion++;
scannedTick = scannedWorld.getTotalWorldTime();
@@ -230,7 +189,6 @@ public final class MobOverlayScan {
final int offsetX = centreX - radius - minX;
if (Math.abs(offsetX) > RECENTRE_DISTANCE) {
final int enteringX = offsetX > 0 ? minX + span : minX + offsetX;
markMovedEdgeChunks(minX, offsetX, true);
minX += offsetX;
for (int x = enteringX; x < enteringX + Math.abs(offsetX); x++) {
for (int z = minZ; z < minZ + span; z++) {
@@ -243,7 +201,6 @@ public final class MobOverlayScan {
final int offsetZ = centreZ - radius - minZ;
if (Math.abs(offsetZ) > RECENTRE_DISTANCE) {
final int enteringZ = offsetZ > 0 ? minZ + span : minZ + offsetZ;
markMovedEdgeChunks(minZ, offsetZ, false);
minZ += offsetZ;
for (int x = minX; x < minX + span; x++) {
for (int z = enteringZ; z < enteringZ + Math.abs(offsetZ); z++) {
@@ -263,7 +220,6 @@ public final class MobOverlayScan {
column.scan(enteringY, enteringY + Math.abs(offsetY));
}
}
markAllChunks();
isMoved = true;
}
return isMoved;
@@ -297,49 +253,7 @@ public final class MobOverlayScan {
private boolean scanColumn(int x, int z) {
column.moveTo(x, z);
dirty[findColumn(x, z)] = false;
final boolean isChanged = column.scan(minY, minY + height);
// the connected outline of a cell depends on the spawn modes of the cells beside the cell
if (isChanged) {
for (int offsetX = -1; offsetX <= 1; offsetX++) {
for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
markChunk((x + offsetX) >> CHUNK_SHIFT, (z + offsetZ) >> CHUNK_SHIFT);
}
}
}
return isChanged;
}
/**
* Mark the chunk columns of the box's edge before and after a move of {@code offset} blocks along x, or along z
* when {@code isAlongX} is false, and of the columns that enter or leave the box. No outline is drawn between an
* edge cell of the box and a cell outside the box, so a move changes the outlines of the edge cells.
*/
private void markMovedEdgeChunks(int oldMin, int offset, boolean isAlongX) {
final int lowFrom = Math.min(oldMin, oldMin + offset);
final int lowTo = Math.max(oldMin, oldMin + offset);
final int highFrom = lowFrom + span - 1;
final int highTo = lowTo + span - 1;
final int acrossFrom = isAlongX ? minZ : minX;
for (int across = acrossFrom >> CHUNK_SHIFT; across <= (acrossFrom + span - 1) >> CHUNK_SHIFT; across++) {
for (int along = lowFrom >> CHUNK_SHIFT; along <= lowTo >> CHUNK_SHIFT; along++) {
markChunk(isAlongX ? along : across, isAlongX ? across : along);
}
for (int along = highFrom >> CHUNK_SHIFT; along <= highTo >> CHUNK_SHIFT; along++) {
markChunk(isAlongX ? along : across, isAlongX ? across : along);
}
}
}
private void markAllChunks() {
Arrays.fill(chunkVersions, ++chunkVersionCount);
}
private void markChunk(int chunkX, int chunkZ) {
chunkVersions[findChunk(chunkX, chunkZ)] = ++chunkVersionCount;
}
private int findChunk(int chunkX, int chunkZ) {
return Math.floorMod(chunkX, chunkSpan) * chunkSpan + Math.floorMod(chunkZ, chunkSpan);
return column.scan(minY, minY + height);
}
private int findColumn(int x, int z) {
@@ -400,11 +314,6 @@ public final class MobOverlayScan {
return 0;
}
// `SpawnerAnimals.canCreatureTypeSpawnAtLocation()` rejects a normal cube in the cell for a monster. Most
// cells below the surface are a normal cube. Test the block here, with no light reads and no reads of the
// blocks above and below the cell
if (chunk.getBlock(x & 15, y, z & 15).isNormalCube()) return 0;
if (chunk.getSavedLightValue(EnumSkyBlock.Block, x & 15, y, z & 15) >= 8 || !SpawnerAnimals
.canCreatureTypeSpawnAtLocation(EnumCreatureType.monster, chunk.worldObj, x, y, z)) {
return 0;
@@ -434,6 +434,30 @@ nei.options.inventory.itemIDs=Item IDs
nei.options.inventory.itemIDs.0=Hidden
nei.options.inventory.itemIDs.1=Auto
nei.options.inventory.itemIDs.2=Shown
nei.options.inventory.itemNameOverlay=Icon Name Overlay
nei.options.inventory.itemNameOverlay.tip=Configure names displayed on item and fluid icons.
nei.options.inventory.itemNameOverlay.mode=Display Name on Icons
nei.options.inventory.itemNameOverlay.mode.0=Items Only
nei.options.inventory.itemNameOverlay.mode.1=Fluids Only
nei.options.inventory.itemNameOverlay.mode.2=Shown
nei.options.inventory.itemNameOverlay.mode.3=Hidden
nei.options.inventory.itemNameOverlay.mode.tip=Choose which icons display names. Hover over an icon to see its full name.
nei.options.inventory.itemNameOverlay.fontScale=Font Scale
nei.options.inventory.itemNameOverlay.fontScale.tip=Preferred size for ordinary fonts. 1.0 is normal size; names may shrink to fit.
nei.options.inventory.itemNameOverlay.unicodeFontScale=Unicode Font Scale
nei.options.inventory.itemNameOverlay.unicodeFontScale.tip=Preferred size for Unicode fonts and text, including Chinese characters. 1.0 is normal size.
nei.options.inventory.itemNameOverlay.minimumScale=Minimum Font Scale
nei.options.inventory.itemNameOverlay.minimumScale.tip=Lower bound when shrinking names. This takes priority if it exceeds a preferred font scale.
nei.options.inventory.itemNameOverlay.width=Label Width
nei.options.inventory.itemNameOverlay.width.tip=Total label width in pixels, centered on each icon. Larger values can overlap neighboring icons.
nei.options.inventory.itemNameOverlay.maxCharacters=Maximum Characters per Line
nei.options.inventory.itemNameOverlay.maxCharacters.tip=0 = automatic. Limits Unicode characters per line, including any ellipsis.
nei.options.inventory.itemNameOverlay.maxLines=Maximum Lines
nei.options.inventory.itemNameOverlay.maxLines.tip=1 disables wrapping. The available height and minimum scale can reduce the actual number of lines.
nei.options.inventory.itemNameOverlay.outline=Text Outline
nei.options.inventory.itemNameOverlay.outline.true=Shown
nei.options.inventory.itemNameOverlay.outline.false=Hidden
nei.options.inventory.itemNameOverlay.outline.tip=Draw a one-screen-pixel black outline to keep names readable against the icon.
nei.options.inventory.utilities=Utilities
nei.options.inventory.utilities.tip=Select features for utility mode
nei.options.inventory.utilities.time=Time
@@ -153,6 +153,30 @@ nei.options.inventory.itemIDs=物品ID
nei.options.inventory.itemIDs.0=隐藏
nei.options.inventory.itemIDs.1=自动
nei.options.inventory.itemIDs.2=显示
nei.options.inventory.itemNameOverlay=图标名称显示
nei.options.inventory.itemNameOverlay.tip=调整物品和流体图标上的名称显示。
nei.options.inventory.itemNameOverlay.mode=显示名称
nei.options.inventory.itemNameOverlay.mode.0=仅物品
nei.options.inventory.itemNameOverlay.mode.1=仅流体
nei.options.inventory.itemNameOverlay.mode.2=显示
nei.options.inventory.itemNameOverlay.mode.3=隐藏
nei.options.inventory.itemNameOverlay.mode.tip=选择哪些图标显示名称,悬停可查看完整名称。
nei.options.inventory.itemNameOverlay.fontScale=普通字体缩放
nei.options.inventory.itemNameOverlay.fontScale.tip=普通字体的首选大小,1.0 表示正常字号;名称放不下时可自动缩小。
nei.options.inventory.itemNameOverlay.unicodeFontScale=Unicode 字体缩放
nei.options.inventory.itemNameOverlay.unicodeFontScale.tip=汉字等字符和 Unicode 字体的首选大小,1.0 表示正常字号。
nei.options.inventory.itemNameOverlay.minimumScale=最小字体缩放
nei.options.inventory.itemNameOverlay.minimumScale.tip=自动缩小名称时的下限;若大于首选缩放,则优先采用此下限。
nei.options.inventory.itemNameOverlay.width=标签宽度
nei.options.inventory.itemNameOverlay.width.tip=标签的总宽度(像素),始终以图标居中;较大值可能覆盖相邻图标。
nei.options.inventory.itemNameOverlay.maxCharacters=每行最多字符数
nei.options.inventory.itemNameOverlay.maxCharacters.tip=0 表示自动;限制每行的 Unicode 字符数,包括省略号。
nei.options.inventory.itemNameOverlay.maxLines=最多行数
nei.options.inventory.itemNameOverlay.maxLines.tip=设为 1 可关闭换行;实际行数还取决于可用高度和最小缩放。
nei.options.inventory.itemNameOverlay.outline=文字描边
nei.options.inventory.itemNameOverlay.outline.true=显示
nei.options.inventory.itemNameOverlay.outline.false=隐藏
nei.options.inventory.itemNameOverlay.outline.tip=在文字外绘制 1 个屏幕像素的黑色描边,方便辨认名称。
nei.options.inventory.search.patternMode=搜索模式
nei.options.inventory.search.patternMode.0=简单
nei.options.inventory.search.patternMode.1=扩展
@@ -91,6 +91,30 @@ nei.options.inventory.itemIDs=物品ID
nei.options.inventory.itemIDs.0=隱藏
nei.options.inventory.itemIDs.1=自動
nei.options.inventory.itemIDs.2=顯示
nei.options.inventory.itemNameOverlay=圖示名稱顯示
nei.options.inventory.itemNameOverlay.tip=調整物品和流體圖示上的名稱顯示。
nei.options.inventory.itemNameOverlay.mode=顯示名稱
nei.options.inventory.itemNameOverlay.mode.0=僅物品
nei.options.inventory.itemNameOverlay.mode.1=僅流體
nei.options.inventory.itemNameOverlay.mode.2=顯示
nei.options.inventory.itemNameOverlay.mode.3=隱藏
nei.options.inventory.itemNameOverlay.mode.tip=選擇哪些圖示顯示名稱,懸停可查看完整名稱。
nei.options.inventory.itemNameOverlay.fontScale=普通字型縮放
nei.options.inventory.itemNameOverlay.fontScale.tip=普通字型的首選大小,1.0 表示正常字級;名稱放不下時可自動縮小。
nei.options.inventory.itemNameOverlay.unicodeFontScale=Unicode 字型縮放
nei.options.inventory.itemNameOverlay.unicodeFontScale.tip=漢字等字元和 Unicode 字型的首選大小,1.0 表示正常字級。
nei.options.inventory.itemNameOverlay.minimumScale=最小字型縮放
nei.options.inventory.itemNameOverlay.minimumScale.tip=自動縮小名稱時的下限;若大於首選縮放,則優先採用此下限。
nei.options.inventory.itemNameOverlay.width=標籤寬度
nei.options.inventory.itemNameOverlay.width.tip=標籤的總寬度(像素),始終以圖示置中;較大值可能覆蓋相鄰圖示。
nei.options.inventory.itemNameOverlay.maxCharacters=每行最多字元數
nei.options.inventory.itemNameOverlay.maxCharacters.tip=0 表示自動;限制每行的 Unicode 字元數,包括省略號。
nei.options.inventory.itemNameOverlay.maxLines=最多行數
nei.options.inventory.itemNameOverlay.maxLines.tip=設為 1 可關閉換行;實際行數還取決於可用高度和最小縮放。
nei.options.inventory.itemNameOverlay.outline=文字描邊
nei.options.inventory.itemNameOverlay.outline.true=顯示
nei.options.inventory.itemNameOverlay.outline.false=隱藏
nei.options.inventory.itemNameOverlay.outline.tip=在文字外繪製 1 個螢幕像素的黑色描邊,方便辨認名稱。
nei.options.inventory.search.patternMode=搜索模式
nei.options.inventory.search.patternMode.0=簡單
nei.options.inventory.search.patternMode.1=擴展