Compare commits

...
Author SHA1 Message Date
Jason Mitchell 34b9998ba3 Don't crash with divide by zero error 2021-02-14 15:42:22 -08:00
Jason Mitchell ebbfd349f2 Custom NBT <> JSON Encoder - Fix bookmark saving of items that require escaping 2021-02-14 10:10:53 -08:00
Martin Robertz 127f422e39 Update build.properties 2021-02-02 18:07:13 +01:00
Martin Robertz 3f3ce46301 Merge pull request #38 from GTNewHorizons/classloading-order-fix
Prevent NEIClientConfig being loaded too early
2021-02-02 18:06:53 +01:00
Glease 6fb48eaac4 Prevent NEIClientConfig being loaded too early
Signed-off-by: Glease <[email protected]>
2021-02-02 23:56:42 +08:00
Glease fda24ff453 Add javadoc on what the patch does
Signed-off-by: Glease <[email protected]>
2021-01-30 13:27:25 -08:00
Glease 42445c61e7 Merge OreDictBandAid fix
https://github.com/Glease/OreDictBandAid

Signed-off-by: Glease <[email protected]>
2021-01-30 13:27:25 -08:00
Jason Mitchell 3bb7b6722a Fixes thread starvation issue with parallelStream in findFuels() being called from within another parallelStream on the same ForkJoinPool
Introduces a `findFuelsOnceParallel` that is called before the parallel recipe/usage handlers are run (which now call the non parallel version of findFuels())
2021-01-30 12:38:45 -08:00
Jason Mitchell 03ede1773c Backwards Compat
* Some mods (GC, for example) rely on FuelPair in FurnaceRecipeHandler so add it back as deprecated and switch to TemplateFuelPair
2021-01-17 14:57:58 -08:00
Jason Mitchell f534b6ed0d Some reorganization and bugfixes
* Moved findFuels to TemplateRecipeHandler and made it thread safe.
* Several for loops -> streams
* Slight refactor on Item Filtering.execute()
2021-01-17 14:05:11 -08:00
Martin Robertz 7cfa4ae4ca Merge pull request #31 from GTNewHorizons/small_bug_fixes
Too many ingredients, and apparently an empty fuel?
2020-12-13 22:47:08 +01:00
Jason Mitchell 8c858b5842 Too many ingredients, and apparently an empty fuel? 2020-12-13 12:00:33 -08:00
DreamMasterXXL 6734326ec9 update(NEI)bump version 2020-09-20 20:13:11 +02:00
Martin Robertz 4dc5832d34 Merge pull request #28 from dvdmandt/master
[NEEDS CAREFUL REVIEW] Highly experimental support for backing to BetterQuesting from recipe view
2020-09-03 11:25:07 +02:00
David Lindström abfcdbb3f2 Highly experimental support for backing to BQ when coming from there
This is a highly exprimental solution to backing out of NEI's recipe view back to whatever opened it, such as BetterQuesting. It seems highly likely that this will break something somewhere, but extremely quick testing did not find any such case.
2020-09-03 03:39:30 +02:00
Martin Robertz 2fae9f0968 Merge pull request #27 from TataTawa/patch-1
Update NEIClientConfig.java
2020-08-01 09:56:14 +02:00
TataTawa 2fe5ad7275 Update NEIClientConfig.java
This reduce server start time for about 1 min. Very helpful to GTNH ssp player.
2020-07-29 08:03:43 +00:00
Jason Mitchell e67e134726 Bump version 2020-05-30 09:57:07 -07:00
Jason Mitchell 5b35ce5575 Mark itemlist dirty after adjusting ItemInfo (hidden, overrides, etc). Should fix craft tweaker item hiding. 2020-05-30 09:57:07 -07:00
DreamMasterXXL a2d469b411 update gitignore 2020-05-27 14:49:35 +02:00
Jason Mitchell 5ddfdeafcc Bump version 2020-05-25 13:58:45 -07:00
Jason Mitchell 2062a79a2a Gitignore and should be buildable 2020-05-25 13:54:38 -07:00
Jason Mitchell 23173070c9 lambda 2020-05-25 13:54:38 -07:00
Balthild 4c37971a2b Reuse the ForkJoinPool in ItemList 2020-05-25 13:54:38 -07:00
Balthild 458947628c Add TaskProfiler back 2020-05-25 13:54:38 -07:00
Balthild 6e23c51868 Use a dedicated ForkJoinPool 2020-05-25 13:54:38 -07:00
Balthild c2acfb7d8a Parallelize recipe handlers 2020-05-25 13:54:38 -07:00
DreamMasterXXL edcd410ee1 did it build now ? 2020-05-24 18:47:05 +02:00
DreamMasterXXL 8e366e1982 bump version 2020-05-24 16:33:29 +02:00
Martin Robertz f9c627fdda Merge pull request #22 from Kiwi233/master
Update zh_CN.lang
2020-05-24 12:10:59 +02:00
[Kiwi233] ee04d3786f Update zh_CN.lang 2020-05-24 18:07:44 +08:00
Dream-Master e294cbfd54 update gitignore 2020-04-02 17:20:46 +02:00
Dream-Master ce5928ce7e change folder for gradle 2020-04-02 17:20:27 +02:00
Jason Mitchell 0311599a34 Whoops, it's ArithmeticException not NPE 2020-03-04 20:55:41 -08:00
Jason Mitchell 3bb594ba11 Handle NPE from GC 2020-03-04 16:39:23 -08:00
Jason Mitchell 4b2f944617 promote to non beta 2020-02-22 20:04:28 -08:00
Jason Mitchell 8db8fa1b72 Adjust cheat button alignment with bookmark previous button 2020-02-22 20:04:01 -08:00
Jason Mitchell 10c2326184 Fix the underlying problem -- Bad X! 2020-02-04 20:11:17 -08:00
Jason Mitchell 4375a91220 bump version 2020-02-02 10:45:05 -08:00
Jason Mitchell bb7a9c51f7 Slightly better fix. 2020-02-02 10:44:48 -08:00
Jason Mitchell 1d66a2a015 Create README.md 2020-02-02 10:06:24 -08:00
Jason Mitchell bb40acc7a3 Fix clicking on items in the bookmark panel. Thanks @monatann for contributing 2020-02-02 09:50:22 -08:00
32 changed files with 711 additions and 218 deletions

No files matched your search

+8 -3
View File
@@ -1,7 +1,12 @@
build/build/*
build/run/*
build/.gradle/*
./build/
NotEnoughItems.iml
NotEnoughItems.ipr
NotEnoughItems.iws
*.ipr
*.iml
*.iws
.idea/**
run/*
.gradle/
*.bat
+23
View File
@@ -0,0 +1,23 @@
# NotEnoughItems - GTNH
A continuation of NotEnoughItems for 1.7.10 by the developers of Gregtech: New Horizons modpack, with features either inspired and/or backported from JustEnoughItems
We've tested this against all of the mods included in GTNH, as well as a limited set of other mods (like Reika's mods). Every effort has been made to maintain backwards compatibility, however the focus is on the mods contained in the GTNH modpack.
## New Features:
* Speed - Uses a parallel stream to search the item list over multiple cores, resulting in 2-6x faster searches on average [Feels instantaneous]
* A textbox for search with most of the features you'd expect - moving forward, backwards, selection, etc
* Bookmarks! What are you in the process of crafting? Bookmark it using either 'A' or configure your own key.
* Utility/Cheat buttons line up and wrap based on GUI size
* ItemList is no longer regenerated from the ItemRegistry on every inventory load
## Other items of note:
* Licensed under LGPL - Use this however you want, but please give back any modifications
* Remove TMI style
* Removed inventory Load/Save state
+1 -1
View File
@@ -56,7 +56,7 @@ minecraft {
version = config.mc_version + "-" + config.forge_version
}
def root = project.projectDir.parentFile
def root = project.projectDir;
sourceSets {
main {
java {
+1 -1
View File
@@ -2,4 +2,4 @@ mc_version=1.7.10
forge_version=10.13.4.1614-1.7.10
ccl_version=1.1.3.138
ccc_version=1.0.7.+
mod_version=2.0.0-beta-3-GTNH
mod_version=2.0.10-GTNH
File renamed without changes.
View File
File renamed without changes.
+84 -84
View File
@@ -1,84 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+50 -7
View File
@@ -1,11 +1,16 @@
nei.load=载入
nei.save=保存
nei.bookmark.toggle=书签
nei.enchant=附魔
nei.enchant.level=等级
nei.enchant.locked=锁定
nei.enchant.unlocked=解锁
nei.potion.favourite=最爱的药水
nei.potion.duration=持续时间
nei.potion.level=等级
nei.inventory.options=选项
nei.inventory.prev=上一页
nei.inventory.next=下一页
@@ -39,7 +44,7 @@ nei.inventory.gamemode.3=设置为冒险模式
nei.chat.gamemode.0=生存模式开启
nei.chat.gamemode.1=创造模式开启
nei.chat.gamemode.2=创造模式+开启
nei.hat.gamemode.3=冒险模式开启
nei.chat.gamemode.3=冒险模式开启
nei.chat.rain.on=开启雨雪
nei.chat.rain.off=关闭雨雪
nei.chat.time=白天 %d. %d:00
@@ -55,16 +60,22 @@ nei.options.wbutton.tip.0=使用全局设置
nei.options.wbutton.tip.1=覆写全局设置
nei.options.keys=按键绑定
nei.options.keys.showenchant=显示附魔
nei.options.keys.gui=物品栏
nei.options.keys.gui.recipe=查看合成
nei.options.keys.gui.usage=查看用途
nei.options.keys.gui.enchant=附魔
nei.options.keys.gui.potion=药水
nei.options.keys.gui.back=上一个合成表
nei.options.keys.gui.back=返回上一合成表
nei.options.keys.gui.prev=上一页
nei.options.keys.gui.next=下一页
nei.options.keys.gui.hide=隐藏/显示NEI界面
ei.options.keys.gui.search=跳转到搜索框
nei.options.keys.gui.next_recipe=下一合成表
nei.options.keys.gui.prev_recipe=上一合成表
nei.options.keys.gui.next_machine=下一机器
nei.options.keys.gui.prev_machine=上一机器
nei.options.keys.gui.search=跳转到搜索框
nei.options.keys.gui.bookmark=添加书签
nei.options.keys.world=世界
nei.options.keys.world.chunkoverlay=区块(chunks)边界显示
nei.options.keys.world.moboverlay=刷怪区域显示
@@ -84,7 +95,7 @@ nei.options.inventory.widgetsenabled.false=禁用NEI
nei.options.inventory.cheatmode.0=合成模式
nei.options.inventory.cheatmode.1=实用模式
nei.options.inventory.cheatmode.2=作弊模式
nei.options.inventory.layoutstyle=界面风格
nei.options.inventory.profileRecipes=合成查阅性能分析
nei.options.inventory.profileRecipes.true=开启
nei.options.inventory.profileRecipes.false=关闭
@@ -129,6 +140,7 @@ nei.options.command.heal.tip={0}=玩家
nei.options.world.highlight_tips=高亮显示
nei.options.world.highlight_tips.hide=隐藏
nei.options.world.highlight_tips.show=显示
nei.options.world.highlight_tips.sample=样本
nei.options.tools=工具
nei.options.tools.dump=数据存储
@@ -152,11 +164,15 @@ nei.options.tools.dump.itempanel.dumped=物品面板内容已保存到.minecraft
nei.options.tools.dump.itempanel.mode.0=CSV
nei.options.tools.dump.itempanel.mode.1=NBT
nei.options.tools.dump.itempanel.mode.2=Json
nei.options.tools.dump.itempanel.mode.3=PNG
nei.options.tools.dump.itempanel.icon.dumped=物品面板图标已保存到.minecraft/e%s
nei.options.tools.dump.itempanel.icon.cancelled=保存取消
nei.layoutstyle.minecraft=Minecraft风格
nei.layoutstyle.oldtmi=老式TMI风格
nei.recipe.page=页数 %s/%s
nei.recipe.tooltip=合成表
nei.recipe.shaped=有序合成
nei.recipe.shapeless=无序合成
nei.recipe.furnace=烧制
@@ -180,4 +196,31 @@ nei.itemsort.id=按物品ID排序
nei.itemsort.default=默认
nei.itemsort.default.tip=保留每个物品的自然顺序
nei.itemsort.damage=按照物品耐久(metadata)排序
nei.itemsort.name=按显示名称排序
nei.itemsort.name=按显示名称排序
nei.subsets.Blocks=方块
nei.subsets.Blocks.MobSpawners=刷怪笼
nei.subsets.CreativeTabs=创造模式标签页
nei.subsets.Items=物品
nei.subsets.Items.Armor=装甲
nei.subsets.Items.Armor.Boots=靴子
nei.subsets.Items.Armor.Chestplates=胸甲
nei.subsets.Items.Armor.Helmets=头盔
nei.subsets.Items.Armor.Leggings=腿甲
nei.subsets.Items.Food=食物
nei.subsets.Items.Potions=药水
nei.subsets.Items.Potions.Ingredients=原料
nei.subsets.Items.Potions.Negative=负面效果
nei.subsets.Items.Potions.Neutral=中立效果
nei.subsets.Items.Potions.Positive=正面效果
nei.subsets.Items.Potions.Splash=喷溅
nei.subsets.Items.Tools=工具
nei.subsets.Items.Tools.Axes=斧
nei.subsets.Items.Tools.Hoes=锄
nei.subsets.Items.Tools.Other=其他
nei.subsets.Items.Tools.Pickaxes=镐
nei.subsets.Items.Tools.Shovels=铲
nei.subsets.Items.Weapons=武器
nei.subsets.Items.Weapons.Ranged=远程
nei.subsets.Items.Weapons.Swords=剑
nei.subsets.Mod=Mod
+2
View File
@@ -11,3 +11,5 @@ public net.minecraft.client.gui.GuiScreen field_146292_n #buttonList
public net.minecraft.entity.EntityList field_75624_e #classToIDMapping
public net.minecraft.client.renderer.Tessellator field_78415_z #isDrawing
public net.minecraft.client.multiplayer.PlayerControllerMP field_78779_k #currentGameType
public net.minecraft.nbt.NBTTagCompound field_74784_a #tagMap
public net.minecraft.nbt.NBTTagList field_74747_a #taglist
File renamed without changes.
+13 -7
View File
@@ -1,11 +1,12 @@
package codechicken.nei;
import codechicken.nei.util.NBTJson;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.io.IOUtils;
@@ -71,7 +72,7 @@ public class BookmarkPanel extends ItemPanel {
public void saveBookmarks() {
List<String> strings = new ArrayList<>();
for (ItemStack item:_items) {
strings.add(itemStackToNBT(item, new NBTTagCompound()).toString());
strings.add(NBTJson.toJson(itemStackToNBT(item, new NBTTagCompound())));
}
File file = NEIClientConfig.bookmarkFile;
if(file != null) {
@@ -97,17 +98,18 @@ public class BookmarkPanel extends ItemPanel {
return;
}
_items.clear();
JsonParser parser = new JsonParser();
for (String itemStr: itemStrings) {
try {
NBTTagCompound itemStackNBT = (NBTTagCompound)JsonToNBT.func_150315_a(itemStr);
NBTTagCompound itemStackNBT = (NBTTagCompound) NBTJson.toNbt(parser.parse(itemStr));
ItemStack itemStack = loadFromNBT(itemStackNBT);
if (itemStack != null) {
_items.add(itemStack);
} else {
NEIClientConfig.logger.warn("Failed to load bookmarked ItemStack from json string, the item no longer exists:\n{}", itemStr);
}
} catch (NBTException e) {
NEIClientConfig.logger.error("Failed to load bookmarked ItemStack from json string:\n{}", itemStr, e);
} catch (IllegalArgumentException | JsonSyntaxException e) {
NEIClientConfig.logger.error("Failed to load bookmarked ItemStack from json string:\n{}", itemStr);
}
}
}
@@ -129,6 +131,10 @@ public class BookmarkPanel extends ItemPanel {
return false;
}
@Override
public int getX(GuiContainer gui) {
return 5;
}
@Override
public int getMarginLeft() {
@@ -162,7 +168,7 @@ public class BookmarkPanel extends ItemPanel {
}
public int getWidth(GuiContainer gui) {
return LayoutManager.getLeftSize(gui) - x;
return LayoutManager.getLeftSize(gui) - ( (gui.xSize + gui.width) / 2 + 3 );
}
+6 -10
View File
@@ -18,6 +18,7 @@ import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ItemList
{
@@ -245,20 +246,15 @@ public class ItemList
@Override
public void execute() {
// System.out.println("Executing NEI Item Filtering");
ArrayList<ItemStack> filtered = new ArrayList<>();
ArrayList<ItemStack> filtered;
ItemFilter filter = getItemListFilter();
try {
ItemList.forkJoinPool.submit(() -> items.parallelStream().forEach(item -> {
if (interrupted()) return;
if(filter.matches(item)) {
synchronized (filtered){
filtered.add(item);
}
}
})).get();
filtered = ItemList.forkJoinPool.submit(() -> items.parallelStream()
.filter(filter::matches)
.collect(Collectors.toCollection(ArrayList::new))).get();
} catch (InterruptedException | ExecutionException e) {
filtered = new ArrayList<>();
e.printStackTrace();
stop();
}
+5 -1
View File
@@ -107,6 +107,10 @@ public class ItemPanel extends Widget {
};
}
public int getX(GuiContainer gui) {
return (gui.xSize + gui.width) / 2 + 3;
}
public int getMarginLeft() {
return x + (w % 18) / 2;
}
@@ -177,7 +181,7 @@ public class ItemPanel extends Widget {
pageLabel.text = getLabelText();
y = prev.h + prev.y;
x = (gui.xSize + gui.width) / 2 + 3;
x = getX(gui);
w = getWidth(gui);
h = getHeight(gui);
+5
View File
@@ -554,6 +554,11 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
return true;
}
public static void markItemsDirty() {
// If anything has modified data this depends on, we'll need to reload the item list
itemsLoaded = false;
}
@Override
public void load(GuiContainer gui) {
@@ -143,7 +143,7 @@ public class LayoutStyleMinecraft extends LayoutStyle
}
public void layoutButton(Button button) {
button.x = 6 + (buttonCount % numButtons) * 20;
button.x = 2 + (buttonCount % numButtons) * 20;
button.y = 3 + (buttonCount / numButtons) * 18;
button.h = 17;
+16 -12
View File
@@ -242,21 +242,25 @@ public class NEIClientConfig
configLoaded = true;
ClassDiscoverer classDiscoverer = new ClassDiscoverer(test -> test.startsWith("NEI") && test.endsWith("Config.class"), IConfigureNEI.class);
new Thread("NEI Plugin Loader") {
@Override
public void run() {
ClassDiscoverer classDiscoverer = new ClassDiscoverer(test -> test.startsWith("NEI") && test.endsWith("Config.class"), IConfigureNEI.class);
classDiscoverer.findClasses();
classDiscoverer.findClasses();
for (Class<?> clazz : classDiscoverer.classes) {
try {
IConfigureNEI config = (IConfigureNEI) clazz.newInstance();
config.loadConfig();
NEIModContainer.plugins.add(config);
logger.debug("Loaded " + clazz.getName());
} catch (Exception e) {
logger.error("Failed to Load " + clazz.getName(), e);
for (Class<?> clazz : classDiscoverer.classes) {
try {
IConfigureNEI config = (IConfigureNEI) clazz.newInstance();
config.loadConfig();
NEIModContainer.plugins.add(config);
logger.debug("Loaded " + clazz.getName());
} catch (Exception e) {
logger.error("Failed to Load " + clazz.getName(), e);
}
}
}
}
}.start();
ItemSorter.loadConfig();
}
+5
View File
@@ -121,6 +121,7 @@ public class API
*/
public static void hideItem(ItemStack item) {
ItemInfo.hiddenItems.add(item);
LayoutManager.markItemsDirty();
}
/**
@@ -128,6 +129,7 @@ public class API
*/
public static void setOverrideName(ItemStack item, String name) {
ItemInfo.nameOverrides.put(item, name);
LayoutManager.markItemsDirty();
}
/**
@@ -136,6 +138,7 @@ public class API
*/
public static void addItemListEntry(ItemStack item) {
ItemInfo.itemOverrides.put(item.getItem(), item);
LayoutManager.markItemsDirty();
}
/**
@@ -145,6 +148,7 @@ public class API
if(items == null)
items = Collections.emptyList();
ItemInfo.itemOverrides.replaceValues(item, items);
LayoutManager.markItemsDirty();
}
/**
@@ -273,5 +277,6 @@ public class API
*/
public static void addItemVariant(Item item, ItemStack variant) {
ItemInfo.itemVariants.put(item, variant);
LayoutManager.markItemsDirty();
}
}
+11 -8
View File
@@ -15,6 +15,8 @@ import codechicken.lib.asm.ModularASMTransformer.MethodWriter;
import codechicken.lib.asm.ObfMapping;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
@@ -31,13 +33,7 @@ import static codechicken.lib.asm.InsnComparator.getControlFlowLabels;
import static codechicken.lib.asm.InsnComparator.matches;
import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES;
import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.*;
public class NEITransformer implements IClassTransformer
{
@@ -259,8 +255,15 @@ public class NEITransformer implements IClassTransformer
public byte[] transform(String name, String tname, byte[] bytes) {
if (bytes == null) return null;
try {
if (FMLLaunchHandler.side().isClient())
if (FMLLaunchHandler.side().isClient()) {
if (name.equals("net.minecraftforge.oredict.OreDictionary")) {
ClassReader cr = new ClassReader(bytes);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cr.accept(new OreDictionaryVisitor(ASM5, cw), ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
bytes = cw.toByteArray();
}
bytes = transformSubclasses(name, bytes);
}
bytes = transformer.transform(name, bytes);
} catch (Exception e) {
@@ -0,0 +1,149 @@
package codechicken.nei.asm;
import static org.objectweb.asm.Opcodes.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
/**
* Code without this patch
* <pre>
public class OreDictionary {
public static int getOreID(String name) {
Integer val = nameToId.get(name);
if (val == null)
{
idToName.add(name);
val = idToName.size() - 1; //0 indexed
nameToId.put(name, val);
idToStack.add(new ArrayList<ItemStack>());
idToStackUn.add(new UnmodifiableArrayList(idToStack.get(val)));
}
return val;
}
}
</pre>
Code with this patch
<pre>
public class OreDictionary {
private static final Object emptyEntryCreationLock = new Object();
public static int getOreID(String name) {
Integer val = nameToId.get(name);
if (val == null)
{
synchronized (emptyEntryCreationLock) {
if ((val = nameToId.get(name)) != null)
return val;
idToName.add(name);
val = idToName.size() - 1; //0 indexed
nameToId.put(name, val);
idToStack.add(new ArrayList<ItemStack>());
idToStackUn.add(new UnmodifiableArrayList(idToStack.get(val)));
}
}
return val;
}
}
* </pre>
*/
public class OreDictionaryVisitor extends ClassVisitor {
private static final Logger logger = LogManager.getLogger("OreDictionaryVisitor");
private static class GetOreIDVisitor extends MethodVisitor {
Label jumpEnd;
Label catchStart = new Label();
Label exitStart = new Label();
public GetOreIDVisitor(int api, MethodVisitor mv) {
super(api, mv);
}
@Override
public void visitJumpInsn(int opcode, Label label) {
super.visitJumpInsn(opcode, label);
logger.trace("Adding getOreID MONITERENTER");
jumpEnd = label;
mv.visitFieldInsn(GETSTATIC, "net/minecraftforge/oredict/OreDictionary", "emptyEntryCreationLock", "Ljava/lang/Object;");
mv.visitInsn(MONITORENTER);
mv.visitLabel(catchStart);
mv.visitFieldInsn(GETSTATIC, "net/minecraftforge/oredict/OreDictionary", "nameToId", "Ljava/util/Map;");
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
mv.visitVarInsn(ASTORE, 1);
mv.visitVarInsn(ALOAD, 1);
mv.visitJumpInsn(IFNONNULL, exitStart);
}
@Override
public void visitLabel(Label label) {
if (label.equals(jumpEnd)) {
logger.trace("Adding getOreID MONITEREXIT");
// normal exit
mv.visitLabel(exitStart);
mv.visitFieldInsn(GETSTATIC, "net/minecraftforge/oredict/OreDictionary", "emptyEntryCreationLock", "Ljava/lang/Object;");
mv.visitInsn(MONITOREXIT);
// not normal
mv.visitJumpInsn(GOTO, jumpEnd);
Label catchBegin = new Label();
mv.visitLabel(catchBegin);
mv.visitFieldInsn(GETSTATIC, "net/minecraftforge/oredict/OreDictionary", "emptyEntryCreationLock", "Ljava/lang/Object;");
mv.visitInsn(MONITOREXIT);
mv.visitInsn(ATHROW);
// try-catch block metadata
mv.visitTryCatchBlock(catchStart, catchBegin, catchBegin, null);
}
super.visitLabel(label);
}
@Override
public void visitEnd() {
super.visitEnd();
}
}
private static class ClassInitializerVisitor extends MethodVisitor{
public ClassInitializerVisitor(int api, MethodVisitor mv) {
super(api, mv);
}
@Override
public void visitCode() {
super.visitCode();
logger.trace("Adding emptyEntryCreationLock initializer");
mv.visitTypeInsn(NEW, "java/lang/Object");
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
mv.visitFieldInsn(PUTSTATIC, "net/minecraftforge/oredict/OreDictionary","emptyEntryCreationLock", "Ljava/lang/Object;");
}
@Override
public void visitEnd() {
super.visitEnd();
}
}
public OreDictionaryVisitor(int api, ClassVisitor cv) {
super(api, cv);
}
@Override
public void visitEnd() {
logger.debug("Adding emptyEntryCreationLock");
cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "emptyEntryCreationLock", "Ljava/lang/Object;", null, null);
super.visitEnd();
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
if (name.equals("getOreID") && desc.equals("(Ljava/lang/String;)I")) {
logger.debug("Patching getOreID");
return new GetOreIDVisitor(api, super.visitMethod(access, name, desc, signature, exceptions));
} else if (name.equals("<clinit>")) {
// some classes don't have clinit. not this one.
logger.debug("Patching clinit");
return new ClassInitializerVisitor(api, super.visitMethod(access, name, desc, signature, exceptions));
}
return super.visitMethod(access, name, desc, signature, exceptions);
}
}
@@ -92,19 +92,23 @@ public class BrewingRecipeHandler extends TemplateRecipeHandler
public void loadCraftingRecipes(ItemStack result) {
if (result.getItem() != potionitem) return;
int damage = result.getItemDamage();
for (BrewingRecipe recipe : apotions)
if (recipe.result.item.getItemDamage() == damage)
arecipes.add(new CachedBrewingRecipe(recipe));
// Note: Not safe as written for parallelStream
apotions.stream()
.filter(recipe -> recipe.result.item.getItemDamage() == damage)
.map(CachedBrewingRecipe::new)
.collect(Collectors.toCollection(() -> arecipes));
}
@Override
public void loadUsageRecipes(ItemStack ingredient) {
if (ingredient.getItem() != potionitem && !ingredients.contains(ingredient)) return;
for (BrewingRecipe recipe : apotions)
if (NEIServerUtils.areStacksSameType(recipe.ingredient.item, ingredient) || NEIServerUtils.areStacksSameType(recipe.precursorPotion.item, ingredient))
arecipes.add(new CachedBrewingRecipe(recipe));
// Note: Not safe as written for parallelStream
apotions.stream()
.filter(recipe -> NEIServerUtils.areStacksSameType(recipe.ingredient.item, ingredient) || NEIServerUtils.areStacksSameType(recipe.precursorPotion.item, ingredient))
.map(CachedBrewingRecipe::new)
.collect(Collectors.toCollection(() -> arecipes));
}
@Override
@@ -228,7 +228,7 @@ public class DefaultOverlayHandler implements IOverlayHandler
for(ItemStack pstack : posstack.items)
{
for (DistributedIngred istack : ingredStacks) {
if (!canStack(pstack, istack.stack) || istack.invAmount - istack.distributed < pstack.stackSize)
if (!canStack(pstack, istack.stack) || istack.invAmount - istack.distributed < pstack.stackSize || istack.recipeAmount == 0 || istack.distributed == 0 || pstack.stackSize == 0)
continue;
int relsize = (istack.invAmount - istack.invAmount / istack.recipeAmount * istack.distributed) / pstack.stackSize;
@@ -9,6 +9,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import static codechicken.nei.NEIClientUtils.translate;
@@ -16,9 +17,9 @@ public class FuelRecipeHandler extends FurnaceRecipeHandler
{
public class CachedFuelRecipe extends CachedRecipe
{
public final FuelPair fuel;
public final TemplateFuelPair fuel;
public CachedFuelRecipe(FuelPair fuel) {
public CachedFuelRecipe(TemplateFuelPair fuel) {
this.fuel = fuel;
}
@@ -49,24 +50,32 @@ public class FuelRecipeHandler extends FurnaceRecipeHandler
return NEIClientUtils.translate("recipe.fuel");
}
@SuppressWarnings("unchecked")
private void loadAllSmelting() {
Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet())
mfurnace.add(new SmeltingPair(recipe.getKey(), recipe.getValue()));
// Note: Not safe as written for parallelStream
final Map<ItemStack, ItemStack> smeltingRecipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
smeltingRecipes.entrySet().stream()
.map(recipe -> new SmeltingPair(recipe.getKey(), recipe.getValue()))
.collect(Collectors.toCollection(() -> mfurnace));
}
@Override
public void loadCraftingRecipes(String outputId, Object... results) {
// Note: Not safe as written for parallelStream
if (outputId.equals("fuel") && getClass() == FuelRecipeHandler.class)
for (FuelPair fuel : afuels)
arecipes.add(new CachedFuelRecipe(fuel));
afuels.stream()
.map(CachedFuelRecipe::new)
.collect(Collectors.toCollection(() -> arecipes));
}
public void loadUsageRecipes(ItemStack ingredient) {
for (FuelPair fuel : afuels)
if (fuel.stack.contains(ingredient))
arecipes.add(new CachedFuelRecipe(fuel));
// Note: Not safe as written for parallelStream
afuels.stream()
.filter(fuel -> fuel != null && fuel.stack != null && fuel.stack.contains(ingredient))
.map(CachedFuelRecipe::new)
.collect(Collectors.toCollection(() -> arecipes));
}
public String getOverlayIdentifier() {
@@ -76,7 +85,7 @@ public class FuelRecipeHandler extends FurnaceRecipeHandler
@Override
public List<String> handleItemTooltip(GuiRecipe gui, ItemStack stack, List<String> currenttip, int recipe) {
CachedFuelRecipe crecipe = (CachedFuelRecipe) arecipes.get(recipe);
FuelPair fuel = crecipe.fuel;
TemplateFuelPair fuel = crecipe.fuel;
float burnTime = fuel.burnTime / 200F;
if (gui.isMouseOver(fuel.stack, recipe) && burnTime < 1) {
@@ -1,26 +1,18 @@
package codechicken.nei.recipe;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
import net.minecraft.block.Block;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiFurnace;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.tileentity.TileEntityFurnace;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class FurnaceRecipeHandler extends TemplateRecipeHandler
{
@@ -48,8 +40,8 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler
final PositionedStack result;
}
public static class FuelPair
{
@Deprecated
public static class FuelPair {
public FuelPair(ItemStack ingred, int burnTime) {
this.stack = new PositionedStack(ingred, 51, 42, false);
this.burnTime = burnTime;
@@ -59,8 +51,6 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler
public final int burnTime;
}
public static ArrayList<FuelPair> afuels;
public static HashSet<Block> efuels;
@Override
public void loadTransferRects() {
@@ -80,8 +70,9 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler
@Override
public TemplateRecipeHandler newInstance() {
if (afuels == null || afuels.isEmpty())
findFuels();
// Use the non parallel version since we might already be using the forkJoinPool and might have no threads available
// This will ideally have been pre-cached elsewhere and will be a NOOP
findFuelsOnce();
return super.newInstance();
}
@@ -133,27 +124,6 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler
drawProgressBar(74, 23, 176, 14, 24, 16, 48, 0);
}
private static Set<Item> excludedFuels() {
Set<Item> efuels = new HashSet<>();
efuels.add(Item.getItemFromBlock(Blocks.brown_mushroom));
efuels.add(Item.getItemFromBlock(Blocks.red_mushroom));
efuels.add(Item.getItemFromBlock(Blocks.standing_sign));
efuels.add(Item.getItemFromBlock(Blocks.wall_sign));
efuels.add(Item.getItemFromBlock(Blocks.wooden_door));
efuels.add(Item.getItemFromBlock(Blocks.trapped_chest));
return efuels;
}
private static void findFuels() {
afuels = new ArrayList<>();
Set<Item> efuels = excludedFuels();
for (ItemStack item : ItemList.items)
if (!efuels.contains(item.getItem())) {
int burnTime = TileEntityFurnace.getItemBurnTime(item);
if (burnTime > 0)
afuels.add(new FuelPair(item.copy(), burnTime));
}
}
@Override
public String getOverlayIdentifier() {
@@ -1,27 +1,40 @@
package codechicken.nei.recipe;
import codechicken.core.TaskProfiler;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.GuiScreen;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class GuiCraftingRecipe extends GuiRecipe
{
public static boolean openRecipeGui(String outputId, Object... results) {
Minecraft mc = NEIClientUtils.mc();
GuiContainer prevscreen = mc.currentScreen instanceof GuiContainer ? (GuiContainer) mc.currentScreen : null;
GuiScreen prevscreen = mc.currentScreen;// instanceof GuiContainer ? (GuiContainer) mc.currentScreen : null;
ArrayList<ICraftingHandler> handlers;
TaskProfiler profiler = ProfilerRecipeHandler.getProfiler();
ArrayList<ICraftingHandler> handlers = new ArrayList<>();
for (ICraftingHandler craftinghandler : craftinghandlers) {
profiler.start(craftinghandler.getRecipeName());
ICraftingHandler handler = craftinghandler.getRecipeHandler(outputId, results);
if (handler.numRecipes() > 0)
handlers.add(handler);
profiler.start("recipe.concurrent.crafting");
// Pre-find the fuels so we're not fighting over it
FuelRecipeHandler.findFuelsOnceParallel();
try {
handlers = ItemList.forkJoinPool.submit(() -> craftinghandlers.parallelStream()
.map(h -> h.getRecipeHandler(outputId, results))
.filter(h -> h.numRecipes() > 0)
.collect(Collectors.toCollection(ArrayList::new))).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return false;
} finally {
profiler.end();
}
profiler.end();
if (handlers.isEmpty())
return false;
@@ -29,7 +42,7 @@ public class GuiCraftingRecipe extends GuiRecipe
return true;
}
private GuiCraftingRecipe(GuiContainer prevgui, ArrayList<ICraftingHandler> handlers) {
private GuiCraftingRecipe(GuiScreen prevgui, ArrayList<ICraftingHandler> handlers) {
super(prevgui);
currenthandlers = handlers;
}
+6 -3
View File
@@ -15,6 +15,7 @@ import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.guihook.IGuiClientSide;
import codechicken.nei.guihook.IGuiHandleMouseWheel;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
@@ -34,18 +35,20 @@ public abstract class GuiRecipe extends GuiContainer implements IGuiContainerOve
public int recipetype;
public ContainerRecipe slotcontainer;
public GuiContainer firstGui;
public GuiContainer prevGui;
public GuiScreen prevGui;
public GuiButton nextpage;
public GuiButton prevpage;
public GuiButton overlay1;
public GuiButton overlay2;
protected GuiRecipe(GuiContainer prevgui) {
protected GuiRecipe(GuiScreen prevgui) {
super(new ContainerRecipe());
slotcontainer = (ContainerRecipe) inventorySlots;
this.prevGui = prevgui;
this.firstGui = prevgui;
if(prevgui instanceof GuiContainer)
this.firstGui = (GuiContainer)prevgui;
if (prevgui instanceof IGuiContainerOverlay)
this.firstGui = ((IGuiContainerOverlay) prevgui).getFirstScreen();
}
+20 -7
View File
@@ -1,11 +1,14 @@
package codechicken.nei.recipe;
import codechicken.core.TaskProfiler;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
public class GuiUsageRecipe extends GuiRecipe
{
@@ -13,15 +16,25 @@ public class GuiUsageRecipe extends GuiRecipe
Minecraft mc = NEIClientUtils.mc();
GuiContainer prevscreen = mc.currentScreen instanceof GuiContainer ? (GuiContainer) mc.currentScreen : null;
ArrayList<IUsageHandler> handlers;
TaskProfiler profiler = ProfilerRecipeHandler.getProfiler();
ArrayList<IUsageHandler> handlers = new ArrayList<>();
for (IUsageHandler usagehandler : usagehandlers) {
profiler.start(usagehandler.getRecipeName());
IUsageHandler handler = usagehandler.getUsageHandler(inputId, ingredients);
if (handler.numRecipes() > 0)
handlers.add(handler);
// Pre-find the fuels so we're not fighting over it
FuelRecipeHandler.findFuelsOnceParallel();
profiler.start("recipe.concurrent.usage");
try {
handlers = ItemList.forkJoinPool.submit(() -> usagehandlers.parallelStream()
.map(h -> h.getUsageHandler(inputId, ingredients))
.filter(h -> h.numRecipes() > 0)
.collect(Collectors.toCollection(ArrayList::new))).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return false;
} finally {
profiler.end();
}
profiler.end();
if (handlers.isEmpty())
return false;
@@ -35,9 +35,13 @@ public class RecipeItemInputHandler implements IContainerInputHandler
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button)
{
ItemStack stackover = GuiContainerManager.getStackMouseOver(gui);
if(stackover == null || !(gui instanceof GuiRecipe))
if(stackover == null)
return false;
if (!(gui instanceof GuiRecipe))
return false;
if(button == 0)
return GuiCraftingRecipe.openRecipeGui("item", stackover.copy());
@@ -154,7 +154,7 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler
Object[] items = recipe.getInput();
for (Object item : items)
if (item instanceof List && ((List<?>) item).isEmpty())//ore handler, no ores
if (item instanceof List && ((List<?>) item).isEmpty()) //ore handler, no ores
return null;
return new CachedShapedRecipe(width, height, items, recipe.getRecipeOutput());
@@ -49,7 +49,12 @@ public class ShapelessRecipeHandler extends ShapedRecipeHandler
public void setIngredients(List<?> items) {
ingredients.clear();
for (int ingred = 0; ingred < items.size(); ingred++) {
int itemsSize = items.size();
if (itemsSize > stackorder.length) {
NEIClientConfig.logger.error("RECIPE BUG: Too many items (" + itemsSize + ") for " + this.result.toString());
itemsSize = stackorder.length;
}
for (int ingred = 0; ingred < itemsSize; ingred++) {
PositionedStack stack = new PositionedStack(items.get(ingred), 25 + stackorder[ingred][0] * 18, 6 + stackorder[ingred][1] * 18);
stack.setMaxSize(1);
ingredients.add(stack);
@@ -1,5 +1,6 @@
package codechicken.nei.recipe;
import codechicken.nei.ItemList;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
@@ -11,11 +12,14 @@ import codechicken.nei.api.IStackPositioner;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerTooltipHandler;
import com.google.common.base.Stopwatch;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Container;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntityFurnace;
import org.lwjgl.opengl.GL11;
import java.awt.Point;
@@ -26,7 +30,12 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import static codechicken.lib.gui.GuiDraw.changeTexture;
import static codechicken.lib.gui.GuiDraw.drawTexturedModalRect;
@@ -41,6 +50,75 @@ import static codechicken.lib.gui.GuiDraw.getMousePosition;
*/
public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageHandler
{
protected static ReentrantLock lock = new ReentrantLock();
public static class TemplateFuelPair
{
public TemplateFuelPair(ItemStack ingred, int burnTime) {
this.stack = new PositionedStack(ingred, 51, 42, false);
this.burnTime = burnTime;
}
public final PositionedStack stack;
public final int burnTime;
}
public static List<TemplateFuelPair> afuels;
public static void findFuelsOnce() {
// Ensure we only find fuels once, even if threaded
lock.lock();
try {
if (afuels == null || afuels.isEmpty())
findFuels(false);
} finally {
lock.unlock();
}
}
public static void findFuelsOnceParallel() {
// Ensure we only find fuels once, even if threaded
lock.lock();
try {
if (afuels == null || afuels.isEmpty())
findFuels(true);
} finally {
lock.unlock();
}
}
private static Set<Item> efuels;
@SuppressWarnings("UnstableApiUsage")
private static void findFuels(boolean parallel) {
efuels = new HashSet<>();
efuels.add(Item.getItemFromBlock(Blocks.brown_mushroom));
efuels.add(Item.getItemFromBlock(Blocks.red_mushroom));
efuels.add(Item.getItemFromBlock(Blocks.standing_sign));
efuels.add(Item.getItemFromBlock(Blocks.wall_sign));
efuels.add(Item.getItemFromBlock(Blocks.wooden_door));
efuels.add(Item.getItemFromBlock(Blocks.trapped_chest));
Stopwatch stopwatch = Stopwatch.createStarted();
if (parallel) {
try {
afuels = ItemList.forkJoinPool.submit(() -> ItemList.items.parallelStream().map(TemplateRecipeHandler::identifyFuel).filter(Objects::nonNull).collect(Collectors.toList())).get();
} catch (InterruptedException | ExecutionException e) {
afuels = new ArrayList<>();
e.printStackTrace();
}
} else {
afuels = ItemList.items.stream().map(TemplateRecipeHandler::identifyFuel).filter(Objects::nonNull).collect(Collectors.toList());
}
NEIClientConfig.logger.info("FindFuels took " + stopwatch.stop() );
}
private static TemplateFuelPair identifyFuel(final ItemStack itemStack) {
if (efuels.contains(itemStack.getItem())) return null;
final int burnTime = TileEntityFurnace.getItemBurnTime(itemStack);
if (burnTime <= 0) return null;
return new TemplateFuelPair(itemStack.copy(), burnTime);
}
/**
* This Recipe Handler runs on this internal class
* Fill the recipe array with subclasses of this to make transforming the different types of recipes out there into a nice format for NEI a much easier job.
@@ -83,9 +161,13 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
*/
public List<PositionedStack> getOtherStacks() {
ArrayList<PositionedStack> stacks = new ArrayList<>();
PositionedStack stack = getOtherStack();
if (stack != null)
stacks.add(stack);
try {
PositionedStack stack = getOtherStack();
if (stack != null)
stacks.add(stack);
} catch (ArithmeticException e) {
NEIClientConfig.logger.error("Error in getOtherStacks: " + e);
}
return stacks;
}
@@ -306,7 +388,7 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
*/
public ArrayList<CachedRecipe> arecipes = new ArrayList<>();
/**
* A list of transferRects that apon when clicked or R is pressed will open a new recipe.
* A list of transferRects that when clicked or R is pressed will open a new recipe.
*/
public LinkedList<RecipeTransferRect> transferRects = new LinkedList<>();
@@ -459,6 +541,9 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
public TemplateRecipeHandler newInstance() {
try {
// Use the non parallel version since we might already be using the forkJoinPool and might have no threads available
// This will ideally have been pre-cached elsewhere and will be a NOOP
findFuelsOnce();
return getClass().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
+142
View File
@@ -0,0 +1,142 @@
package codechicken.nei.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagByte;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagFloat;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.nbt.NBTTagIntArray;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagLong;
import net.minecraft.nbt.NBTTagShort;
import net.minecraft.nbt.NBTTagString;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NBTJson {
private static final Pattern numberPattern = Pattern.compile("^([-+]?[\\d]+\\.?[0-9]*)([bBsSlLfFdD]?)$");
private static final JsonParser parser = new JsonParser();
private static final Gson gson = new GsonBuilder().create();
public static String toJson(NBTTagCompound tag) {
final String jsonString = toJsonObject(tag).toString();
return gson.toJson(parser.parse(jsonString));
}
@SuppressWarnings("unchecked")
public static JsonElement toJsonObject(NBTBase nbt) {
if (nbt instanceof NBTTagCompound) {
// NBTTagCompound
final NBTTagCompound nbtTagCompound = (NBTTagCompound) nbt;
final Map<String, NBTBase> tagMap = (Map<String, NBTBase>)nbtTagCompound.tagMap;
JsonObject root = new JsonObject();
for (Map.Entry<String, NBTBase> nbtEntry : tagMap.entrySet() ) {
root.add(nbtEntry.getKey(), toJsonObject(nbtEntry.getValue()));
}
return root;
} else if (nbt instanceof NBTBase.NBTPrimitive) {
// Number
return new JsonPrimitive(((NBTBase.NBTPrimitive) nbt).func_150286_g());
} else if (nbt instanceof NBTTagString) {
// String
return new JsonPrimitive(((NBTTagString) nbt).func_150285_a_());
} else if (nbt instanceof NBTTagList) {
// Tag List
JsonArray arr = new JsonArray();
((NBTTagList) nbt).tagList.forEach(c -> arr.add(toJsonObject((NBTBase) c)));
return arr;
} else if (nbt instanceof NBTTagIntArray) {
// Int Array
JsonArray arr = new JsonArray();
for(int i : ((NBTTagIntArray) nbt).func_150302_c()) {
arr.add(new JsonPrimitive(i));
}
return arr;
} else {
throw new IllegalArgumentException("Unsupported NBT Tag: " + NBTBase.NBTTypes[nbt.getId()] + " - " + nbt);
}
}
public static NBTBase toNbt(JsonElement jsonElement) {
if (jsonElement instanceof JsonPrimitive) {
// Number or String
final JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonElement;
final String jsonString = jsonPrimitive.getAsString();
final Matcher m = numberPattern.matcher(jsonString);
if(m.find()) {
// Number
final String numberString = m.group(1);
if (m.groupCount() == 2 && m.group(2).length() > 0) {
final char numberType = m.group(2).charAt(0);
switch(numberType) {
case 'b':
case 'B':
return new NBTTagByte(Byte.parseByte(numberString));
case 's':
case 'S':
return new NBTTagShort(Short.parseShort(numberString));
case 'l':
case 'L':
return new NBTTagLong(Long.parseLong(numberString));
case 'f':
case 'F':
return new NBTTagFloat(Float.parseFloat(numberString));
case 'd':
case 'D':
return new NBTTagDouble(Double.parseDouble(numberString));
}
} else {
if (numberString.contains("."))
return new NBTTagDouble(Double.parseDouble(numberString));
else
return new NBTTagInt(Integer.parseInt(numberString));
}
} else {
// String
return new NBTTagString(jsonString);
}
} else if (jsonElement instanceof JsonArray) {
// NBTTagIntArray or NBTTagList
final JsonArray jsonArray = (JsonArray) jsonElement;
final List<NBTBase> nbtList = new ArrayList<>();
for (JsonElement element : jsonArray) {
nbtList.add(toNbt(element));
}
if (nbtList.stream().allMatch(n -> n instanceof NBTTagInt)) {
return new NBTTagIntArray(nbtList.stream().mapToInt(i -> ((NBTTagInt)i).func_150287_d() ).toArray());
} else {
NBTTagList nbtTagList = new NBTTagList();
nbtList.forEach(nbtTagList::appendTag);
return nbtTagList;
}
} else if (jsonElement instanceof JsonObject) {
// NBTTagCompound
final JsonObject jsonObject = (JsonObject) jsonElement;
NBTTagCompound nbtTagCompound = new NBTTagCompound();
for (Map.Entry<String, JsonElement> jsonEntry : jsonObject.entrySet()) {
nbtTagCompound.setTag(jsonEntry.getKey(), toNbt(jsonEntry.getValue()));
}
return nbtTagCompound;
}
throw new IllegalArgumentException("Unhandled element " + jsonElement);
}
}