Compare commits

...
116 Commits
Author SHA1 Message Date
miozune bdb206b45d Fix world specific settings on MP being also specific to dimension (#414) 2023-08-18 21:42:20 +02:00
Raven Szewczyk aa44a97f80 Partial fix for the NEI custom diagram in recipe tooltip issue (#413) 2023-08-17 10:36:15 +02:00
Nico Spiske 00c4411ec5 Pull bookmarked items from container to player inventory (#410)
* [major] first potential version for basic chests

* [major] added api to register chest/inventory guis for bookmark item pulling

* [minor] added hotkey to pull all bookmarked items

* [major] finished

* [minor] spotless apply

* [minor] removed bak file

* [minor] function cleanup

* [minor] fixed bookmarks being set to 0

* [minor] little oversight

* [minor] private attribute and curly brackets
2023-08-07 15:29:05 +02:00
miozune 4f23d21d37 Fix recipe tooltip crash with BetterQuesting (#409)
* updateBuildScript

* Fix recipe tooltip crash with BetterQuesting
2023-07-28 13:20:45 +02:00
8569431e1d Recipe tooltip fixes (#402)
* Unconditionally override Minecraft.currentScreen when drawing tooltips

* Fix bad item lighting in recipe tooltips

* Update buildscript

* Fix NEI ignoring handler switching on click

Handlers might call Minecraft#displayGuiScreen and overwrite Minecraft.currentScreen, but the height hack would unconditionally undo this again.

* spotlessApply (#404)

Co-authored-by: GitHub GTNH Actions <>

* Attempt to fix CME when opening recipes immediately after load (#403)

* Rename the internal private class HeightHack->CompatibilityHacks to better reflect the new usage.

* Move trueGui assignment down.

* Fix overlay button y offsets

* Fix wrong recipe tooltip background rendering

* Apply spotless

---------

Co-authored-by: Wilhelm Schuster <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-07-23 08:04:31 +02:00
Wilhelm Schuster 5b9c27e253 Fix potential NPE when calling ItemMobSpawner#loadSpawners. (#405) 2023-07-16 14:29:31 +02:00
Raven Szewczyk d613d06471 Attempt to fix CME when opening recipes immediately after load (#403) 2023-07-16 09:00:35 +01:00
65ffbad491 Show a full recipe widget in item tooltips for bookmarked recipes (#398)
* Update buildscript

* Show a full recipe widget in item tooltips for bookmarked recipes

* Make recipe tooltips configurable and only show in the bookmarks panel

* Fix layout relative to tooltip boxes

* Fix wildcard import

* spotlessApply (#401)

Co-authored-by: GitHub GTNH Actions <>

* Fix handler tooltip offsets for new&legacy handlers

* Fix render order to draw crafting tooltips on top of container manager buttons

* Fix wrong mouse Y half-point calculation

* Allow saving recipes with empty item ingredient lists to bookmarks (e.g. fluid-only)

* Fix waila vs. non-waila tooltip offsets

Co-authored-by: Wilhelm Schuster <[email protected]>

---------

Co-authored-by: Wilhelm Schuster <[email protected]>
2023-07-10 17:38:07 +01:00
Wilhelm Schuster 885609720e Extend height hack for legacy recipe handlers (#395)
* Store heighthackhandlers.cfg as an internal asset instead of an array of strings

Is copied into the config directory upon first launch. Also, comments
are now allowed (only from the beginning of the file).

* Store serialhandlers.cfg as an internal asset instead of an array of strings

Is copied into the config directory upon first launch. Also, comments
are now allowed (only from the beginning of the file).

Removes GTNH-specific code to be replaced with a configuration file.

* Extend the height hack to also cover guiTop and getRecipePosition

Certain legacy recipe handlers hardcode even more of the NEI recipe
screen layout, requiring only the singular recipe handler switcher
widget at the top, whereas this improved NEI moves the recipe pager to
the top as well expecting recipe handler to move down another 16px. One
such mod that breaks is Immersive Engineering. To fix it we move the top
edge of the gui (guiTop) down by 16px so that the old gap calculation
works correctly. This required special handling in getRecipePosition()
and refreshSlots().

* Fix Immersive Engineering recipe handlers

* Fix Ex Nihilo recipe handlers

* Fix Thermal Expansion recipe handlers

These handlers expect only two recipes to be displayed at a time. This can only be fixed through asm AFAICT.
2023-07-08 23:23:19 +02:00
chochemandglowredman bacf246504 Adjust nei overlay to gt oregen changes (#391)
* adjust to oregen changes

* add compat for old worlds

* remove testing debug

* Update buildscript

* Adjust to changed oregenPattern API

* fix fieldname

---------

Co-authored-by: glowredman <[email protected]>
2023-07-04 18:36:35 +02:00
Wilhelm Schuster 1ab3350eb8 Adjust recipe handler scrolling again (#393)
* Update buildscript

* Rework recipe handler tab scrolling again

Move the recipe handler tab scrolling before the handler-specific
scrolling again. This ensures that tab scrolling while hovering over the
tab bar will always be possible, regardless of how a recipe handler
handles scrolling itself. This mostly reverts back to how this feature
was implemented originally with one change: the Shift-scrolling behavior
is moved outside the recipe tabs scroll handler after the recipe
handler-specific scroll handling to prevent this from overwriting any
other behavior.
2023-06-24 12:01:21 +02:00
Wilhelm Schuster f3aa12483d Expand the tooltips for the time manipulation action buttons (#392) 2023-06-15 23:19:57 +02:00
miozune d86c472790 Fix crash with IC2 setItemDamage (#387)
* Ducttape fix for crash with IC2 setItemDamage

* Use Items.feather
2023-06-01 07:20:24 +02:00
Wilhelm Schuster 4124151208 Prevent recipe handler tab scrolling from overwriting recipe handler-specific scrolling (#384)
* Rename variable in GuiRecipeTabs to avoid confusion

Based on feedback in a previous PR review.

* Make sure recipe handler-specific scrolling behavior takes precedence over recipe handler tab scrolling
2023-05-13 17:40:08 +02:00
miozune 68ad800620 Remove handlers for Et Futurum Requiem (#383)
* Update dependencies

* updateBuildScript

* Remove handlers for Et Futurum Requiem
2023-05-13 14:12:22 +02:00
Wilhelm Schuster 2c7207485d Ensure the NEI config is really only initialized once (#381)
bootNEI() is supposed to only be called once during the client's
lifetime. Turns out, if your pack has 800 mods, bootNEI() might be
called a second time before configLoaded is set to true at the end of
the plugin loading thread. This introduces a second variable that is
set at the end of the single threaded portion of bootNEI() so that it
truly can only be called once, but we can still retain the ability to
check if the plugin loading thread has finished.
2023-05-10 23:55:45 +02:00
Wilhelm Schuster e8094794c3 Allow scrolling through recipe handlers (#379)
In addition to scrolling through all recipes of a single handler, you
can now scroll through all the recipe handlers while hovering over the
handler tab bar (or anywhere in the recipe area while holding left
shift).
2023-05-09 21:57:27 +02:00
miozune ad86d8f9c5 Separate logic to get detailed string of fluid amount (#378)
* Separate logic to get detailed string of fluid amount

* updateBuildScript & spotlessApply

* probably better way
2023-05-07 20:10:18 +02:00
Wilhelm Schuster 30c87e9160 Make sure NEI plugins are loaded before processing keybindings (#375)
NEI plugins are initialized in a separate thread. If this takes too long,
the client tick handler might already be running checking the keybindings
in KeyManager while a plugin calls API.addKeyBind() which can lead to a
CME.

Reported in https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/13292
Thanks to @Denostrov for helping me track this down.
2023-05-05 21:01:50 +02:00
chill 5eeb001534 Readme: fix wording (#374) 2023-05-05 12:16:22 +02:00
MalTeeez 962754ee10 Create handlers for Fusion Crafting (DE-), Techguns and some missing NC recipes (#372)
* Add Fusion Crafting catalyst.csv

* Add Fusion Crafter handler.csv

* Add Techguns handlers & some missing NuclearCraft handlers

* Add Techguns catalysts & some missing NuclearCraft catalysts

* Fix typo

* Add heights to handlers and fix typo

* Small height increase

* Group NC catalysts

* Group NC handlers
2023-04-28 08:24:58 +02:00
Jason Mitchell 0e34840c21 More robust IMC handling (#371)
* Complain if IMC adds a handler/catalyst for a handlerID that doesn't exist.

* Look at the right maps this time

* Don't show matches, only misses
2023-04-16 21:22:09 +02:00
CaedisandMartin Robertz a12fadb10d Add option to have the search widget under item panel (#364)
* Add option to have the search widget under item panel

* update bs+sa

* Make heights consistent

---------

Co-authored-by: Martin Robertz <[email protected]>
2023-04-01 23:16:18 +02:00
Raven Szewczyk 9218e233aa Ignore nonstackables in max overlaid recipe count calculation (#365)
* Update buildscript

* Ignore nonstackables in max overlaid recipe count calculation
2023-03-30 21:47:33 +02:00
theOnly1iKnow 23e16abae6 Add handlers of Reikas mods plus fixes (#362)
* Added Handlers for some of Reikas mods aswell as:
 - a fix for the Industrialcraft Fluid/Solid Canning Machine
 - Tiling for all MFR machines with multiple recipes 
 - Added Cyanite Reporcessor from Big Reactors

* Bring metalformer in line with other IC2 machines
2023-03-20 08:30:15 -07:00
theOnly1iKnow b3cb4db9ca Added handlers for Factorization plus a missing MFR handler (#359)
* Added Handlers for Factorization
as well as a missing MFR Handler

* Added three more MFR handlers
2023-03-06 13:10:28 +01:00
Raven Szewczyk 45fea43a4b Fix MissingFileException in <https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/12791> (#360) 2023-03-05 14:11:45 +01:00
miozune 088d9c08a8 Prevent NPE with null value for keybind (#358) 2023-03-03 11:15:13 +01:00
miozune 98547c2bcf Prevent NPE with null overlayHandler (#357) 2023-03-03 11:14:56 +01:00
Raven Szewczyk 02fa633043 Fix mob spawn spots sometimes showing as gray (#355) 2023-03-01 13:39:08 +01:00
r1tsuu 9df6ab0232 MacOS Command key accessibility (#354)
* MacOS Command key accessibility

* MacOS Command key accessibility

* Fixed spotless violation build error

* Fixed RMENU key to RMETA as CTRL on MacOS
2023-02-28 15:53:59 +01:00
Raven Szewczyk 89cc203875 Light/chunk overlay fixes (#353)
* Update buildscript

* Fix mob/chunk overlay rendering at very far x/z coordinates

Closes <https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/12680>

* Use Tesselator for mob spawn overlay drawing for a minor performance boost

* Missed a couple of offsets in the other chunk overlay modes
2023-02-27 13:31:44 +01:00
asdflj 4b247d08a5 add more api (#352) 2023-02-15 11:55:16 +01:00
Midnight145 8ecc8f20d5 add legacy handlers for botania,neiplugins (#349)
* add missing handlers for Blightfall

* update gitignore

* remove trailing commas

* add fluid registry handler

* readd missing quotes
2023-02-13 16:41:32 +00:00
miozune 74b9f8339a Require shift by default for moving items with overlaying recipe (#351) 2023-02-13 07:26:28 +01:00
miozune e20756a196 Don't require holding shift to move items when overlaying recipe (#348)
* updateBuildScript

* Remove redundant public modifier

* Don't require holding shift to move items when overlaying recipe
2023-02-09 11:21:30 +01:00
miozune 6d0f83c499 Make recipe query load all the uncrashed handlers instead of all-or-nothing if one of the handlers crashed (#347)
* Make recipe query load all the uncrashed handlers instead of all-or-nothing if one of the handlers crashed

* better error handling
2023-02-08 08:54:43 +01:00
miozune 8e219c06be Add JEI styled cycle ingredients (#346) 2023-02-05 16:57:09 +01:00
miozune 3fc576b6fc Add more error message for crash with recipe lookup (#345) 2023-02-05 11:27:52 +01:00
miozune 249cb2b308 Allow using hash for tooltip pagination keybind (#344) 2023-02-04 10:35:36 +01:00
miozune e8d8c1994b Add tooltip pagination (#343) 2023-02-03 15:35:03 +01:00
Raven Szewczyk 195b47944f There is no more 1.7.10- in the gha urls (#342) 2023-01-31 19:21:17 +01:00
Raven Szewczyk 3224fdef7d [ci skip] upgraded build system 2023-01-31 09:54:53 +00:00
Raven Szewczyk 46a159d788 Update buildscript, dependencies and modid injection shenanigans 2023-01-30 11:53:56 +00:00
İlker ARICI bd20e00a6e Add Actually Additions Catalysts.csv (#340)
* Actually Additions Catalysts.csv

* Update catalysts.csv

* Update catalysts.csv
2023-01-29 15:56:08 +01:00
İlker ARICI bf06b09d5a Add Actually Additions handlers (#339)
* Update handlers.csv

I have no experience in coding and not sure if this works, but here is my try at adding Actually Additions handlers to NEI

* Update handlers.csv

* Update handlers.csv

* Update handlers.csv

* Update handlers.csv
2023-01-29 15:55:59 +01:00
Jason Mitchell 1b1dd3567a [ci skip] Add git-blame-ignore-revs for spotlessApply 2023-01-28 17:55:51 -08:00
Jason Mitchell f106b5e766 [ci skip] spotlessApply with the new settings 2023-01-28 17:55:51 -08:00
Jason Mitchell f1dea5460a [ci skip] Update buildscript to RetroFuturaGradle 2023-01-28 17:55:49 -08:00
miozune 9b73b94d16 Fix meta id for MAX Bio Lab (#338) 2023-01-28 17:24:57 +01:00
Raven Szewczyk e133afc774 Fix jar resource loading on newer Java versions (still works on 8) (#337) 2023-01-25 20:50:48 +01:00
asdflj 75ff631f16 bookmark item stack size readable conversion (#335) 2023-01-23 10:59:29 +01:00
Raven Szewczyk 6f5d45c4ea Update CodeChicken dependencies (#330) 2023-01-05 12:18:21 +00:00
miozune fb51475bb9 Fix stack size of permutations on PositionedStack (#327) 2022-12-26 19:14:45 +01:00
Jason Mitchell 99ec3a4204 Add cf & modrinth deps (#325)
* Add cf & modrinth deps

* rm jitpack

* Spotless, you are annoying sometimes
2022-12-22 20:58:39 +01:00
miozune 8c4d609e4c Expose some members in GuiContainerManager (#324) 2022-12-21 10:37:43 +01:00
miozune 336c7dc621 Fix inventory desync when closing GuiRecipe (#320) 2022-11-29 18:21:45 +01:00
Yang Xizhi 2130a47f6f fix overlap of ? button (#321) 2022-11-29 11:19:42 +01:00
miozune 73b492b0e3 Add Dangote Distillus to catalyst for distillery (#319) 2022-11-18 07:33:16 +01:00
miozune efa69f31b6 Fix incorrect RecipeCatalysts for naquadah generators (#318) 2022-11-08 07:38:28 +01:00
makamys 95b437e5c9 Only mark item list as dirty if it's actually modified (#316)
Fixes #315
2022-10-23 11:53:29 +02:00
miozune afe3c54c29 Add config to not optimize computation for GUI overlap (#314) 2022-10-17 20:59:14 +02:00
Jason MitchellandGitHub GTNH Actions 2cab09e91b Try/Catch AIOBE - maybe fixes #295 (#312)
* Try/Catch AIOBE - maybe fixes #295

* spotlessApply

Co-authored-by: GitHub GTNH Actions <unknown>
2022-10-17 11:34:06 +02:00
Jason Mitchell 4b4ab434c0 Update buildscript and add CF/Modrinth project IDs 2022-10-15 08:20:59 -07:00
Yang Xizhi 9d108b21f9 fix missing yShift (#309) 2022-10-15 15:40:52 +02:00
slprimeandslprime 2302dac5c0 Bookmarks: save result that has output bigger than 64 (#308)
Co-authored-by: slprime <[email protected]>
2022-10-13 20:49:43 +02:00
slprimeandslprime 7c2fb2df5f fix bookmarks (#307)
Co-authored-by: slprime <[email protected]>
2022-10-13 10:06:08 +02:00
miozune 14aa3728ca Add AE2 Stuff Inscriber to RecipeCatalyst (#306) 2022-10-13 08:50:04 +02:00
Kiwi 66fc2270dd Update zh_CN.lang (#301) 2022-09-24 12:25:39 +02:00
miozune 138d25dbfd Fix incorrect color applied to GuiRecipeCatalyst (#300) 2022-09-19 05:58:46 +02:00
Raven Szewczyk d9191750a7 Update CodeChickenLib (#299) 2022-09-18 23:15:42 +02:00
くぁーりぃ 6d9ec0c0da Backport some of REI bookmark features (#296)
* add placeholder bookmark drop

* add item panel to bookmark panel injection support

* fix outofboundsexception

* fix drag'n drop voids bookmark

* add itemstack moving animation

* implement pop animation

* fix crashes

* disable ItemPanel Animation

* disable pop animation on bookmark load

* spotlessapply

* disable move animation on gui scale

* add config option
2022-09-18 12:08:16 +02:00
くぁーりぃ 617ac0600d Add search history (#294)
* add search history

* spotlessApply

* linkedlist->arraylist
2022-09-10 18:35:48 +02:00
7d7e3b61a6 Fix other mods cannot mixin GuiContainer.java when NEI is loaded (#291)
Co-authored-by: くぁーりぃ <[email protected]>
Co-authored-by: GitHub GTNH Actions <>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-09-05 18:47:51 +08:00
miozune 748695158f Allow using handlerId for handler order (#290) 2022-09-03 10:25:40 +02:00
DrParadox7 a2c037e0c0 Update Handlers (#288)
Updated Handlers and Catalyst for the following:
-Minefactory Reloaded
-GregTech 4
-Nuclearcraft
2022-08-31 17:30:14 +02:00
miozune e93d23e444 Show message while loading itempanel (#286)
* Show message while loading itempanel

* Move to ItemsGrid

* Add bookmark message

* ItemList

* Revert "Add bookmark message"

This reverts commit 030b5ed1ef.

* Item List

* Use Label

* clean
2022-08-31 10:43:22 +02:00
miozune 748cfe3754 Fix crash when itempanel is not initialized yet (#285) 2022-08-28 14:23:11 +02:00
firenoo b64d104d7e README.md: Add some documentation for getting started on development (#283) 2022-08-27 17:19:09 +02:00
miozune 46d90b6923 Show handler order when hovering on tab and shift pressed (#281) 2022-08-26 22:14:08 +02:00
slprime e61120099a Fix DnD Real Item as Ghost (#279) 2022-08-23 21:15:37 +02:00
Yang Xizhi bcb6eb214f fix dead loop when click certain gui with real item (#278)
fix https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/11067
2022-08-23 06:41:34 +01:00
slprimeandVladislav Laetansky 9221434b2e Create ShortcutInputHandler api class (#277)
* Add RecipeItemInputHandler#lastKeyTyped(ItemStack)

* move shortcut to api

* Update src/main/java/codechicken/nei/api/ShortcutInputHandler.java

Co-authored-by: Vladislav Laetansky <[email protected]>

Co-authored-by: Vladislav Laetansky <[email protected]>
2022-08-21 16:33:52 +02:00
slprime 02937061d4 Presets: Open List Fatal & Slot Overlay (#276)
* Presets: Open List Fatal

* fix slot overlay
2022-08-21 11:34:56 +02:00
miozuneGitHub GTNH Actionsgithub-actions[bot]
0e6425295b Catch exception on drawSlotItem (#273)
* Catch exception on drawSlotItem

* updateBuildScript

* updateBuildScript

* spotlessApply

* spotlessApply (#274)

Co-authored-by: miozune <[email protected]>
Co-authored-by: GitHub GTNH Actions <>

* spotlessApply (#275)

Co-authored-by: miozune <[email protected]>
Co-authored-by: GitHub GTNH Actions <>

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-08-20 11:41:22 +02:00
slprime fb9d517f78 Added keyboard shortcuts to NEI And More... (#271)
* Added keyboard shortcuts to NEI

* OptionButton: Add Tooltip to long prefix

* fix formatting

* Tooltip shown when shift is held
2022-08-19 14:03:42 +02:00
miozune 529f4374d6 Add catalysts for large boiler fuel (#270) 2022-08-10 01:43:05 +02:00
miozune 0bf369a996 Purge OpV (#269) 2022-08-03 11:32:22 +07:00
Jason Mitchell 1897dba35a [ci skip] Migrate github actions to GTNH-Actions-Workflows 2022-07-16 10:50:05 -07:00
YannickMG 5bbf275980 Focus the previous recipe if it's still visible when loading usage re… (#263)
* Focus the previous recipe if it's still visible when loading usage recipes.

* Reduced code duplication by extracting getRecipeHandlers

* Moved RecipeHandlerQuery to its own package-private file

* Refactored RecipeHandlerQuery methods

* Saving the current recipe when left clicking a machine's "Recipes" button

* Restored prevScreen so we can restore it with overlay

* Genericized GuiRecipe so that currentHandlers is no longer hidden in subclasses

* Cleaned up overlay handling

* Fixed trivial IDE warnings & bad JavaDoc on files I touched
2022-06-29 20:18:48 +02:00
Raven Szewczyk f7a900e910 Update buildscript & apply automatic formatting rules 2022-06-27 10:23:18 -07:00
slprime a7683b885d Add another bookmark view mode (#261)
* add another bookmark view mode

* enum BookmarkViewMode
2022-06-23 00:03:29 +02:00
glowredman fe4566901a Update handlers and catalysts (#259)
New:
- Ex Astris
- Ex Compressum
- RFTools
- Steves Carts
- Thaumcraft NEI Plugin
- TC NEI Additions
- Bibliocraft
- ComputerCraft

Updated:
- Thermal Expansion
- Project Red
2022-06-08 16:12:47 +02:00
embeddedt de2b2ece69 Fix minor memory leaks (#258)
* Fix memory leak caused by mob spawner items

* Use a weak hash map instead of manually clearing the map

* Clear manager reference to prevent holding a WorldClient reference through the GUI

* Revert "Use a weak hash map instead of manually clearing the map"

This reverts commit 91bb997250.
2022-06-06 17:05:02 +02:00
Kiwiand[Kiwi233] d20a80a77c Update zh_CN.lang (#257)
* Update zh_CN.lang

* Update zh_CN.lang

* Update zh_CN.lang

* Update zh_CN.lang

* Update zh_CN.lang

* Update zh_CN.lang

Co-authored-by: [Kiwi233] <[[email protected]]>
2022-06-04 22:57:15 +02:00
Jerome226 6cced8dea0 Added compat for TFC+, IE and other mods 2022-05-31 21:16:48 -07:00
miozune 68b9453328 Add config to ignore overlap with potion effect HUD (#255) 2022-05-31 16:38:14 +02:00
embeddedt ae21012ea2 Use a proper key implementation for the search cache (#254)
* Use a proper key implementation for the search cache
* Synchronize itemSearchNames accesses to prevent CMEs
* Use a ConcurrentHashMap instead of synchronizing
  This allows multiple threads to read at the same time, which is the more common scenario.
2022-05-29 12:25:39 -07:00
miozune 2b31129ef9 Use OverlayIdentifier for GT4 2022-05-29 11:32:49 -07:00
Raven Szewczyk ba77a63545 Make sure to use utf-8 for bookmark reading as well as writing (#253) 2022-05-27 19:38:54 +02:00
embeddedt 8f7d698e7d Add option to cache item grid rendering (#250)
* Add option to cache item grid rendering

* Fix highlighting for bookmarks

* Tweak GL state slightly

* Fix focus box being in the wrong place

* Fix flickering for one frame when searching

* Prevent potion effects from rendering over NEI slots

Fixes #231

* Invalidate the buffer if `invalidSlotMap` changes

* Clean up imports

* Delay blitting until after the buffer is refreshed

but still avoid waiting for the next frame

* Refactor slot focus logic to handle highlighting multiple slots

* Refresh grid when sorting bookmarks

* Minor code cleanup, fix some more hovering issues

* Remove `slotNeedsOutline`, it is now redundant

* Remove focus parameter from drawItem
2022-05-27 13:42:41 +02:00
glowredman 72d44fd711 Fix AppleCore's reflection
AppleCore accesses `getStackMouseOver` via reflection but it has been moved to the `PanelWidget` class -> the reflection fails
2022-05-16 10:40:12 -07:00
MuXiu1997 d735cc2a38 Use shortcut key to trigger overlay recipe (#248)
* Use shortcut key to trigger overlay recipe

* Add a way to remove overlay renderer

* Change of implementation

* Fix crash
2022-05-16 17:57:00 +02:00
slprimeandSerghei Borovetchi 91e9b2a5ae Panel settings (#240)
* panel settings

* Highlight hidden items; mark item with recipe

* open gui usage with recipeId

* small  changes

* restore gl after draw item

Co-authored-by: Serghei Borovetchi <[email protected]>
2022-05-06 21:41:45 +02:00
miozune 96e4fe55e8 Send chat to player when recipe loading was errored (#241) 2022-05-03 20:42:09 +02:00
miozune 8717df0cbb Fix scrolling recipes when hovering over ingredients changes stack size (#237) 2022-04-28 15:46:01 +02:00
miozune d6a6551561 Allow GuiRecipe to back to general GuiScreen (#236) 2022-04-25 15:31:50 +02:00
Jason Mitchell 995ed24056 Fix catalysts for gt6 2022-04-20 08:19:47 -07:00
Kiwiand[Kiwi233] 2917f2a4c9 Update zh_CN.lang (#235)
* Update zh_CN.lang

* Update zh_CN.lang

* Update zh_CN.lang

* Update zh_CN.lang

* Update zh_CN.lang

Co-authored-by: [Kiwi233] <[[email protected]]>
2022-04-14 20:04:31 +02:00
NoXъ 5b2ff42d4f typo correction, russification (#234) 2022-04-09 18:11:15 +02:00
miozune 6f2782b06e Add way to register catalysts via IMC (#232) 2022-04-08 21:15:24 +02:00
Glease f17bf6e8e2 fix weird cme (#230) 2022-03-12 15:03:44 +01:00
Glease 10ee4d17ef super unlikely NPE fix (#229) 2022-03-12 12:22:17 +01:00
miozune f6acd768f3 Fix not being able to scroll recipes when hovering over ingredients (#228) 2022-03-05 11:05:26 +01:00
miozune 8a5146b672 Workaround for issue where GT++ registers Chemical Plant handler twice 2022-03-03 08:23:55 -08:00
miozune 1632a90d15 Add support for Natura and Campfire Backport (#226) 2022-03-01 11:28:25 +01:00
202 changed files with 11779 additions and 7755 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Ignore spotlessApply reformat
f106b5e7665df6341ae8539f74dc391a7efc98b1
+44
View File
@@ -0,0 +1,44 @@
* text eol=lf
*.[jJ][aA][rR] binary
*.[pP][nN][gG] binary
*.[jJ][pP][gG] binary
*.[jJ][pP][eE][gG] binary
*.[gG][iI][fF] binary
*.[tT][iI][fF] binary
*.[tT][iI][fF][fF] binary
*.[iI][cC][oO] binary
*.[sS][vV][gG] text
*.[eE][pP][sS] binary
*.[xX][cC][fF] binary
*.[kK][aA][rR] binary
*.[mM]4[aA] binary
*.[mM][iI][dD] binary
*.[mM][iI][dD][iI] binary
*.[mM][pP]3 binary
*.[oO][gG][gG] binary
*.[rR][aA] binary
*.7[zZ] binary
*.[gG][zZ] binary
*.[tT][aA][rR] binary
*.[tT][gG][zZ] binary
*.[zZ][iI][pP] binary
*.[tT][cC][nN] binary
*.[sS][oO] binary
*.[dD][lL][lL] binary
*.[dD][yY][lL][iI][bB] binary
*.[pP][sS][dD] binary
*.[tT][tT][fF] binary
*.[oO][tT][fF] binary
*.[pP][aA][tT][cC][hH] -text
*.[bB][aA][tT] text eol=crlf
*.[cC][mM][dD] text eol=crlf
*.[pP][sS]1 text eol=crlf
*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary
-9
View File
@@ -1,9 +0,0 @@
directory="run/crash-reports"
if [ -d $directory ]; then
echo "Crash reports detected:"
cat $directory/*
exit 1
else
echo "No crash reports detected"
exit 0
fi
+2 -34
View File
@@ -1,5 +1,3 @@
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Build and test
@@ -11,35 +9,5 @@ on:
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Setup the workspace
run: ./gradlew setupCIWorkspace
- name: Build the mod
run: ./gradlew build
- name: Run server for 1 minute
run: |
mkdir run
echo "eula=true" > run/eula.txt
timeout 10 ./gradlew runServer || true
- name: Test no crashes happend
run: |
chmod +x .github/scripts/test-no-crash-reports.sh
.github/scripts/test-no-crash-reports.sh
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/build-and-test.yml@master
secrets: inherit
+7 -44
View File
@@ -1,51 +1,14 @@
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Release tagged build
on:
push:
tags:
- '*'
tags: [ '*' ]
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set release version
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Set up JDK 8
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: gradle
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Setup the workspace
run: ./gradlew setupCIWorkspace
- name: Build the mod
run: ./gradlew build
- name: Release under current tag
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "${{ env.RELEASE_VERSION }}"
prerelease: false
title: "${{ env.RELEASE_VERSION }}"
files: build/libs/*.jar
- name: Publish to Maven
run: ./gradlew publish
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
release-tags:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/release-tags.yml@master
secrets: inherit
+9 -1
View File
@@ -1,6 +1,7 @@
.gradle
.settings
/.idea/
/.vscode/
/run/
/build/
/eclipse/
@@ -25,5 +26,12 @@ whitelist.json
*.iml
*.ipr
*.iws
src/main/resources/mixins.*.json
src/main/resources/mixins.*([!.]).json
*.bat
*.DS_Store
!gradlew.bat
.factorypath
addon.local.gradle
addon.local.gradle.kts
addon.late.local.gradle
addon.late.local.gradle.kts
+5 -5
View File
@@ -8,18 +8,18 @@ If you have issues with NEI outside of the GTNH modpack you may report them in t
## New Features:
* Speed
* Speed
- Uses a parallel stream to search the item list over multiple cores, resulting in 2-6x faster searches on average
- Loads the recipe handlers in parallel
- Loads the recipe handlers in parallel
* 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.
* Bookmarks! Are you in the process of crafting? Bookmark it using either 'A' or configure your own key.
* Toggle bookmark pane. Default shortcut key `B`. Item Subsets menu is only available if bookmarks are not visible.
* Utility/Cheat buttons line up and wrap based on GUI size
* ItemList is no longer regenerated from the ItemRegistry on every inventory load
* JEI (Or Creative) Style tabs [Optional] Note: Requires explicit support to be added for an ItemStack to render, otherwise falls back to the first two letters of the handler name.
* JEI (Or Creative) Style tabs [Optional] Note: Requires explicit support to be added for an ItemStack to render, otherwise falls back to the first two letters of the handler name.
* Tabs/Handlers are loaded from a CSV config in the JAR (or optionally from the config folder). NBT IMCEvents `registerHandlerInfo` and `removeHandlerInfo` are available for mod authors to add handler information, using the same fields as the CSV file
* `@[Mod]->[item]` searching. ex: `@Mod.gregtech->iron ingot`
* Cycle between Recipe, Utility, and Cheat mode by ctrl clicking on the Wrench Icon
* Cycle between Recipe, Utility, and Cheat mode by ctrl clicking on the Wrench Icon
* GT5u Tools/Items and GT6 tools should now properly work with the Overlay Recipe Transfer
## Other items of note:
+3
View File
@@ -0,0 +1,3 @@
compileJava {
options.encoding = "UTF-8"
}
+1277 -415
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -1,7 +1,7 @@
// Add your dependencies here
dependencies {
compile('com.github.GTNewHorizons:CodeChickenLib:1.1.5.3:dev')
compile('com.github.GTNewHorizons:CodeChickenCore:1.1.3:dev')
shadowImplementation('org.apache.commons:commons-csv:1.8')
api('com.github.GTNewHorizons:CodeChickenLib:1.1.8:dev')
api('com.github.GTNewHorizons:CodeChickenCore:1.1.11:dev')
shadowImplementation('org.apache.commons:commons-csv:1.10.0')
}
+43 -5
View File
@@ -26,11 +26,19 @@ developmentEnvironmentUserName = Developer
# The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's
# version in @Mod([...], version = VERSION, [...])
# Leave these properties empty to skip individual token replacements
replaceGradleTokenInFile = NEIModContainer.java
gradleTokenModId = GRADLETOKEN_MODID
gradleTokenModName = GRADLETOKEN_MODNAME
gradleTokenVersion = GRADLETOKEN_VERSION
gradleTokenGroupName =
# Generate a class with String fields for the mod id, name, version and group name named with the fields below
generateGradleTokenClass = codechicken.nei.Tags
gradleTokenModId = MODID
gradleTokenModName = MODNAME
gradleTokenVersion = VERSION
gradleTokenGroupName = GROUPNAME
# [DEPRECATED]
# Multiple source files can be defined here by providing a comma-seperated list: Class1.java,Class2.java,Class3.java
# public static final String VERSION = "GRADLETOKEN_VERSION";
# The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's
# version in @Mod([...], version = VERSION, [...])
# Leave these properties empty to skip individual token replacements
replaceGradleTokenInFile =
# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise, you can
# leave this property empty.
@@ -58,3 +66,33 @@ containsMixinsAndOrCoreModOnly = true
# If enabled, you may use 'shadowImplementation' for dependencies. They will be integrated in your jar. It is your
# responsibility check the licence and request permission for distribution, if required.
usesShadowedDependencies = true
# Publishing to CurseForge requires you to set the CURSEFORGE_TOKEN environment variable to one of your CurseForge API tokens.
# The project's numeric ID on CurseForge. You can find this in the About Project box.
# Leave this empty if you don't want to publish on CurseForge.
curseForgeProjectId = 358228
# The project's relations on CurseForge. You can use this to refer to other projects on CurseForge.
# Syntax: type1:name1;type2:name2;...
# Where type can be one of [requiredDependency, embeddedLibrary, optionalDependency, tool, incompatible],
# and the name is the CurseForge project id of the other mod.
curseForgeRelations = requiredDependency:codechickencore-unofficial;requiredDependency:codechickenlib-unofficial
# Publishing to modrinth requires you to set the MODRINTH_TOKEN environment variable to your current modrinth API token.
# The project's ID on Modrinth. Can be either the slug or the ID.
# Leave this empty if you don't want to publish on Modrinth.
modrinthProjectId = notenoughitems-unofficial
# The project's relations on Modrinth. You can use this to refer to other projects on Modrinth.
# Syntax: scope1-type1:name1;scope2-type2:name2;...
# Where scope can be one of [required, optional, incompatible, embedded],
# type can be one of [project, version],
# and the name is the Modrinth project or version slug/id of the other mod.
modrinthRelations = required-project:codechickenlib-unofficial;required-project:codechickencore-unofficial
Binary file not shown.
+2 -1
View File
@@ -1,5 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+173 -116
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright 2015 the original author or authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,78 +17,110 @@
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -97,7 +129,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
@@ -105,84 +137,109 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+15 -23
View File
@@ -14,7 +14,7 @@
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -25,10 +25,14 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@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="-Xmx64m" "-Xms64m"
@@ -37,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -51,7 +55,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@@ -61,38 +65,26 @@ 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%
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 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
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
-14
View File
@@ -1,18 +1,4 @@
// Add any additional repositiroes for your dependencies here
repositories {
mavenCentral()
maven {
name 'GTNH Maven'
url 'http://jenkins.usrv.eu:8081/nexus/content/groups/public/'
}
maven {
url 'https://cursemaven.com'
content {
includeGroup 'curse.maven'
}
}
maven {
url 'https://jitpack.io'
}
}
+31
View File
@@ -0,0 +1,31 @@
pluginManagement {
repositories {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/"
allowInsecureProtocol = true
mavenContent {
includeGroup("com.gtnewhorizons.retrofuturagradle")
}
}
gradlePluginPortal()
mavenCentral()
mavenLocal()
}
}
plugins {
id 'com.diffplug.blowdryerSetup' version '1.6.0'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' // Provides java toolchains
}
blowdryerSetup {
repoSubfolder 'gtnhShared'
github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.0')
//devLocal '.' // Use this when testing config updates locally
}
rootProject.name = "NotEnoughItems"
@@ -0,0 +1,31 @@
package codechicken.nei;
import java.util.HashMap;
import net.minecraft.client.gui.inventory.GuiChest;
import net.minecraft.client.gui.inventory.GuiContainer;
import codechicken.nei.api.API;
import codechicken.nei.api.IBookmarkContainerHandler;
public class BookmarkContainerInfo {
private static final HashMap<Class<? extends GuiContainer>, IBookmarkContainerHandler> handlerMap = new HashMap<>();
public static void registerBookmarkContainerHandler(Class<? extends GuiContainer> classz,
IBookmarkContainerHandler handler) {
handlerMap.put(classz, handler);
}
public static boolean hasBookmarkContainerHandler(Class<? extends GuiContainer> classz) {
return handlerMap.containsKey(classz);
}
public static IBookmarkContainerHandler getBookmarkContainerHandler(GuiContainer gui) {
return handlerMap.get(gui.getClass());
}
public static void load() {
API.registerBookmarkContainerHandler(GuiChest.class, new DefaultBookmarkContainerHandler());
}
}
File diff suppressed because it is too large. Load diff
+12 -19
View File
@@ -1,11 +1,11 @@
package codechicken.nei;
import java.util.List;
import static codechicken.lib.gui.GuiDraw.getStringWidth;
public abstract class Button extends Widget
{
import java.util.List;
public abstract class Button extends Widget {
public Button(String s) {
label = s;
}
@@ -25,9 +25,7 @@ public abstract class Button extends Widget
@Override
public boolean handleClick(int mx, int my, int button) {
if (button == 1 || button == 0)
if (onButtonPress(button == 1))
NEIClientUtils.playClickSound();
if (button == 1 || button == 0) if (onButtonPress(button == 1)) NEIClientUtils.playClickSound();
return true;
}
@@ -39,23 +37,21 @@ public abstract class Button extends Widget
@Override
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
if (!contains(mx, my))
return tooltip;
if (!contains(mx, my)) return tooltip;
final String tip = getButtonTip();
if (tip != null)
tooltip.add(tip);
if (tip != null) tooltip.add(tip);
addTooltips(tooltip);
return tooltip;
}
public String getButtonTip() {
return null;
}
public void addTooltips(List<String> tooltip) {}
public void addTooltips(List<String> tooltip) {}
public String getRenderLabel() {
return label;
@@ -65,10 +61,7 @@ public abstract class Button extends Widget
public Image icon;
/**
* 0x4 = state flag, as opposed to 1 click
* 0 = normal
* 1 = on
* 2 = disabled
* 0x4 = state flag, as opposed to 1 click 0 = normal 1 = on 2 = disabled
*/
public int state;
}
@@ -1,20 +1,21 @@
package codechicken.nei;
public abstract class ButtonCycled extends Button
{
public abstract class ButtonCycled extends Button {
public ButtonCycled() {}
public ButtonCycled(int num) {
icons = new Image[num];
init();
}
@Override
public Image getRenderIcon()
{
public Image getRenderIcon() {
return icons[index];
}
public void init() {}
public int index;
public Image[] icons;
}
@@ -1,20 +1,20 @@
package codechicken.nei;
import codechicken.core.ClientUtils;
import codechicken.core.GuiModListScroll;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.api.API;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.StackInfo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import cpw.mods.fml.client.CustomModLoadingErrorDisplayException;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.FontRenderer;
@@ -28,53 +28,35 @@ import net.minecraft.entity.item.EntityItem;
import net.minecraft.world.World;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import codechicken.core.ClientUtils;
import codechicken.core.GuiModListScroll;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.api.API;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.StackInfo;
import cpw.mods.fml.client.CustomModLoadingErrorDisplayException;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
public class ClientHandler {
public class ClientHandler
{
private static String[] defaultSerialHandlers = {
"WayofTime.alchemicalWizardry.client.nei.NEIAlchemyRecipeHandler"
};
private static String[] defaultHeightHackHandlerRegex = {
"buildcraft.compat.nei.*",
"cofh.thermalexpansion.plugins.nei.handlers.*",
"crazypants.enderio.nei.*",
"forestry.factory.recipes.nei.*",
"ic2.neiIntegration.core.recipehandler.*",
"mariculture.plugins.nei.*",
"redgear.brewcraft.plugins.nei.*",
"tconstruct.plugins.nei.*",
"WayofTime.alchemicalWizardry.client.nei.*",
};
private static String[] defaultHandlerOrdering = {
"# Each line in this file should either be a comment (starts with '#') or an ordering.",
"# Ordering lines are <handler ID>,<ordering number>.",
"# Handlers will be sorted in order of number ascending, so smaller numbers first.",
"# Any handlers that are missing from this file will be assigned to 0.",
"# Negative numbers are fine.",
"# If you delete this file, it will be regenerated with all registered handler IDs.",
};
"# Any handlers that are missing from this file will be assigned to 0.", "# Negative numbers are fine.",
"# If you delete this file, it will be regenerated with all registered handler IDs.", };
private static ClientHandler instance;
private ArrayList<EntityItem> SMPmagneticItems = new ArrayList<>();
@@ -104,9 +86,11 @@ public class ClientHandler
if (world.isRemote) {
items = SMPmagneticItems;
} else {
items = world.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.expand(distancexz, distancey, distancexz));
items = world.getEntitiesWithinAABB(
EntityItem.class,
player.boundingBox.expand(distancexz, distancey, distancexz));
}
for (Iterator<EntityItem> iterator = items.iterator(); iterator.hasNext(); ) {
for (Iterator<EntityItem> iterator = items.iterator(); iterator.hasNext();) {
EntityItem item = iterator.next();
if (item.delayBeforeCanPickup > 0) continue;
@@ -164,21 +148,25 @@ public class ClientHandler
ItemInfo.preInit();
StackInfo.loadGuidFilters();
}
public static void loadSerialHandlers() {
File file = NEIClientConfig.serialHandlersFile;
if(!file.exists()) {
try(FileWriter writer = new FileWriter(file)) {
if (!file.exists()) {
try (FileWriter writer = new FileWriter(file)) {
NEIClientConfig.logger.info("Creating default serial handlers list {}", file);
Collection<String> toSave = Loader.isModLoaded("dreamcraft") ? Collections.singletonList("") : Arrays.asList(defaultSerialHandlers);
IOUtils.writeLines(toSave, "\n", writer);
URL defaultSerialHandlersResource = ClientHandler.class
.getResource("/assets/nei/cfg/serialhandlers.cfg");
if (defaultSerialHandlersResource != null) {
IOUtils.copy(defaultSerialHandlersResource.openStream(), writer);
}
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to save default serial handlers list to file {}", file, e);
}
}
try (FileReader reader = new FileReader(file)) {
NEIClientConfig.logger.info("Loading serial handlers from file {}", file);
NEIClientConfig.serialHandlers = new HashSet<>(IOUtils.readLines(reader));
NEIClientConfig.serialHandlers = IOUtils.readLines(reader).stream().filter((line) -> !line.startsWith("#"))
.collect(Collectors.toCollection(HashSet::new));
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to load serial handlers from file {}", file, e);
}
@@ -189,8 +177,11 @@ public class ClientHandler
if (!file.exists()) {
try (FileWriter writer = new FileWriter(file)) {
NEIClientConfig.logger.info("Creating default height hack handlers list {}", file);
Collection<String> toSave = Arrays.asList(defaultHeightHackHandlerRegex);
IOUtils.writeLines(toSave, "\n", writer);
URL defaultHeightHackHandlersResource = ClientHandler.class
.getResource("/assets/nei/cfg/heighthackhandlers.cfg");
if (defaultHeightHackHandlersResource != null) {
IOUtils.copy(defaultHeightHackHandlersResource.openStream(), writer);
}
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to save default height hack handlers list to file {}", file, e);
}
@@ -198,10 +189,9 @@ public class ClientHandler
try (FileReader reader = new FileReader(file)) {
NEIClientConfig.logger.info("Loading height hack handlers from file {}", file);
NEIClientConfig.heightHackHandlerRegex =
IOUtils.readLines(reader).stream()
.map(Pattern::compile)
.collect(Collectors.toCollection(HashSet::new));
NEIClientConfig.heightHackHandlerRegex = IOUtils.readLines(reader).stream()
.filter((line) -> !line.startsWith("#")).map(Pattern::compile)
.collect(Collectors.toCollection(HashSet::new));
} catch (IOException e) {
NEIClientConfig.logger.error("Failed to load height hack handlers from file {}", file, e);
}
@@ -231,8 +221,7 @@ public class ClientHandler
NEIClientConfig.logger.info("Creating default handler ordering CSV {}", file);
List<String> toWrite = Lists.newArrayList(defaultHandlerOrdering);
GuiRecipeTab.handlerMap.keySet().stream()
.sorted()
GuiRecipeTab.handlerMap.keySet().stream().sorted()
.forEach(handlerId -> toWrite.add(String.format("%s,0", handlerId)));
IOUtils.writeLines(toWrite, "\n", writer);
@@ -274,49 +263,48 @@ public class ClientHandler
@SubscribeEvent
public void tickEvent(TickEvent.ClientTickEvent event) {
if(event.phase == Phase.END)
return;
if (event.phase == Phase.END) return;
Minecraft mc = Minecraft.getMinecraft();
if(mc.theWorld != null) {
if (mc.theWorld != null) {
loadWorld(mc.theWorld, false);
if (!NEIClientConfig.isEnabled())
return;
if (!NEIClientConfig.isEnabled()) return;
KeyManager.tickKeyStates();
/*
* NEI plugins are loaded in a separate thread. Make sure loading them has finished otherwise a CME might
* occur in KeyManager if a plugin calls API.addKeyBind() during initialization.
*/
if (NEIClientConfig.isLoaded()) KeyManager.tickKeyStates();
NEIController.updateUnlimitedItems(mc.thePlayer.inventory);
if (mc.currentScreen == null)
NEIController.processCreativeCycling(mc.thePlayer.inventory);
if (mc.currentScreen == null) NEIController.processCreativeCycling(mc.thePlayer.inventory);
updateMagnetMode(mc.theWorld, mc.thePlayer);
}
GuiScreen gui = mc.currentScreen;
if (gui != lastGui) {
if (gui instanceof GuiMainMenu)
lastworld = null;
else if (gui instanceof GuiSelectWorld)
NEIClientConfig.reloadSaves();
if (gui instanceof GuiMainMenu) lastworld = null;
else if (gui instanceof GuiSelectWorld) NEIClientConfig.reloadSaves();
else if (gui == null) {
/* prevent WorldClient reference being held in the Gui */
NEIController.manager = null;
}
}
lastGui = gui;
}
@SubscribeEvent
public void tickEvent(TickEvent.RenderTickEvent event) {
if(event.phase == Phase.END && NEIClientConfig.isEnabled())
HUDRenderer.renderOverlay();
if (event.phase == Phase.END && NEIClientConfig.isEnabled()) HUDRenderer.renderOverlay();
}
@SubscribeEvent
public void renderLastEvent(RenderWorldLastEvent event) {
if (NEIClientConfig.isEnabled())
WorldOverlayRenderer.render(event.partialTicks);
if (NEIClientConfig.isEnabled()) WorldOverlayRenderer.render(event.partialTicks);
}
public void loadWorld(World world, boolean fromServer) {
if (world != lastworld) {
SMPmagneticItems.clear();
@@ -326,8 +314,10 @@ public class ClientHandler
NEIClientConfig.setHasSMPCounterPart(false);
NEIClientConfig.setInternalEnabled(false);
if (!Minecraft.getMinecraft().isSingleplayer())//wait for server to initiate in singleplayer
if (!Minecraft.getMinecraft().isSingleplayer()) // wait for server to initiate in singleplayer
NEIClientConfig.loadWorld("remote/" + ClientUtils.getServerIP().replace(':', '~'));
ItemMobSpawner.clearEntityReferences(world);
}
lastworld = world;
@@ -339,8 +329,8 @@ public class ClientHandler
}
public static RuntimeException throwCME(final String message) {
final GuiScreen errorGui = new GuiErrorScreen(null, null)
{
final GuiScreen errorGui = new GuiErrorScreen(null, null) {
@Override
public void handleMouseInput() {}
@@ -357,15 +347,16 @@ public class ClientHandler
};
@SuppressWarnings("serial")
CustomModLoadingErrorDisplayException e = new CustomModLoadingErrorDisplayException()
{
CustomModLoadingErrorDisplayException e = new CustomModLoadingErrorDisplayException() {
@Override
public void initGui(GuiErrorScreen errorScreen, FontRenderer fontRenderer) {
Minecraft.getMinecraft().displayGuiScreen(errorGui);
}
@Override
public void drawScreen(GuiErrorScreen errorScreen, FontRenderer fontRenderer, int mouseRelX, int mouseRelY, float tickTime) {}
public void drawScreen(GuiErrorScreen errorScreen, FontRenderer fontRenderer, int mouseRelX, int mouseRelY,
float tickTime) {}
};
throw e;
}
@@ -1,7 +1,5 @@
package codechicken.nei;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
@@ -11,10 +9,13 @@ import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
public class ContainerCreativeInv extends Container
{
private class SlotArmor extends Slot
{
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ContainerCreativeInv extends Container {
private class SlotArmor extends Slot {
final int armorType;
public SlotArmor(IInventory inv, int x, int y, int slot, int armor) {
@@ -39,15 +40,16 @@ public class ContainerCreativeInv extends Container
}
}
private class SlotBlockArmor extends SlotArmor
{
private class SlotBlockArmor extends SlotArmor {
public SlotBlockArmor(IInventory inv, int x, int y, int slot, int armor) {
super(inv, x, y, slot, armor);
}
@Override
public boolean isItemValid(ItemStack stack) {
return super.isItemValid(stack) || stack != null;// && Block.getBlockFromItem(stack.getItem()) != Blocks.air;
return super.isItemValid(stack) || stack != null; // && Block.getBlockFromItem(stack.getItem()) !=
// Blocks.air;
}
}
@@ -56,20 +58,22 @@ public class ContainerCreativeInv extends Container
public ContainerCreativeInv(EntityPlayer player, ExtendedCreativeInv extraInv) {
this.player = player;
InventoryPlayer invPlayer = player.inventory;
for (int row = 0; row < 6; row++)
for (int col = 0; col < 9; col++)
addSlotToContainer(new Slot(extraInv, col + row * 9, 8 + col * 18, 5 + row * 18));
for (int row = 0; row < 6; row++) for (int col = 0; col < 9; col++)
addSlotToContainer(new Slot(extraInv, col + row * 9, 8 + col * 18, 5 + row * 18));
for (int row = 0; row < 3; ++row)
for (int col = 0; col < 9; ++col)
addSlotToContainer(new Slot(invPlayer, col + row * 9 + 9, 8 + col * 18, 118 + row * 18));
for (int row = 0; row < 3; ++row) for (int col = 0; col < 9; ++col)
addSlotToContainer(new Slot(invPlayer, col + row * 9 + 9, 8 + col * 18, 118 + row * 18));
for (int col = 0; col < 9; ++col)
addSlotToContainer(new Slot(invPlayer, col, 8 + col * 18, 176));
for (int col = 0; col < 9; ++col) addSlotToContainer(new Slot(invPlayer, col, 8 + col * 18, 176));
addSlotToContainer(new SlotBlockArmor(invPlayer, invPlayer.getSizeInventory() - 1, -15, 23, 0));
for (int armorType = 1; armorType < 4; armorType++)
addSlotToContainer(new SlotArmor(invPlayer, invPlayer.getSizeInventory() - 1 - armorType, -15, 23 + armorType * 18, armorType));
for (int armorType = 1; armorType < 4; armorType++) addSlotToContainer(
new SlotArmor(
invPlayer,
invPlayer.getSizeInventory() - 1 - armorType,
-15,
23 + armorType * 18,
armorType));
}
@Override
@@ -91,16 +95,13 @@ public class ContainerCreativeInv extends Container
}
if (slotIndex < 54) {
if (!this.mergeItemStack(stack, 54, 90, true))
return null;
if (!this.mergeItemStack(stack, 54, 90, true)) return null;
} else if (!this.mergeItemStack(stack, 0, 54, false)) {
return null;
}
if (stack.stackSize == 0)
slot.putStack(null);
else
slot.onSlotChanged();
if (stack.stackSize == 0) slot.putStack(null);
else slot.onSlotChanged();
}
return transferredStack;
@@ -1,6 +1,7 @@
package codechicken.nei;
import codechicken.lib.render.CCRenderState;
import java.util.ArrayList;
import net.minecraft.client.gui.Gui;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.player.EntityPlayer;
@@ -12,17 +13,18 @@ import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import codechicken.lib.render.CCRenderState;
/**
* This is crap code, don't ever do this.
*/
public class ContainerEnchantmentModifier extends ContainerEnchantment
{
public static class EnchantmentHash
{
public class ContainerEnchantmentModifier extends ContainerEnchantment {
public static class EnchantmentHash {
public EnchantmentHash(Enchantment e, int i, int l) {
enchantment = e;
state = i;
@@ -104,10 +106,11 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
int barempty = height - getScrollBarHeight();
int sbary = rely + (int) (barempty * percentscrolled + 0.5);
if (button == 0 &&
getScrollBarHeight() < height && //the scroll bar can move (not full length)
mousex >= relx + cwidth && mousex < relx + cwidth + getScrollBarWidth() &&
mousey >= rely && mousey < rely + height)//in the scroll pane
if (button == 0 && getScrollBarHeight() < height && // the scroll bar can move (not full length)
mousex >= relx + cwidth
&& mousex < relx + cwidth + getScrollBarWidth()
&& mousey >= rely
&& mousey < rely + height) // in the scroll pane
{
if (mousey < sbary) {
percentscrolled = (mousey - rely) / (float) barempty;
@@ -126,7 +129,7 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
}
public void mouseUp(int mousex, int mousey, int button) {
if (scrollclicky >= 0 && button == 0)//we were scrolling and we released mouse
if (scrollclicky >= 0 && button == 0) // we were scrolling and we released mouse
{
scrollclicky = -1;
}
@@ -135,8 +138,7 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
public boolean clickButton(int mousex, int mousey, int button) {
mousex -= parentscreen.guiLeft;
mousey -= parentscreen.guiTop;
if (mousex >= relx && mousex < relx + cwidth &&
mousey >= rely && mousey <= rely + height)//in the box
if (mousex >= relx && mousex < relx + cwidth && mousey >= rely && mousey <= rely + height) // in the box
{
int slot = getClickedSlot(mousey);
if (slot >= getNumSlots()) return false;
@@ -176,10 +178,8 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
int ID = nbttaglist.getCompoundTagAt(i).getShort("id");
if (ID == e) {
nbttaglist.removeTag(i);
if (nbttaglist.tagCount() == 0)
stack.getTagCompound().removeTag("ench");
if (stack.getTagCompound().hasNoTags())
stack.setTagCompound(null);
if (nbttaglist.tagCount() == 0) stack.getTagCompound().removeTag("ench");
if (stack.getTagCompound().hasNoTags()) stack.setTagCompound(null);
return;
}
}
@@ -191,8 +191,7 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
}
public void onCraftMatrixChanged(IInventory iinventory) {
if (parentscreen != null)
updateEnchantmentOptions(GuiEnchantmentModifier.validateEnchantments());
if (parentscreen != null) updateEnchantmentOptions(GuiEnchantmentModifier.validateEnchantments());
}
public void updateEnchantmentOptions(boolean validate) {
@@ -221,9 +220,10 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
if (NEIServerUtils.stackHasEnchantment(toolstack, e.effectId)) {
state = 2;
level = NEIServerUtils.getEnchantmentLevel(toolstack, e.effectId);
} else if (NEIServerUtils.doesEnchantmentConflict(NEIServerUtils.getEnchantments(toolstack), e) && validate) {
state = 1;
}
} else
if (NEIServerUtils.doesEnchantmentConflict(NEIServerUtils.getEnchantments(toolstack), e) && validate) {
state = 1;
}
slotEnchantment.add(new EnchantmentHash(e, state, level));
}
if (numoptions != slotEnchantment.size()) {
@@ -257,10 +257,28 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
CCRenderState.changeTexture("textures/gui/container/enchanting_table.png");
GL11.glColor3f(1, 1, 1);
if (hasScrollBar()) {
gui.drawTexturedModalRect(relx, rely + slot * slotheight, 0, gui.ySize + slotheight * shade, cwidth - 30, slotheight);
gui.drawTexturedModalRect(relx + cwidth - 30, rely + slot * slotheight, cwidth - 23, gui.ySize + slotheight * shade, 30, slotheight);
gui.drawTexturedModalRect(
relx,
rely + slot * slotheight,
0,
gui.ySize + slotheight * shade,
cwidth - 30,
slotheight);
gui.drawTexturedModalRect(
relx + cwidth - 30,
rely + slot * slotheight,
cwidth - 23,
gui.ySize + slotheight * shade,
30,
slotheight);
} else {
gui.drawTexturedModalRect(relx, rely + slot * slotheight, 0, gui.ySize + slotheight * shade, cwidth + 7, slotheight);
gui.drawTexturedModalRect(
relx,
rely + slot * slotheight,
0,
gui.ySize + slotheight * shade,
cwidth + 7,
slotheight);
}
gui.getFontRenderer().drawString(text, relx + 4, rely + slot * slotheight + 5, textColourFromState(shade));
@@ -277,18 +295,32 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment
int sbary = rely + (int) ((height - getScrollBarHeight()) * percentscrolled + 0.5);
int sbarx = relx + cwidth;
Gui.drawRect(sbarx, rely, sbarx + getScrollBarWidth(), rely + height, 0xFF202020);//background
Gui.drawRect(sbarx, sbary, sbarx + getScrollBarWidth(), sbary + getScrollBarHeight(), 0xFF8B8B8B);//corners
Gui.drawRect(sbarx, sbary, sbarx + getScrollBarWidth() - 1, sbary + getScrollBarHeight() - 1, 0xFFF0F0F0);//topleft up
Gui.drawRect(sbarx + 1, sbary + 1, sbarx + getScrollBarWidth() - 1, sbary + getScrollBarHeight() - 1, 0xFF555555);//bottom right down
Gui.drawRect(sbarx + 1, sbary + 1, sbarx + getScrollBarWidth() - 2, sbary + getScrollBarHeight() - 2, 0xFFC6C6C6);//scrollbar
Gui.drawRect(sbarx, rely, sbarx + getScrollBarWidth(), rely + height, 0xFF202020); // background
Gui.drawRect(sbarx, sbary, sbarx + getScrollBarWidth(), sbary + getScrollBarHeight(), 0xFF8B8B8B); // corners
Gui.drawRect(sbarx, sbary, sbarx + getScrollBarWidth() - 1, sbary + getScrollBarHeight() - 1, 0xFFF0F0F0); // topleft
// up
Gui.drawRect(
sbarx + 1,
sbary + 1,
sbarx + getScrollBarWidth() - 1,
sbary + getScrollBarHeight() - 1,
0xFF555555); // bottom right down
Gui.drawRect(
sbarx + 1,
sbary + 1,
sbarx + getScrollBarWidth() - 2,
sbary + getScrollBarHeight() - 2,
0xFFC6C6C6); // scrollbar
}
private int textColourFromState(int shade) {
switch(shade) {
case 0: return 0x685e4a;
case 1: return 0x407f10;
default: return 0xffff80;
switch (shade) {
case 0:
return 0x685e4a;
case 1:
return 0x407f10;
default:
return 0xffff80;
}
}
@@ -1,10 +1,5 @@
package codechicken.nei;
import codechicken.lib.inventory.ContainerExtended;
import codechicken.lib.inventory.InventoryNBT;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.inventory.SlotHandleClicks;
import codechicken.lib.packet.PacketCustom;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
@@ -16,10 +11,16 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.PotionEffect;
public class ContainerPotionCreator extends ContainerExtended
{
public class SlotPotion extends Slot
{
import codechicken.lib.inventory.ContainerExtended;
import codechicken.lib.inventory.InventoryNBT;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.inventory.SlotHandleClicks;
import codechicken.lib.packet.PacketCustom;
public class ContainerPotionCreator extends ContainerExtended {
public class SlotPotion extends Slot {
public SlotPotion(IInventory inv, int slotIndex, int x, int y) {
super(inv, slotIndex, x, y);
}
@@ -34,16 +35,15 @@ public class ContainerPotionCreator extends ContainerExtended
super.onSlotChanged();
if (getHasStack()) {
ItemStack stack = getStack();
if (!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound());
if (!stack.getTagCompound().hasKey("CustomPotionEffects"))
stack.getTagCompound().setTag("CustomPotionEffects", new NBTTagList());
}
}
}
public class SlotPotionStore extends SlotHandleClicks
{
public class SlotPotionStore extends SlotHandleClicks {
public SlotPotionStore(IInventory inv, int slotIndex, int x, int y) {
super(inv, slotIndex, x, y);
}
@@ -60,8 +60,7 @@ public class ContainerPotionCreator extends ContainerExtended
putStack(InventoryUtils.copyStack(held, 1));
player.inventory.setItemStack(null);
}
} else if (getHasStack())
player.inventory.setItemStack(getStack());
} else if (getHasStack()) player.inventory.setItemStack(getStack());
return null;
}
@@ -72,8 +71,8 @@ public class ContainerPotionCreator extends ContainerExtended
}
}
public static class InventoryPotionStore extends InventoryNBT
{
public static class InventoryPotionStore extends InventoryNBT {
public InventoryPotionStore() {
super(9, NEIClientConfig.global.nbt.getCompoundTag("potionStore"));
}
@@ -96,15 +95,13 @@ public class ContainerPotionCreator extends ContainerExtended
this.potionStoreInv = potionStoreInv;
addSlotToContainer(new SlotPotion(potionInv, 0, 25, 102));
for (int i = 0; i < 9; i++)
addSlotToContainer(new SlotPotionStore(potionStoreInv, i, 8 + i * 18, 14));
for (int i = 0; i < 9; i++) addSlotToContainer(new SlotPotionStore(potionStoreInv, i, 8 + i * 18, 14));
bindPlayerInventory(inventoryPlayer, 8, 125);
}
@Override
public boolean doMergeStackAreas(int slotIndex, ItemStack stack) {
if (slotIndex < 10)
return mergeItemStack(stack, 10, 46, true);
if (slotIndex < 10) return mergeItemStack(stack, 10, 46, true);
return mergeItemStack(stack, 0, 1, false);
}
@@ -117,30 +114,28 @@ public class ContainerPotionCreator extends ContainerExtended
public void onContainerClosed(EntityPlayer player) {
super.onContainerClosed(player);
if (!player.worldObj.isRemote)
InventoryUtils.dropOnClose(player, potionInv);
if (!player.worldObj.isRemote) InventoryUtils.dropOnClose(player, potionInv);
}
@SuppressWarnings("unchecked")
@Override
public void handleServerPacket(PacketCustom packet) {
ItemStack potion = potionInv.getStackInSlot(0);
if (potion == null)
return;
if (potion == null) return;
boolean add = packet.getType() == 3;
int effectID = packet.readUByte();
NBTTagList effects = potion.getTagCompound().getTagList("CustomPotionEffects", 10);
NBTTagList newEffects = new NBTTagList();
for(int i = 0; i < effects.tagCount(); i++) {
for (int i = 0; i < effects.tagCount(); i++) {
NBTTagCompound tag = effects.getCompoundTagAt(i);
PotionEffect e = PotionEffect.readCustomPotionEffectFromNBT(tag);
if(e.getPotionID() != effectID)
newEffects.appendTag(tag);
if (e.getPotionID() != effectID) newEffects.appendTag(tag);
}
if(add)
newEffects.appendTag(new PotionEffect(effectID, packet.readInt(), packet.readUByte()).writeCustomPotionEffectToNBT(new NBTTagCompound()));
if (add) newEffects.appendTag(
new PotionEffect(effectID, packet.readInt(), packet.readUByte())
.writeCustomPotionEffectToNBT(new NBTTagCompound()));
potion.getTagCompound().setTag("CustomPotionEffects", newEffects);
}
@@ -157,4 +152,4 @@ public class ContainerPotionCreator extends ContainerExtended
packet.writeByte(effectID);
packet.sendToServer();
}
}
}
@@ -0,0 +1,47 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.LinkedList;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import codechicken.nei.api.IBookmarkContainerHandler;
public class DefaultBookmarkContainerHandler implements IBookmarkContainerHandler {
@Override
public void pullBookmarkItemsFromContainer(GuiContainer guiContainer, ArrayList<ItemStack> bookmarkItems) {
FastTransferManager manager = new FastTransferManager();
LinkedList<ItemStack> containerStacks = manager.saveContainer(guiContainer.inventorySlots);
for (ItemStack bookmarkItem : bookmarkItems) {
int bookmarkSizeBackup = bookmarkItem.stackSize;
for (int i = 0; i < containerStacks.size() - 4 * 9; i++) { // Last 36 slots are player inventory
ItemStack containerItem = containerStacks.get(i);
if (containerItem == null) {
continue;
}
if (bookmarkItem.isItemEqual(containerItem)) {
if (bookmarkItem.stackSize <= 0) {
break;
}
int transferAmount = Math.min(bookmarkItem.stackSize, containerItem.stackSize);
manager.transferItems(guiContainer, i, transferAmount);
bookmarkItem.stackSize -= transferAmount;
if (bookmarkItem.stackSize == 0) {
break;
}
}
}
bookmarkItem.stackSize = bookmarkSizeBackup;
}
}
}
@@ -1,35 +1,34 @@
package codechicken.nei;
import codechicken.nei.api.IHighlightHandler;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import java.util.List;
import codechicken.nei.api.IHighlightHandler;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
public class DefaultHighlightHandler implements IHighlightHandler {
public class DefaultHighlightHandler implements IHighlightHandler
{
@Override
public List<String> handleTextData(ItemStack stack, World world, EntityPlayer player, MovingObjectPosition mop, List<String> currenttip, ItemInfo.Layout layout) {
public List<String> handleTextData(ItemStack stack, World world, EntityPlayer player, MovingObjectPosition mop,
List<String> currenttip, ItemInfo.Layout layout) {
String name = null;
try {
String s = GuiContainerManager.itemDisplayNameShort(stack);
if (s != null && !s.endsWith("Unnamed"))
name = s;
if (s != null && !s.endsWith("Unnamed")) name = s;
if (name != null)
currenttip.add(name);
if (name != null) currenttip.add(name);
} catch (Exception ignored) {}
if (name != null && stack.getItem() == Items.redstone) {
int md = world.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ);
String s = "" + md;
if (s.length() < 2)
s = " " + s;
if (s.length() < 2) s = " " + s;
currenttip.set(currenttip.size() - 1, name + " " + s);
}
@@ -1,20 +1,22 @@
package codechicken.nei;
import codechicken.nei.api.ItemFilter;
import net.minecraft.item.ItemStack;
import codechicken.nei.api.ItemFilter;
public class DoubleFilteredFilter implements ItemFilter {
private ItemFilter filter;
private ItemList.PatternItemFilter patternFilter;
public DoubleFilteredFilter(ItemFilter filter, String itemFilter) {
this.filter = filter;
this.filter = filter;
this.patternFilter = new ItemList.PatternItemFilter(SearchField.getPattern(itemFilter));
}
@Override
public boolean matches(ItemStack item) {
if(filter.matches(item)) {
if (filter.matches(item)) {
return patternFilter.matches(item);
}
return false;
@@ -1,12 +1,13 @@
package codechicken.nei;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public class ExtendedCreativeInv implements IInventory
{
import cpw.mods.fml.relauncher.Side;
public class ExtendedCreativeInv implements IInventory {
final PlayerSave playerSave;
final Side side;
@@ -22,8 +23,7 @@ public class ExtendedCreativeInv implements IInventory
@Override
public ItemStack getStackInSlot(int slot) {
if (side.isClient())
return NEIClientConfig.creativeInv[slot];
if (side.isClient()) return NEIClientConfig.creativeInv[slot];
return playerSave.creativeInv[slot];
}
@@ -58,10 +58,8 @@ public class ExtendedCreativeInv implements IInventory
@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
if (side.isClient())
NEIClientConfig.creativeInv[slot] = stack;
else
playerSave.creativeInv[slot] = stack;
if (side.isClient()) NEIClientConfig.creativeInv[slot] = stack;
else playerSave.creativeInv[slot] = stack;
markDirty();
}
@@ -78,8 +76,7 @@ public class ExtendedCreativeInv implements IInventory
@Override
public void markDirty() {
if (side.isServer())
playerSave.setCreativeDirty();
if (side.isServer()) playerSave.setCreativeDirty();
}
@Override
@@ -88,12 +85,10 @@ public class ExtendedCreativeInv implements IInventory
}
@Override
public void openInventory() {
}
public void openInventory() {}
@Override
public void closeInventory() {
}
public void closeInventory() {}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
@@ -104,5 +99,4 @@ public class ExtendedCreativeInv implements IInventory
public boolean hasCustomInventoryName() {
return true;
}
}
@@ -1,27 +1,28 @@
package codechicken.nei;
import codechicken.nei.guihook.GuiContainerManager;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import static codechicken.nei.NEIServerUtils.areStacksIdentical;
import static codechicken.nei.NEIServerUtils.areStacksSameType;
import static codechicken.nei.NEIServerUtils.copyStack;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import static codechicken.nei.NEIServerUtils.areStacksIdentical;
import static codechicken.nei.NEIServerUtils.areStacksSameType;
import static codechicken.nei.NEIServerUtils.copyStack;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import codechicken.nei.guihook.GuiContainerManager;
public class FastTransferManager {
public class FastTransferManager
{
/**
* Based on the general assumption that we want to fill top to bottom, left to right
*/
public static class SlotPositionComparator implements Comparator<Integer>
{
public static class SlotPositionComparator implements Comparator<Integer> {
final Container container;
public SlotPositionComparator(Container c) {
@@ -47,8 +48,7 @@ public class FastTransferManager
stack.stackSize = 1;
for (int slotNo = 0; slotNo < container.inventorySlots.size(); slotNo++) {
if (slotZoneMap.containsKey(slotNo) || !container.getSlot(slotNo).isItemValid(stack))
continue;
if (slotZoneMap.containsKey(slotNo) || !container.getSlot(slotNo).isItemValid(stack)) continue;
HashSet<Integer> connectedSlots = new HashSet<>();
findConnectedSlots(container, slotNo, connectedSlots);
@@ -69,11 +69,11 @@ public class FastTransferManager
final int threshold = 18;
for (int i = 0; i < container.inventorySlots.size(); i++) {
if (connectedSlots.contains(i))
continue;
if (connectedSlots.contains(i)) continue;
Slot slot1 = container.getSlot(i);
if (Math.abs(slot.xDisplayPosition - slot1.xDisplayPosition) <= threshold && Math.abs(slot.yDisplayPosition - slot1.yDisplayPosition) <= threshold) {
if (Math.abs(slot.xDisplayPosition - slot1.xDisplayPosition) <= threshold
&& Math.abs(slot.yDisplayPosition - slot1.yDisplayPosition) <= threshold) {
findConnectedSlots(container, i, connectedSlots);
}
}
@@ -82,8 +82,7 @@ public class FastTransferManager
public static int findSlotWithItem(Container container, ItemStack teststack) {
for (int slotNo = 0; slotNo < container.inventorySlots.size(); slotNo++) {
ItemStack stack = container.getSlot(slotNo).getStack();
if (areStacksSameType(stack, teststack))
return slotNo;
if (areStacksSameType(stack, teststack)) return slotNo;
}
return -1;
}
@@ -99,20 +98,16 @@ public class FastTransferManager
Integer fromZone = slotZoneMap.get(fromSlot);
Integer toZone = slotZoneMap.get(toSlot);
if (fromZone == null || toZone == null || fromZone.equals(toZone))
return;
if (fromZone == null || toZone == null || fromZone.equals(toZone)) return;
if (NEIClientUtils.getHeldItem() != null && !areStacksSameType(heldStack, NEIClientUtils.getHeldItem()))
return;
if (NEIClientUtils.getHeldItem() != null && !areStacksSameType(heldStack, NEIClientUtils.getHeldItem())) return;
if (!fillZoneWithHeldItem(window, toZone))
return;
if (!fillZoneWithHeldItem(window, toZone)) return;
for (int transferFrom : slotZones.get(fromZone)) {
ItemStack transferStack = window.inventorySlots.getSlot(transferFrom).getStack();
if (!areStacksSameType(heldStack, transferStack))
continue;
if (!areStacksSameType(heldStack, transferStack)) continue;
clickSlot(window, transferFrom);
if (!fillZoneWithHeldItem(window, toZone)) {
@@ -130,8 +125,7 @@ public class FastTransferManager
Slot slot = container.getSlot(fromSlot);
ItemStack stack = slot.getStack();
if (stack == null)
return -1;
if (stack == null) return -1;
stack.stackSize = 1;
slot.putStack(stack.copy());
@@ -141,19 +135,19 @@ public class FastTransferManager
LinkedList<ItemStack> compareAfter = saveContainer(container);
try {
//if(compareAfter.get(fromSlot) != null)//transfer failed
//return -1;
// if(compareAfter.get(fromSlot) != null)//transfer failed
// return -1;
for (int i = 0; i < compareBefore.size(); i++) {
if (i == fromSlot)
continue;
if (i == fromSlot) continue;
ItemStack before = compareBefore.get(i);
ItemStack after = compareAfter.get(i);
if (!areStacksIdentical(before, after) && after != null)
if (before == null ? areStacksSameType(stack, after) ://transfered into this empty slot
areStacksSameType(stack, after) && after.stackSize - before.stackSize > 0)//it added to this stack
if (before == null ? areStacksSameType(stack, after) : // transfered into this empty slot
areStacksSameType(stack, after) && after.stackSize - before.stackSize > 0) // it added to
// this stack
return i;
}
@@ -181,45 +175,48 @@ public class FastTransferManager
public void transferItem(GuiContainer window, int fromSlot) {
int toSlot = findShiftClickDestinationSlot(window.inventorySlots, fromSlot);
if (toSlot == -1)
return;
if (toSlot == -1) return;
Slot from = window.inventorySlots.getSlot(fromSlot);
if (from.isItemValid(from.getStack()))
moveOneItem(window, fromSlot, toSlot);
else//slots that you can't put stuff in
if (from.isItemValid(from.getStack())) moveOneItem(window, fromSlot, toSlot);
else // slots that you can't put stuff in
moveOutputSet(window, fromSlot, toSlot);
}
public void moveOutputSet(GuiContainer window, int fromSlot, int toSlot) {
if (NEIClientUtils.getHeldItem() != null)
return;
public void transferItems(GuiContainer window, int fromSlot, int itemCount) {
for (int i = 0; i < itemCount; i++) {
transferItem(window, fromSlot);
}
}
clickSlot(window, fromSlot);//pickup fromSlot
if (NEIClientUtils.getHeldItem() == null)//maybe this container does auto transfers. No need to pick up the final item
public void moveOutputSet(GuiContainer window, int fromSlot, int toSlot) {
if (NEIClientUtils.getHeldItem() != null) return;
clickSlot(window, fromSlot); // pickup fromSlot
if (NEIClientUtils.getHeldItem() == null) // maybe this container does auto transfers. No need to pick up the
// final item
return;
clickSlot(window, toSlot);//place one in toSlot
clickSlot(window, toSlot); // place one in toSlot
}
public void moveOneItem(GuiContainer window, int fromSlot, int toSlot) {
clickSlot(window, fromSlot);//pickup fromSlot
clickSlot(window, toSlot, 1);//place one in toSlot
clickSlot(window, fromSlot);//place down in fromSlot
clickSlot(window, fromSlot); // pickup fromSlot
clickSlot(window, toSlot, 1); // place one in toSlot
clickSlot(window, fromSlot); // place down in fromSlot
}
public void retrieveItem(GuiContainer window, int toSlot) {
Slot slot = window.inventorySlots.getSlot(toSlot);
ItemStack slotStack = slot.getStack();
if (slotStack == null ||
slotStack.stackSize == slot.getSlotStackLimit() ||
slotStack.stackSize == slotStack.getMaxStackSize())
if (slotStack == null || slotStack.stackSize == slot.getSlotStackLimit()
|| slotStack.stackSize == slotStack.getMaxStackSize())
return;
generateSlotMap(window.inventorySlots, slotStack);
Integer destZone = slotZoneMap.get(toSlot);
if (destZone == null)//slots that don't accept
if (destZone == null) // slots that don't accept
return;
int firstZoneSlot = findShiftClickDestinationSlot(window.inventorySlots, toSlot);
@@ -228,17 +225,14 @@ public class FastTransferManager
Integer integer = slotZoneMap.get(firstZoneSlot);
if (integer != null) {
firstZone = integer;
if (retrieveItemFromZone(window, firstZone, toSlot))
return;
if (retrieveItemFromZone(window, firstZone, toSlot)) return;
}
}
for (int zone = 0; zone < slotZones.size(); zone++) {
if (zone == destZone || zone == firstZone)
continue;
if (zone == destZone || zone == firstZone) continue;
if (retrieveItemFromZone(window, zone, toSlot))
return;
if (retrieveItemFromZone(window, zone, toSlot)) return;
}
retrieveItemFromZone(window, destZone, toSlot);
@@ -247,14 +241,14 @@ public class FastTransferManager
private boolean retrieveItemFromZone(GuiContainer window, int zone, int toSlot) {
ItemStack stack = window.inventorySlots.getSlot(toSlot).getStack();
for (int i : slotZones.get(zone)) {
if (i == toSlot)
continue;
if (i == toSlot) continue;
Slot slot = window.inventorySlots.getSlot(i);
ItemStack stack1 = slot.getStack();
if (areStacksSameType(stack, stack1) &&
stack1.stackSize != slot.getSlotStackLimit() && //get from full stacks on second pass
if (areStacksSameType(stack, stack1) && stack1.stackSize != slot.getSlotStackLimit() && // get from full
// stacks on second
// pass
stack1.stackSize != stack1.getMaxStackSize()) {
moveOneItem(window, i, toSlot);
return true;
@@ -262,8 +256,7 @@ public class FastTransferManager
}
for (int i : slotZones.get(zone)) {
if (i == toSlot)
continue;
if (i == toSlot) continue;
Slot slot = window.inventorySlots.getSlot(i);
ItemStack stack1 = slot.getStack();
@@ -292,28 +285,24 @@ public class FastTransferManager
for (int transferTo : slotZones.get(zoneIndex)) {
ItemStack held = NEIClientUtils.getHeldItem();
if (held == null)
break;
if (held == null) break;
ItemStack inToSlot = window.inventorySlots.getSlot(transferTo).getStack();
if (!areStacksSameType(inToSlot, held))
continue;
if (!areStacksSameType(inToSlot, held)) continue;
clickSlot(window, transferTo);
}
for (int transferTo : slotZones.get(zoneIndex))//repeat on empty slots
for (int transferTo : slotZones.get(zoneIndex)) // repeat on empty slots
{
ItemStack held = NEIClientUtils.getHeldItem();
if (held == null)
break;
if (held == null) break;
ItemStack inToSlot = window.inventorySlots.getSlot(transferTo).getStack();
if (inToSlot != null)
continue;
if (inToSlot != null) continue;
clickSlot(window, transferTo);
}
@@ -323,14 +312,13 @@ public class FastTransferManager
public void throwAll(GuiContainer window, int pickedUpFromSlot) {
ItemStack held = NEIClientUtils.getHeldItem();
if (held == null)
return;
if (held == null) return;
clickSlot(window, -999);
generateSlotMap(window.inventorySlots, held);
Integer zone = slotZoneMap.get(pickedUpFromSlot);
if(zone == null) //something went wrong and we can't work out where the item was picked up from
if (zone == null) // something went wrong and we can't work out where the item was picked up from
return;
for (int slotIndex : slotZones.get(zone)) {
@@ -1,17 +1,19 @@
package codechicken.nei;
import codechicken.lib.render.CCRenderState;
import static codechicken.nei.NEIClientUtils.translate;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import static codechicken.nei.NEIClientUtils.translate;
import codechicken.lib.render.CCRenderState;
public class GuiEnchantmentModifier extends GuiContainer {
public class GuiEnchantmentModifier extends GuiContainer
{
final ContainerEnchantmentModifier container;
public GuiEnchantmentModifier(InventoryPlayer inventoryplayer, World world, int i, int j, int k) {
@@ -1,18 +1,22 @@
package codechicken.nei;
import codechicken.lib.render.CCRenderState;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.TaggedInventoryArea;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import java.util.Collections;
import java.util.List;
public class GuiExtendedCreativeInv extends GuiContainer implements INEIGuiHandler
{
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.TaggedInventoryArea;
public class GuiExtendedCreativeInv extends GuiContainer implements INEIGuiHandler {
public GuiExtendedCreativeInv(Container par1Container) {
super(par1Container);
ySize = 198;
@@ -51,6 +55,17 @@ public class GuiExtendedCreativeInv extends GuiContainer implements INEIGuiHandl
@Override
public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) {
return false;
return (new Rectangle4i(guiLeft - 15, guiTop + 18, 18, 18 * 4 + 4)).intersects(new Rectangle4i(x, y, w, h));
}
@Override
protected void handleMouseClick(Slot p_146984_1_, int p_146984_2_, int p_146984_3_, int p_146984_4_) {
// Hack for armor slots, because they are outside the container
if (p_146984_1_ != null && p_146984_4_ == 4 && p_146984_1_.xDisplayPosition < 0) {
p_146984_4_ = 0;
}
super.handleMouseClick(p_146984_1_, p_146984_2_, p_146984_3_, p_146984_4_);
}
}
+44 -21
View File
@@ -4,38 +4,61 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
public class GuiNEIButton extends GuiButton
{
public class GuiNEIButton extends GuiButton {
protected static final ResourceLocation guiTex = new ResourceLocation("textures/gui/widgets.png");
public GuiNEIButton(int i, int j, int k, int l, int i1, String s)
{
public GuiNEIButton(int i, int j, int k, int l, int i1, String s) {
super(i, j, k, l, i1, s);
}
public void drawButton(Minecraft minecraft, int i, int j)
{
if(!visible)
return;
public void drawButton(Minecraft minecraft, int i, int j) {
if (!visible) return;
FontRenderer fontrenderer = minecraft.fontRenderer;
minecraft.renderEngine.bindTexture(guiTex);
GL11.glColor4f(1, 1, 1, 1);
boolean flag = i >= xPosition && j >= yPosition && i < xPosition + width && j < yPosition + height;
int k = getHoverState(flag);
drawTexturedModalRect(xPosition, yPosition, 0, 46 + k * 20, width / 2, height / 2);//top left
drawTexturedModalRect(xPosition + width / 2, yPosition, 200 - width / 2, 46 + k * 20, width / 2, height / 2);//top right
drawTexturedModalRect(xPosition, yPosition + height / 2, 0, 46 + k * 20 + 20 - height / 2, width / 2, height / 2);//bottom left
drawTexturedModalRect(xPosition + width / 2, yPosition + height / 2, 200 - width / 2, 46 + k * 20 + 20 - height / 2, width / 2, height / 2);//bottom right
drawTexturedModalRect(xPosition, yPosition, 0, 46 + k * 20, width / 2, height / 2); // top left
drawTexturedModalRect(xPosition + width / 2, yPosition, 200 - width / 2, 46 + k * 20, width / 2, height / 2); // top
// right
drawTexturedModalRect(
xPosition,
yPosition + height / 2,
0,
46 + k * 20 + 20 - height / 2,
width / 2,
height / 2); // bottom left
drawTexturedModalRect(
xPosition + width / 2,
yPosition + height / 2,
200 - width / 2,
46 + k * 20 + 20 - height / 2,
width / 2,
height / 2); // bottom right
mouseDragged(minecraft, i, j);
if(!enabled)
drawCenteredString(fontrenderer, displayString, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffa0a0a0);
else if(flag)
drawCenteredString(fontrenderer, displayString, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffffa0);
else
drawCenteredString(fontrenderer, displayString, xPosition + width / 2, yPosition + (height - 8) / 2, 0xe0e0e0);
if (!enabled) drawCenteredString(
fontrenderer,
displayString,
xPosition + width / 2,
yPosition + (height - 8) / 2,
0xffa0a0a0);
else if (flag) drawCenteredString(
fontrenderer,
displayString,
xPosition + width / 2,
yPosition + (height - 8) / 2,
0xffffa0);
else drawCenteredString(
fontrenderer,
displayString,
xPosition + width / 2,
yPosition + (height - 8) / 2,
0xe0e0e0);
}
}
@@ -1,37 +1,37 @@
package codechicken.nei;
import static codechicken.nei.NEIClientUtils.translate;
import java.awt.Dimension;
import java.util.ArrayList;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import codechicken.core.gui.GuiCCButton;
import codechicken.core.gui.GuiCCTextField;
import codechicken.core.gui.GuiScrollSlot;
import codechicken.core.inventory.GuiContainerWidget;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.FontUtils;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import java.awt.Dimension;
import java.util.ArrayList;
public class GuiPotionCreator extends GuiContainerWidget {
import static codechicken.nei.NEIClientUtils.translate;
public class GuiSlotPotionEffects extends GuiScrollSlot {
public class GuiPotionCreator extends GuiContainerWidget
{
public class GuiSlotPotionEffects extends GuiScrollSlot
{
public int selectedslot = -1;
public boolean enabled = true;
private final ArrayList<Potion> validPotions = new ArrayList<>();
public GuiSlotPotionEffects(int x, int y) {
super(x, y, 108, 76);
for (Potion p : Potion.potionTypes)
if (p != null)
validPotions.add(p);
for (Potion p : Potion.potionTypes) if (p != null) validPotions.add(p);
setSmoothScroll(false);
setMargins(0, 0, 0, 0);
}
@@ -48,8 +48,7 @@ public class GuiPotionCreator extends GuiContainerWidget
}
@Override
public void drawOverlay(float frame) {
}
public void drawOverlay(float frame) {}
@Override
public int scrollbarGuideAlignment() {
@@ -69,13 +68,18 @@ public class GuiPotionCreator extends GuiContainerWidget
Potion potion = validPotions.get(slot);
PotionEffect effect = getEffect(potion.id);
boolean blank = effect == null;
if (effect == null)
effect = new PotionEffect(potion.id, 1200, 0);
if (effect == null) effect = new PotionEffect(potion.id, 1200, 0);
int shade = selectedslot == slot ? 2 : blank ? 1 : 0;
CCRenderState.changeTexture("textures/gui/container/enchanting_table.png");
drawTexturedModalRect(x, y, 0, 166 + getSlotHeight(slot) * shade, width - 30, getSlotHeight(slot));
drawTexturedModalRect(x + width - 30, y, width - 23, 166 + getSlotHeight(slot) * shade, 30, getSlotHeight(slot));
drawTexturedModalRect(
x + width - 30,
y,
width - 23,
166 + getSlotHeight(slot) * shade,
30,
getSlotHeight(slot));
if (potion.hasStatusIcon()) {
CCRenderState.changeTexture("textures/gui/container/inventory.png");
@@ -104,8 +108,7 @@ public class GuiPotionCreator extends GuiContainerWidget
NBTTagList potionTagList = potion.getTagCompound().getTagList("CustomPotionEffects", 10);
for (int i = 0; i < potionTagList.tagCount(); i++) {
PotionEffect effect = PotionEffect.readCustomPotionEffectFromNBT(potionTagList.getCompoundTagAt(i));
if (effect.getPotionID() == id)
return effect;
if (effect.getPotionID() == id) return effect;
}
}
return null;
@@ -118,8 +121,7 @@ public class GuiPotionCreator extends GuiContainerWidget
@Override
protected void slotClicked(int slot, int button, int mx, int my, int count) {
if (!enabled)
return;
if (!enabled) return;
if (button == 0) {
select(slot);
@@ -145,19 +147,16 @@ public class GuiPotionCreator extends GuiContainerWidget
}
public void setEnabled(boolean b) {
if (b == enabled)
return;
if (b == enabled) return;
enabled = b;
if (!enabled)
deselect();
if (!enabled) deselect();
}
private void select(int slot) {
selectedslot = slot;
durationField.setEnabled(true);
PotionEffect effect = getEffect(validPotions.get(slot).id);
if (effect == null)
effect = new PotionEffect(validPotions.get(slot).id, 1200, 0);
if (effect == null) effect = new PotionEffect(validPotions.get(slot).id, 1200, 0);
durationField.setDurationTicks(effect.getDuration());
amplifier = effect.getAmplifier();
validateInputButtons();
@@ -175,8 +174,8 @@ public class GuiPotionCreator extends GuiContainerWidget
}
}
public class GuiDurationField extends GuiCCTextField
{
public class GuiDurationField extends GuiCCTextField {
private String baseValue;
public GuiDurationField(int x, int y, int width, int height) {
@@ -190,27 +189,22 @@ public class GuiPotionCreator extends GuiContainerWidget
i /= 20;
String minutes = Integer.toString(i / 60);
String seconds = Integer.toString(i % 60);
if (seconds.length() == 1)
seconds = '0' + seconds;
if (seconds.length() == 1) seconds = '0' + seconds;
setText(minutes + seconds);
}
@Override
public void setEnabled(boolean b) {
super.setEnabled(b);
if (!isEnabled())
setText("100");
if (!isEnabled()) setText("100");
}
@Override
public void onFocusChanged() {
if (isFocused())
baseValue = getText();
if (isFocused()) baseValue = getText();
else {
if (!validateValue())
setText(baseValue);
else
applyEffect();
if (!validateValue()) setText(baseValue);
else applyEffect();
}
}
@@ -231,7 +225,8 @@ public class GuiPotionCreator extends GuiContainerWidget
@Override
public void drawText() {
String s = getText();
String seconds = s.substring(Math.max(0, s.length() - 2), Math.max(0, s.length() - 2) + Math.min(s.length(), 2));
String seconds = s
.substring(Math.max(0, s.length() - 2), Math.max(0, s.length() - 2) + Math.min(s.length(), 2));
String minutes = s.length() < 3 ? "" : s.substring(0, s.length() - 2);
int ty = y + height / 2 - 4;
int tcolour = getTextColour();
@@ -316,10 +311,8 @@ public class GuiPotionCreator extends GuiContainerWidget
@Override
public void actionPerformed(String ident, Object... params) {
if (ident.equals("ampDown"))
amplifier--;
else if (ident.equals("ampUp"))
amplifier++;
if (ident.equals("ampDown")) amplifier--;
else if (ident.equals("ampUp")) amplifier++;
applyEffect();
validateInputButtons();
}
+35 -43
View File
@@ -1,29 +1,31 @@
package codechicken.nei;
import codechicken.lib.config.ConfigTag;
import codechicken.nei.KeyManager.IKeyStateTracker;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition.MovingObjectType;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.awt.Dimension;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import static codechicken.lib.gui.GuiDraw.displaySize;
import static codechicken.lib.gui.GuiDraw.drawString;
import static codechicken.lib.gui.GuiDraw.drawTooltipBox;
import static codechicken.lib.gui.GuiDraw.getStringWidth;
public class HUDRenderer implements IKeyStateTracker
{
import java.awt.Dimension;
import java.awt.Point;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition.MovingObjectType;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import codechicken.lib.config.ConfigTag;
import codechicken.nei.KeyManager.IKeyStateTracker;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.StackInfo;
public class HUDRenderer implements IKeyStateTracker {
@Override
public void tickKeyStates() {
if (KeyManager.keyStates.get("world.highlight_tips").down) {
@@ -34,37 +36,28 @@ public class HUDRenderer implements IKeyStateTracker
public static void renderOverlay() {
Minecraft mc = Minecraft.getMinecraft();
if (mc.currentScreen == null &&
mc.theWorld != null &&
!mc.gameSettings.keyBindPlayerList.getIsKeyPressed() &&
NEIClientConfig.getBooleanSetting("world.highlight_tips") &&
mc.objectMouseOver != null &&
mc.objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {
if (mc.currentScreen == null && mc.theWorld != null
&& !mc.gameSettings.keyBindPlayerList.getIsKeyPressed()
&& NEIClientConfig.getBooleanSetting("world.highlight_tips")
&& mc.objectMouseOver != null
&& mc.objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {
World world = mc.theWorld;
ArrayList<ItemStack> items = ItemInfo.getIdentifierItems(world, mc.thePlayer, mc.objectMouseOver);
if (items.isEmpty())
return;
ItemStack[] items = ItemInfo.getIdentifierItems(world, mc.thePlayer, mc.objectMouseOver)
.toArray(new ItemStack[0]);
int minDamage = Integer.MAX_VALUE;
ItemStack stack = null;
for(ItemStack astack : items) {
if(astack.getItem() != null && astack.getItemDamage() < minDamage) {
stack = astack;
minDamage = stack.getItemDamage();
}
}
if (items.length == 0) return;
ItemStack stack = StackInfo.getItemStackWithMinimumDamage(items);
renderOverlay(stack, ItemInfo.getText(stack, world, mc.thePlayer, mc.objectMouseOver), getPositioning());
}
}
public static void renderOverlay(ItemStack stack, List<String> textData, Point pos) {
if((stack == null || stack.getItem() == null) && textData.isEmpty())
return;
if ((stack == null || stack.getItem() == null) && textData.isEmpty()) return;
int w = 0;
for (String s : textData)
w = Math.max(w, getStringWidth(s) + 29);
for (String s : textData) w = Math.max(w, getStringWidth(s) + 29);
int h = Math.max(24, 10 + 10 * textData.size());
Dimension size = displaySize();
@@ -85,8 +78,7 @@ public class HUDRenderer implements IKeyStateTracker
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
if (stack != null && stack.getItem() != null)
GuiContainerManager.drawItem(x + 5, y + h / 2 - 8, stack);
if (stack != null && stack.getItem() != null) GuiContainerManager.drawItem(x + 5, y + h / 2 - 8, stack);
}
private static Point getPositioning() {
@@ -98,4 +90,4 @@ public class HUDRenderer implements IKeyStateTracker
public static void load() {
KeyManager.trackers.add(new HUDRenderer());
}
}
}
+3 -4
View File
@@ -1,14 +1,13 @@
package codechicken.nei;
public class Image
{
public class Image {
public int x;
public int y;
public int width;
public int height;
public Image(int x, int y, int w, int h)
{
public Image(int x, int y, int w, int h) {
this.x = x;
this.y = y;
width = w;
@@ -1,55 +1,47 @@
package codechicken.nei;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.nei.api.IInfiniteItemHandler;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
public class InfiniteStackSizeHandler implements IInfiniteItemHandler
{
import codechicken.lib.inventory.InventoryUtils;
import codechicken.nei.api.IInfiniteItemHandler;
public class InfiniteStackSizeHandler implements IInfiniteItemHandler {
@Override
public void onPickup(ItemStack heldItem)
{
public void onPickup(ItemStack heldItem) {
heldItem.stackSize = 1;
}
@Override
public void onPlaceInfinite(ItemStack heldItem)
{
public void onPlaceInfinite(ItemStack heldItem) {
heldItem.stackSize = 111;
}
@Override
public boolean canHandleItem(ItemStack stack)
{
public boolean canHandleItem(ItemStack stack) {
return !stack.isItemStackDamageable();
}
@Override
public boolean isItemInfinite(ItemStack stack)
{
public boolean isItemInfinite(ItemStack stack) {
return stack.stackSize == -1 || stack.stackSize > 100;
}
@Override
public void replenishInfiniteStack(InventoryPlayer inv, int slotNo)
{
public void replenishInfiniteStack(InventoryPlayer inv, int slotNo) {
ItemStack stack = inv.getStackInSlot(slotNo);
stack.stackSize = 111;
for(int i = 0; i < inv.getSizeInventory(); i++)
{
if(i == slotNo)
continue;
if(NEIServerUtils.areStacksSameType(stack, inv.getStackInSlot(i)))
inv.setInventorySlotContents(i, null);
for (int i = 0; i < inv.getSizeInventory(); i++) {
if (i == slotNo) continue;
if (NEIServerUtils.areStacksSameType(stack, inv.getStackInSlot(i))) inv.setInventorySlotContents(i, null);
}
}
@Override
public ItemStack getInfiniteItem(ItemStack typeStack)
{
public ItemStack getInfiniteItem(ItemStack typeStack) {
return InventoryUtils.copyStack(typeStack, -1);
}
}
@@ -1,11 +1,12 @@
package codechicken.nei;
import codechicken.nei.api.IInfiniteItemHandler;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
public class InfiniteToolHandler implements IInfiniteItemHandler
{
import codechicken.nei.api.IInfiniteItemHandler;
public class InfiniteToolHandler implements IInfiniteItemHandler {
@Override
public void onPickup(ItemStack heldItem) {
heldItem.setItemDamage(0);
@@ -4,15 +4,13 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryCrafting;
public class InventoryCraftingDummy extends InventoryCrafting
{
public InventoryCraftingDummy()
{
super(new Container()
{
public class InventoryCraftingDummy extends InventoryCrafting {
public InventoryCraftingDummy() {
super(new Container() {
@Override
public boolean canInteractWith(EntityPlayer entityplayer)
{
public boolean canInteractWith(EntityPlayer entityplayer) {
return true;
}
}, 3, 3);
+84 -82
View File
@@ -1,16 +1,5 @@
package codechicken.nei;
import codechicken.nei.ThreadOperationTimer.TimeoutException;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
@@ -20,12 +9,25 @@ import java.util.concurrent.ForkJoinPool;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ItemList
{
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import codechicken.nei.ThreadOperationTimer.TimeoutException;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
public class ItemList {
/**
* Fields are replaced atomically and contents never modified.
*/
public static volatile List<ItemStack> items = new ArrayList<>();
public static volatile List<ItemStack> items = new ArrayList<>();
/**
* Fields are replaced atomically and contents never modified.
*/
@@ -34,29 +36,34 @@ public class ItemList
* Updates to this should be synchronised on this
*/
public static final List<ItemFilterProvider> itemFilterers = new LinkedList<>();
public static final List<ItemsLoadedCallback> loadCallbacks = new LinkedList<>();
private static final HashSet<Item> erroredItems = new HashSet<>();
private static final HashSet<String> stackTraces = new HashSet<>();
/**
* Unlike {@link LayoutManager#itemsLoaded}, this indicates whether item loading is actually finished or not.
*/
public static boolean loadFinished;
public static class EverythingItemFilter implements ItemFilter {
public static class EverythingItemFilter implements ItemFilter
{
@Override
public boolean matches(ItemStack item) {
return true;
}
}
public static class NothingItemFilter implements ItemFilter
{
public static class NothingItemFilter implements ItemFilter {
@Override
public boolean matches(ItemStack item) {
return false;
}
}
public static class PatternItemFilter implements ItemFilter
{
public static class PatternItemFilter implements ItemFilter {
public Pattern pattern;
public PatternItemFilter(Pattern pattern) {
@@ -69,8 +76,8 @@ public class ItemList
}
}
public static class AllMultiItemFilter implements ItemFilter
{
public static class AllMultiItemFilter implements ItemFilter {
public List<ItemFilter> filters;
public AllMultiItemFilter(List<ItemFilter> filters) {
@@ -83,19 +90,18 @@ public class ItemList
@Override
public boolean matches(ItemStack item) {
for(ItemFilter filter : filters)
try {
if (!filter.matches(item)) return false;
} catch (Exception e) {
NEIClientConfig.logger.error("Exception filtering "+item+" with "+filter, e);
}
for (ItemFilter filter : filters) try {
if (!filter.matches(item)) return false;
} catch (Exception e) {
NEIClientConfig.logger.error("Exception filtering " + item + " with " + filter, e);
}
return true;
}
}
public static class AnyMultiItemFilter implements ItemFilter
{
public static class AnyMultiItemFilter implements ItemFilter {
public List<ItemFilter> filters;
public AnyMultiItemFilter(List<ItemFilter> filters) {
@@ -108,29 +114,27 @@ public class ItemList
@Override
public boolean matches(ItemStack item) {
for(ItemFilter filter : filters)
try {
if (filter.matches(item)) return true;
} catch (Exception e) {
NEIClientConfig.logger.error("Exception filtering "+item+" with "+filter, e);
}
for (ItemFilter filter : filters) try {
if (filter.matches(item)) return true;
} catch (Exception e) {
NEIClientConfig.logger.error("Exception filtering " + item + " with " + filter, e);
}
return false;
}
}
public static interface ItemsLoadedCallback
{
public static interface ItemsLoadedCallback {
public void itemsLoaded();
}
public static boolean itemMatchesAll(ItemStack item, List<ItemFilter> filters) {
for(ItemFilter filter : filters) {
for (ItemFilter filter : filters) {
try {
if (!filter.matches(item))
return false;
if (!filter.matches(item)) return false;
} catch (Exception e) {
NEIClientConfig.logger.error("Exception filtering "+item+" with "+filter, e);
NEIClientConfig.logger.error("Exception filtering " + item + " with " + filter, e);
}
}
@@ -138,7 +142,7 @@ public class ItemList
}
/**
* @deprecated use getItemListFilter().matches(item)
* @deprecated use getItemListFilter().matches(item)
*/
@Deprecated
public static boolean itemMatches(ItemStack item) {
@@ -152,33 +156,33 @@ public class ItemList
public static List<ItemFilter> getItemFilters() {
LinkedList<ItemFilter> filters = new LinkedList<>();
synchronized (itemFilterers) {
for(ItemFilterProvider p : itemFilterers)
filters.add(p.getFilter());
for (ItemFilterProvider p : itemFilterers) filters.add(p.getFilter());
}
return filters;
}
public static final RestartableTask loadItems = new RestartableTask("NEI Item Loading")
{
public static final RestartableTask loadItems = new RestartableTask("NEI Item Loading") {
private void damageSearch(Item item, List<ItemStack> permutations) {
HashSet<String> damageIconSet = new HashSet<>();
for (int damage = 0; damage < 16; damage++)
try {
ItemStack itemstack = new ItemStack(item, 1, damage);
IIcon icon = item.getIconIndex(itemstack);
String name = GuiContainerManager.concatenatedDisplayName(itemstack, false);
String s = name + "@" + (icon == null ? 0 : icon.hashCode());
if (!damageIconSet.contains(s)) {
damageIconSet.add(s);
permutations.add(itemstack);
}
}
catch(TimeoutException t) {
throw t;
}
catch(Throwable t) {
NEIServerUtils.logOnce(t, stackTraces, "Ommiting "+item+":"+damage+" "+item.getClass().getSimpleName(), item.toString());
for (int damage = 0; damage < 16; damage++) try {
ItemStack itemstack = new ItemStack(item, 1, damage);
IIcon icon = item.getIconIndex(itemstack);
String name = GuiContainerManager.concatenatedDisplayName(itemstack, false);
String s = name + "@" + (icon == null ? 0 : icon.hashCode());
if (!damageIconSet.contains(s)) {
damageIconSet.add(s);
permutations.add(itemstack);
}
} catch (TimeoutException t) {
throw t;
} catch (Throwable t) {
NEIServerUtils.logOnce(
t,
stackTraces,
"Ommiting " + item + ":" + damage + " " + item.getClass().getSimpleName(),
item.toString());
}
}
@Override
@@ -186,6 +190,7 @@ public class ItemList
public void execute() {
// System.out.println("Executing NEI Item Loading");
ThreadOperationTimer timer = getTimer(NEIClientConfig.getItemLoadingTimeout());
loadFinished = false;
LinkedList<ItemStack> items = new LinkedList<>();
LinkedList<ItemStack> permutations = new LinkedList<>();
@@ -195,8 +200,7 @@ public class ItemList
for (Item item : (Iterable<Item>) Item.itemRegistry) {
if (interrupted()) return;
if (item == null || erroredItems.contains(item))
continue;
if (item == null || erroredItems.contains(item)) continue;
try {
timer.reset(item);
@@ -204,11 +208,9 @@ public class ItemList
permutations.clear();
permutations.addAll(ItemInfo.itemOverrides.get(item));
if (permutations.isEmpty())
item.getSubItems(item, null, permutations);
if (permutations.isEmpty()) item.getSubItems(item, null, permutations);
if (permutations.isEmpty())
damageSearch(item, permutations);
if (permutations.isEmpty()) damageSearch(item, permutations);
permutations.addAll(ItemInfo.itemVariants.get(item));
@@ -222,19 +224,19 @@ public class ItemList
}
}
if(interrupted()) return;
if (interrupted()) return;
ItemList.items = items;
ItemList.itemMap = itemMap;
for(ItemsLoadedCallback callback : loadCallbacks)
callback.itemsLoaded();
for (ItemsLoadedCallback callback : loadCallbacks) callback.itemsLoaded();
updateFilter.restart();
loadFinished = true;
}
};
public static ForkJoinPool getPool(int poolSize) {
if(poolSize < 1)
poolSize = 1;
if (poolSize < 1) poolSize = 1;
return new ForkJoinPool(poolSize);
}
@@ -242,8 +244,8 @@ public class ItemList
public static final int numProcessors = Runtime.getRuntime().availableProcessors();
public static ForkJoinPool forkJoinPool = getPool(numProcessors * 2 / 3);
public static final RestartableTask updateFilter = new RestartableTask("NEI Item Filtering")
{
public static final RestartableTask updateFilter = new RestartableTask("NEI Item Filtering") {
@Override
public void execute() {
// System.out.println("Executing NEI Item Filtering");
@@ -251,19 +253,19 @@ public class ItemList
ItemFilter filter = getItemListFilter();
try {
filtered = ItemList.forkJoinPool.submit(() -> items.parallelStream()
.filter(PresetsWidget::matches)
.filter(filter::matches)
.collect(Collectors.toCollection(ArrayList::new))).get();
filtered = ItemList.forkJoinPool.submit(
() -> items.parallelStream().filter(PresetsWidget::matches).filter(filter::matches)
.collect(Collectors.toCollection(ArrayList::new)))
.get();
} catch (InterruptedException | ExecutionException e) {
filtered = new ArrayList<>();
e.printStackTrace();
stop();
}
if(interrupted()) return;
if (interrupted()) return;
ItemSorter.sort(filtered);
if(interrupted()) return;
if (interrupted()) return;
ItemPanel.updateItemList(filtered);
}
};
@@ -1,5 +1,9 @@
package codechicken.nei;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
@@ -16,14 +20,10 @@ import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.client.MinecraftForgeClient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ItemMobSpawner extends ItemBlock {
public class ItemMobSpawner extends ItemBlock
{
private static Map<Integer, EntityLiving> entityHashMap;
private static Map<Integer, String> IDtoNameMap;
private static final Map<Integer, EntityLiving> entityHashMap = new HashMap<>();
private static final Map<Integer, String> IDtoNameMap = new HashMap<>();
public static int idPig;
private static boolean loaded;
@@ -32,15 +32,13 @@ public class ItemMobSpawner extends ItemBlock
hasSubtypes = true;
MinecraftForgeClient.registerItemRenderer(this, new SpawnerRenderer());
entityHashMap = new HashMap<>();
IDtoNameMap = new HashMap<>();
}
/**
* These are ASM translated from BlockMobSpawner
*/
public static int placedX;
public static int placedY;
public static int placedZ;
@@ -49,9 +47,11 @@ public class ItemMobSpawner extends ItemBlock
return Blocks.mob_spawner.getBlockTextureFromSide(0);
}
public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int x, int y, int z, int par7, float par8, float par9, float par10) {
public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int x, int y, int z, int par7,
float par8, float par9, float par10) {
if (super.onItemUse(itemstack, entityplayer, world, x, y, z, par7, par8, par9, par10) && world.isRemote) {
TileEntityMobSpawner tileentitymobspawner = (TileEntityMobSpawner) world.getTileEntity(placedX, placedY, placedZ);
TileEntityMobSpawner tileentitymobspawner = (TileEntityMobSpawner) world
.getTileEntity(placedX, placedY, placedZ);
if (tileentitymobspawner != null) {
setDefaultTag(itemstack);
String mobtype = IDtoNameMap.get(itemstack.getItemDamage());
@@ -83,12 +83,11 @@ public class ItemMobSpawner extends ItemBlock
loadSpawners(world);
Class<?> clazz = (Class<?>) EntityList.IDtoClassMapping.get(ID);
try {
e = (EntityLiving) clazz.getConstructor(new Class[]{World.class}).newInstance(world);
e = (EntityLiving) clazz.getConstructor(new Class[] { World.class }).newInstance(world);
} catch (Throwable t) {
if(clazz == null)
NEIClientConfig.logger.error("Null class for entity ("+ID+", "+IDtoNameMap.get(ID));
else
NEIClientConfig.logger.error("Error creating instance of entity: " + clazz.getName(), t);
if (clazz == null)
NEIClientConfig.logger.error("Null class for entity (" + ID + ", " + IDtoNameMap.get(ID));
else NEIClientConfig.logger.error("Error creating instance of entity: " + clazz.getName(), t);
e = getEntity(idPig);
}
entityHashMap.put(ID, e);
@@ -96,9 +95,12 @@ public class ItemMobSpawner extends ItemBlock
return e;
}
public static void clearEntityReferences(World newWorld) {
entityHashMap.values().removeIf(e -> e.worldObj != newWorld);
}
private void setDefaultTag(ItemStack itemstack) {
if (!IDtoNameMap.containsKey(itemstack.getItemDamage()))
itemstack.setItemDamage(idPig);
if (!IDtoNameMap.containsKey(itemstack.getItemDamage())) itemstack.setItemDamage(idPig);
}
public static void loadSpawners(World world) {
@@ -107,35 +109,30 @@ public class ItemMobSpawner extends ItemBlock
HashMap<Class<Entity>, String> classToStringMapping = (HashMap<Class<Entity>, String>) EntityList.classToStringMapping;
HashMap<Class<Entity>, Integer> classToIDMapping = (HashMap<Class<Entity>, Integer>) EntityList.classToIDMapping;
for (Class<Entity> eclass : classToStringMapping.keySet()) {
if (!EntityLiving.class.isAssignableFrom(eclass))
continue;
if (!EntityLiving.class.isAssignableFrom(eclass)) continue;
try {
EntityLiving entityliving = (EntityLiving) eclass.getConstructor(new Class[]{World.class}).newInstance(world);
EntityLiving entityliving = (EntityLiving) eclass.getConstructor(new Class[] { World.class })
.newInstance(world);
entityliving.isChild();
int id = classToIDMapping.get(eclass);
String name = classToStringMapping.get(eclass);
if (name.equals("EnderDragon"))
continue;
if (name.equals("EnderDragon")) continue;
IDtoNameMap.put(id, name);
if (name.equals("Pig"))
idPig = id;
} catch (Throwable ignored) {
}
if (name.equals("Pig")) idPig = id;
} catch (Throwable ignored) {}
}
IDtoNameMap.entrySet().removeIf(e -> getEntity(e.getKey()).getClass() == EntityPig.class && !e.getValue().equals("Pig"));
IDtoNameMap.entrySet()
.removeIf(e -> getEntity(e.getKey()).getClass() == EntityPig.class && !e.getValue().equals("Pig"));
}
@Override
public void getSubItems(Item item, CreativeTabs tab, List list) {
if(!NEIClientConfig.hasSMPCounterPart())
list.add(new ItemStack(item));
else
for(int i : IDtoNameMap.keySet())
list.add(new ItemStack(item, 1, i));
if (!NEIClientConfig.hasSMPCounterPart()) list.add(new ItemStack(item));
else for (int i : IDtoNameMap.keySet()) list.add(new ItemStack(item, 1, i));
}
}
+133 -471
View File
@@ -1,40 +1,22 @@
package codechicken.nei;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
import codechicken.nei.recipe.StackInfo;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import static codechicken.lib.gui.GuiDraw.drawRect;
import static codechicken.nei.LayoutManager.searchField;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class ItemPanel extends Widget
{
import javax.annotation.Nullable;
public ItemStack draggedStack;
public int mouseDownSlot = -1;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
public Button pagePrev;
public Button pageNext;
public Label pageLabel;
import codechicken.lib.vec.Rectangle4i;
public class ItemPanel extends PanelWidget {
/**
* Backwards compat :-/
* Backwards compat :-/
*/
@SuppressWarnings("unused")
@Deprecated
private int itemsPerPage = 0;
@@ -44,225 +26,190 @@ public class ItemPanel extends Widget
@Deprecated
public ArrayList<ItemStack> realItems = new ArrayList<>();
protected Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
public ItemStack getStackMouseOver(int mousex, int mousey) {
// *looks angrily at AppleCore*
return super.getStackMouseOver(mousex, mousey);
}
public Button more;
public Button less;
public ItemQuantityField quantity;
public static class ItemPanelSlot {
public static class ItemPanelSlot
{
public ItemStack item;
public int slotIndex;
public ItemPanelSlot(int idx, ItemStack stack)
{
public ItemPanelSlot(int idx, ItemStack stack) {
slotIndex = idx;
item = stack;
}
@Deprecated
public ItemPanelSlot(int idx)
{
public ItemPanelSlot(int idx) {
this(idx, ItemPanels.itemPanel.getGrid().getItem(idx));
}
}
protected static class ItemPanelGrid extends ItemsGrid
{
protected static class ItemPanelGrid extends ItemsGrid {
public ArrayList<ItemStack> newItems;
public void setItems(ArrayList<ItemStack> items)
{
public void setItems(ArrayList<ItemStack> items) {
newItems = items;
}
public void refresh(GuiContainer gui)
{
public void refresh(GuiContainer gui) {
if (newItems != null) {
realItems = newItems;
newItems = null;
onGridChanged();
}
super.refresh(gui);
}
@Override
protected void drawItem(Rectangle4i rect, int idx, ItemPanelSlot focus)
{
if (PresetsWidget.inEditMode() && !PresetsWidget.isHidden(getItem(idx))) {
drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555);
protected void drawSlotOutline(@Nullable ItemPanelSlot focused, int slotIdx, Rectangle4i rect) {
if (PresetsWidget.inEditMode()) {
if (!PresetsWidget.isHidden(getItem(slotIdx))) drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555);
} else {
super.drawSlotOutline(focused, slotIdx, rect);
}
super.drawItem(rect, idx, PresetsWidget.inEditMode()? null: focus);
}
@Override
public String getMessageOnEmpty() {
return ItemList.loadFinished ? null : NEIClientUtils.translate("itempanel.loading");
}
}
protected ItemsGrid grid = new ItemPanelGrid();
public ArrayList<ItemStack> getItems()
{
return grid.getItems();
public ItemPanel() {
grid = new ItemPanelGrid();
}
public static void updateItemList(ArrayList<ItemStack> newItems)
{
public static void updateItemList(ArrayList<ItemStack> newItems) {
((ItemPanelGrid) ItemPanels.itemPanel.getGrid()).setItems(newItems);
ItemPanels.itemPanel.realItems = newItems;
}
@Override
public void init() {
super.init();
more = new Button("+") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (rightclick) return false;
int modifier = NEIClientUtils.controlKey() ? 64 : NEIClientUtils.shiftKey() ? 10 : 1;
int quantity = NEIClientConfig.getItemQuantity() + modifier;
if (quantity < 0) {
quantity = 0;
}
ItemPanels.itemPanel.quantity.setText(Integer.toString(quantity));
return true;
}
};
less = new Button("-") {
@Override
public boolean onButtonPress(boolean rightclick) {
if (rightclick) return false;
int modifier = NEIClientUtils.controlKey() ? -64 : NEIClientUtils.shiftKey() ? -10 : -1;
int quantity = NEIClientConfig.getItemQuantity() + modifier;
if (quantity < 0) {
quantity = 0;
}
ItemPanels.itemPanel.quantity.setText(Integer.toString(quantity));
return true;
}
};
quantity = new ItemQuantityField("quantity");
}
@Deprecated
public void scroll(int i)
{
public void scroll(int i) {
grid.shiftPage(i);
}
public ItemsGrid getGrid()
{
return grid;
public String getLabelText() {
return String.format("(%d/%d)", getPage(), Math.max(1, getNumPages()));
}
public void init() {
pageLabel = new Label("(0/0)", true);
pagePrev = new Button("Prev")
{
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
grid.shiftPage(-1);
return true;
}
return false;
}
@Override
public String getRenderLabel() {
return "<";
}
};
pageNext = new Button("Next")
{
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
grid.shiftPage(1);
return true;
}
return false;
}
@Override
public String getRenderLabel() {
return ">";
}
};
protected String getPositioningSettingName() {
return "world.panels.items";
}
public int getMarginLeft(GuiContainer gui)
{
if (gui instanceof GuiContainerCreative && NEIClientUtils.getGamemode() == 2) {
//then activate creative+ first render creative gui and oly then creative+
return (gui.width + 176) / 2 + 2;
public int getMarginLeft(GuiContainer gui) {
return (gui.width + gui.xSize) / 2 + PADDING;
}
public int getMarginTop(GuiContainer gui) {
return PADDING;
}
public int getWidth(GuiContainer gui) {
return gui.width - (gui.xSize + gui.width) / 2 - PADDING * 2;
}
public int getHeight(GuiContainer gui) {
return gui.height - getMarginTop(gui) - PADDING;
}
protected int resizeFooter(GuiContainer gui) {
if (!NEIClientConfig.showItemQuantityWidget() && NEIClientConfig.isSearchWidgetCentered()) return 0;
final int BUTTON_SIZE = 20;
more.w = less.w = BUTTON_SIZE;
quantity.h = BUTTON_SIZE;
if (NEIClientConfig.isSearchWidgetCentered()) {
more.h = less.h = BUTTON_SIZE;
more.x = x + w - BUTTON_SIZE;
more.y = less.y = quantity.y = y + h - BUTTON_SIZE;
less.x = x;
quantity.x = x + BUTTON_SIZE + 2;
quantity.w = more.x - quantity.x - 2;
} else {
quantity.x = (int) (x + (w * 0.7)) + 3;
quantity.y = y + h - BUTTON_SIZE;
quantity.w = (int) ((w * 0.3) - BUTTON_SIZE - 1);
more.h = less.h = BUTTON_SIZE / 2;
more.y = y + h - (more.h * 2);
less.x = more.x = quantity.x + quantity.w;
less.y = more.y + more.h;
}
return (gui.width + gui.xSize) / 2 + 2;
}
public int getMarginTop(GuiContainer gui)
{
return 2;
}
public int getWidth(GuiContainer gui)
{
return LayoutManager.getSideWidth(gui) - getMarginLeft(gui);
}
public int getHeight(GuiContainer gui)
{
// - 19 = 2 + 16 + 1 -> input in bottom
return gui.height - getMarginTop(gui) - 19;
}
public String getLabelText()
{
return "(" + getPage() + "/" + Math.max(1, getNumPages()) + ")";
}
public void resize(GuiContainer gui)
{
final int marginLeft = getMarginLeft(gui);
final int marginTop = getMarginTop(gui);
final int width = getWidth(gui);
final int height = getHeight(gui);
final int buttonHeight = 16;
final int buttonWidth = 16;
pagePrev.w = pageNext.w = buttonWidth;
pagePrev.h = pageNext.h = buttonHeight;
pagePrev.y = pageNext.y = marginTop;
pagePrev.x = marginLeft;
pageNext.x = marginLeft + width - buttonWidth;
pageLabel.x = marginLeft + width / 2;
pageLabel.y = marginTop + 5;
pageLabel.text = getLabelText();
y = marginTop + buttonHeight + 2;
x = marginLeft;
w = width;
h = height - buttonHeight - 2;
grid.setGridSize(x, y, w, h);
grid.refresh(gui);
}
public void setVisible()
{
LayoutManager.addWidget(pagePrev);
LayoutManager.addWidget(pageNext);
LayoutManager.addWidget(pageLabel);
return BUTTON_SIZE + 2;
}
@Override
public void draw(int mousex, int mousey)
{
grid.draw(mousex, mousey);
}
public void setVisible() {
super.setVisible();
@Override
public void postDraw(int mousex, int mousey) {
if (draggedStack != null) {
GuiContainerManager.drawItems.zLevel += 100;
GuiContainerManager.drawItem(mousex - 8, mousey - 8, draggedStack, true);
GuiContainerManager.drawItems.zLevel -= 100;
if (grid.getPerPage() > 0 && NEIClientConfig.showItemQuantityWidget()) {
LayoutManager.addWidget(more);
LayoutManager.addWidget(less);
LayoutManager.addWidget(quantity);
}
}
@Override
public void mouseDragged(int mousex, int mousey, int button, long heldTime) {
if (mouseDownSlot >= 0 && draggedStack == null && NEIClientUtils.getHeldItem() == null &&
NEIClientConfig.hasSMPCounterPart() && !GuiInfo.hasCustomSlots(NEIClientUtils.getGuiContainer())) {
ItemPanelSlot mouseOverSlot = getSlotMouseOver(mousex, mousey);
if (mouseOverSlot == null || mouseOverSlot.slotIndex != mouseDownSlot || heldTime > 500) {
draggedStack = getDraggedStackWithQuantity(mouseDownSlot);
mouseDownSlot = -1;
}
}
}
protected ItemStack getDraggedStackWithQuantity(int mouseDownSlot)
{
protected ItemStack getDraggedStackWithQuantity(int mouseDownSlot) {
ItemStack stack = grid.getItem(mouseDownSlot);
if (stack != null) {
int amount = NEIClientConfig.getItemQuantity();
int amount = NEIClientConfig.showItemQuantityWidget() ? NEIClientConfig.getItemQuantity() : 0;
if (amount == 0) {
amount = stack.getMaxStackSize();
@@ -273,289 +220,4 @@ public class ItemPanel extends Widget
return null;
}
@Override
public boolean handleClick(int mousex, int mousey, int button)
{
if (handleClickExt(mousex, mousey, button))
return true;
if (NEIClientUtils.getHeldItem() != null) {
if (!grid.contains(mousex, mousey)) {
return false;
}
if (NEIClientConfig.canPerformAction("delete") && NEIClientConfig.canPerformAction("item"))
if (button == 1)
NEIClientUtils.decreaseSlotStack(-999);
else
NEIClientUtils.deleteHeldItem();
else
NEIClientUtils.dropHeldItem();
return true;
}
ItemPanelSlot hoverSlot = getSlotMouseOver(mousex, mousey);
if (hoverSlot != null) {
if (button == 2) {
if (hoverSlot.item != null) {
draggedStack = getDraggedStackWithQuantity(hoverSlot.slotIndex);
}
} else {
mouseDownSlot = hoverSlot.slotIndex;
}
return true;
}
return false;
}
@Override
public boolean handleClickExt(int mouseX, int mouseY, int button)
{
if (ItemPanels.itemPanel.draggedStack != null) {
return ItemPanels.itemPanel.handleDraggedClick(mouseX, mouseY, button);
}
if (ItemPanels.bookmarkPanel.draggedStack != null) {
return ItemPanels.bookmarkPanel.handleDraggedClick(mouseX, mouseY, button);
}
return false;
}
protected boolean handleDraggedClick(int mouseX, int mouseY, int button)
{
if (draggedStack == null) {
return false;
}
if (handleFillFluidContainerClick(mouseX, mouseY, button)) {
return true;
}
if (handleSearchInputClick(mouseX, mouseY, button)) {
return true;
}
if (handleGUIContainerClick(mouseX, mouseY, button)) {
return true;
}
if (handleCheatItemClick(mouseX, mouseY, button)) {
return true;
}
final GuiContainer gui = NEIClientUtils.getGuiContainer();
if (mouseX < gui.guiLeft || mouseY < gui.guiTop || mouseX >= gui.guiLeft + gui.xSize || mouseY >= gui.guiTop + gui.ySize) {
draggedStack = null;
}
return true;
}
protected boolean handleFillFluidContainerClick(int mouseX, int mouseY, int button)
{
if (button == 2) {
return false;
}
ItemPanelSlot mouseOverSlot = ItemPanels.itemPanel.getSlotMouseOver(mouseX, mouseY);
if (mouseOverSlot == null) {
mouseOverSlot = ItemPanels.bookmarkPanel.getSlotMouseOver(mouseX, mouseY);
}
if (mouseOverSlot != null && draggedStack.getItem() instanceof IFluidContainerItem) {
FluidStack fluidStack = StackInfo.getFluid(mouseOverSlot.item);
if (fluidStack != null) {
final int stackSize = draggedStack.stackSize;
fluidStack = fluidStack.copy();
if (fluidStack.amount == 0) {
fluidStack.amount = 1000;
}
if (mouseOverSlot.item.stackSize > 1) {
fluidStack.amount *= mouseOverSlot.item.stackSize;
}
draggedStack.stackSize = 1;
((IFluidContainerItem) draggedStack.getItem()).fill(draggedStack, fluidStack, true);
draggedStack.stackSize = stackSize;
if (button == 1 && ((IFluidContainerItem) draggedStack.getItem()).getFluid(draggedStack) != null) {
ItemPanels.bookmarkPanel.addOrRemoveItem(draggedStack.copy());
}
}
return true;
}
return false;
}
protected boolean handleGUIContainerClick(int mouseX, int mouseY, int button)
{
final GuiContainer gui = NEIClientUtils.getGuiContainer();
boolean handled = false;
try {
GuiInfo.readLock.lock();
for (INEIGuiHandler handler : GuiInfo.guiHandlers) {
if (handler.handleDragNDrop(gui, mouseX, mouseY, draggedStack, button)) {
handled = true;
break;
}
}
} finally {
GuiInfo.readLock.unlock();
}
if (draggedStack.stackSize == 0) {
draggedStack = null;
}
return handled;
}
protected boolean handleCheatItemClick(int mouseX, int mouseY, int button)
{
final GuiContainer gui = NEIClientUtils.getGuiContainer();
final Slot overSlot = gui.getSlotAtPosition(mouseX, mouseY);
if (overSlot != null && overSlot.isItemValid(draggedStack)) {
if (NEIClientConfig.canCheatItem(draggedStack)) {
int contents = overSlot.getHasStack() ? overSlot.getStack().stackSize : 0;
final int add = button == 0 ? draggedStack.stackSize : 1;
if (overSlot.getHasStack() && !NEIServerUtils.areStacksSameType(draggedStack, overSlot.getStack())) {
contents = 0;
}
final int total = Math.min(contents + add, Math.min(overSlot.getSlotStackLimit(), draggedStack.getMaxStackSize()));
if (total > contents) {
NEIClientUtils.setSlotContents(overSlot.slotNumber, NEIServerUtils.copyStack(draggedStack, total), true);
NEICPH.sendGiveItem(NEIServerUtils.copyStack(draggedStack, total), false, false);
draggedStack.stackSize -= total - contents;
}
if (draggedStack.stackSize == 0) {
draggedStack = null;
}
} else {
draggedStack = null;
}
return true;
}
return false;
}
protected boolean handleSearchInputClick(int mouseX, int mouseY, int button)
{
if (searchField.contains(mouseX, mouseY)) {
final FluidStack fluidStack = StackInfo.getFluid(draggedStack);
if (fluidStack != null) {
searchField.setText(SPECIAL_REGEX_CHARS.matcher(EnumChatFormatting.getTextWithoutFormattingCodes(fluidStack.getLocalizedName())).replaceAll("\\\\$0"));
} else {
searchField.setText(SPECIAL_REGEX_CHARS.matcher(EnumChatFormatting.getTextWithoutFormattingCodes(draggedStack.getDisplayName())).replaceAll("\\\\$0"));
}
return true;
}
return false;
}
@Override
public void mouseUp(int mousex, int mousey, int button) {
ItemPanelSlot hoverSlot = getSlotMouseOver(mousex, mousey);
if (hoverSlot != null && hoverSlot.slotIndex == mouseDownSlot && draggedStack == null) {
ItemStack item = hoverSlot.item;
if (NEIController.manager.window instanceof GuiRecipe || !NEIClientConfig.canCheatItem(item)) {
if (button == 0)
GuiCraftingRecipe.openRecipeGui("item", item);
else if (button == 1)
GuiUsageRecipe.openRecipeGui("item", item);
mouseDownSlot = -1;
return;
}
NEIClientUtils.cheatItem(getDraggedStackWithQuantity(hoverSlot.slotIndex), button, -1);
}
mouseDownSlot = -1;
}
@Override
public boolean onMouseWheel(int i, int mousex, int mousey) {
if (!contains(mousex, mousey))
return false;
grid.shiftPage(-i);
return true;
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
if (keyID == NEIClientConfig.getKeyBinding("gui.next")) {
grid.shiftPage(1);
return true;
}
if (keyID == NEIClientConfig.getKeyBinding("gui.prev")) {
grid.shiftPage(-1);
return true;
}
return false;
}
@Override
public ItemStack getStackMouseOver(int mousex, int mousey) {
ItemPanelSlot slot = getSlotMouseOver(mousex, mousey);
return slot == null ? null : slot.item;
}
public ItemPanelSlot getSlotMouseOver(int mousex, int mousey)
{
return grid.getSlotMouseOver(mousex, mousey);
}
public int getPage() {
return grid.page + 1;
}
public int getNumPages() {
return grid.numPages;
}
@Override
public boolean contains(int px, int py)
{
return grid.contains(px, py);
}
}
@@ -1,6 +1,7 @@
package codechicken.nei;
public class ItemPanels {
public static final ItemPanel itemPanel = new ItemPanel();
public static final BookmarkPanel bookmarkPanel = new BookmarkPanel();
}
@@ -1,10 +1,13 @@
package codechicken.nei;
public class ItemQuantityField extends TextField
{
import static codechicken.nei.NEIClientUtils.translate;
public class ItemQuantityField extends TextField {
public ItemQuantityField(String ident) {
super(ident);
centered = true;
field.setDisabledTextColour(0xFF303030);
}
public int intValue() {
@@ -35,4 +38,18 @@ public class ItemQuantityField extends TextField
public void onTextChange(String oldText) {
NEIClientUtils.setItemQuantity(intValue());
}
@Override
public void draw(int mousex, int mousey) {
if (!focused() && intValue() == 0) {
field.setText(translate("itempanel.quantity.default"));
field.setEnabled(false);
super.draw(mousex, mousey);
field.setEnabled(true);
field.setText("0");
} else {
super.draw(mousex, mousey);
}
}
}
+33 -38
View File
@@ -1,24 +1,25 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import codechicken.lib.config.ConfigTagParent;
import codechicken.nei.ItemList.ItemsLoadedCallback;
import codechicken.nei.api.API;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.config.GuiItemSorter;
import codechicken.nei.config.OptionOpenGui;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback {
public static class SortEntry {
public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
{
public static class SortEntry
{
public final String name;
public final Comparator<ItemStack> comparator;
@@ -32,7 +33,7 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
}
public String getTooltip() {
String tipname = name+".tip";
String tipname = name + ".tip";
String tip = StatCollector.translateToLocal(tipname);
return !tip.equals(tipname) ? tip : null;
}
@@ -42,12 +43,13 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
public static ArrayList<SortEntry> list = new ArrayList<>();
public static final ItemSorter instance = new ItemSorter();
//optimisations
// optimisations
public HashMap<ItemStack, Integer> ordering = null;
public static void sort(ArrayList<ItemStack> items) {
try {
// items = (ArrayList<ItemStack>) items.parallelStream().sorted(instance).collect(Collectors.toList());
// items = (ArrayList<ItemStack>)
// items.parallelStream().sorted(instance).collect(Collectors.toList());
items.sort(instance);
} catch (Exception e) {
NEIClientConfig.logger.error("Exception sorting item list", e);
@@ -56,9 +58,9 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
@Override
public int compare(ItemStack o1, ItemStack o2) {
for(SortEntry e : list) {
for (SortEntry e : list) {
int c = e.comparator.compare(o1, o2);
if(c != 0) return c;
if (c != 0) return c;
}
return 0;
}
@@ -67,15 +69,12 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
public void itemsLoaded() {
HashMap<ItemStack, Integer> newMap = new HashMap<>();
int i = 0;
for(ItemStack stack : ItemList.items)
newMap.put(stack, i++);
for (ItemStack stack : ItemList.items) newMap.put(stack, i++);
ordering = newMap;
}
public static SortEntry find(String name) {
for(SortEntry e : entries)
if(e.name.equals(name))
return e;
for (SortEntry e : entries) if (e.name.equals(name)) return e;
return null;
}
@@ -89,11 +88,11 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
entries.add(e);
ArrayList<SortEntry> nlist = new ArrayList<>(list);
nlist.add(e);
list = nlist;//concurrency
list = nlist; // concurrency
}
public static void initConfig(ConfigTagParent tag) {
//minecraft, mod, id, default, meta, name
// minecraft, mod, id, default, meta, name
API.addSortOption("nei.itemsort.minecraft", (o1, o2) -> {
boolean m1 = "minecraft".equals(ItemInfo.itemOwners.get(o1.getItem()));
boolean m2 = "minecraft".equals(ItemInfo.itemOwners.get(o2.getItem()));
@@ -102,8 +101,8 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
API.addSortOption("nei.itemsort.mod", (o1, o2) -> {
String mod1 = ItemInfo.itemOwners.get(o1.getItem());
String mod2 = ItemInfo.itemOwners.get(o2.getItem());
if(mod1 == null) return mod2 == null ? 0 : 1;
if(mod2 == null) return -1;
if (mod1 == null) return mod2 == null ? 0 : 1;
if (mod2 == null) return -1;
return mod1.compareTo(mod2);
});
API.addSortOption("nei.itemsort.id", (o1, o2) -> {
@@ -114,8 +113,8 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
API.addSortOption("nei.itemsort.default", (o1, o2) -> {
Integer order1 = instance.ordering.get(o1);
Integer order2 = instance.ordering.get(o2);
if(order1 == null) return order2 == null ? 0 : 1;
if(order2 == null) return -1;
if (order1 == null) return order2 == null ? 0 : 1;
if (order2 == null) return -1;
return compareInt(order1, order2);
});
API.addSortOption("nei.itemsort.damage", (o1, o2) -> {
@@ -130,6 +129,7 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
});
tag.getTag("inventory.itemsort").setDefaultValue(getSaveString(list));
API.addOption(new OptionOpenGui("inventory.itemsort", GuiItemSorter.class) {
@Override
public void useGlobals() {
super.useGlobals();
@@ -141,27 +141,22 @@ public class ItemSorter implements Comparator<ItemStack>, ItemsLoadedCallback
public static String getSaveString(List<SortEntry> list) {
StringBuilder sb = new StringBuilder();
for(SortEntry e : list) {
if(sb.length() > 0)
sb.append(',');
for (SortEntry e : list) {
if (sb.length() > 0) sb.append(',');
sb.append(e.name);
}
return sb.toString();
}
public static ArrayList<SortEntry> fromSaveString(String s) {
if(s == null)
return new ArrayList<>(entries);
if (s == null) return new ArrayList<>(entries);
ArrayList<SortEntry> list = new ArrayList<>();
for(String s2 : s.split(",")) {
for (String s2 : s.split(",")) {
SortEntry e = find(s2.trim());
if(e != null)
list.add(e);
if (e != null) list.add(e);
}
for(SortEntry e : entries)
if(!list.contains(e))
list.add(e);
for (SortEntry e : entries) if (!list.contains(e)) list.add(e);
return list;
}
+50 -71
View File
@@ -1,26 +1,27 @@
package codechicken.nei;
import com.google.common.base.Objects;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import static codechicken.lib.inventory.InventoryUtils.actualDamage;
import static codechicken.lib.inventory.InventoryUtils.newItemStack;
import static net.minecraftforge.oredict.OreDictionary.WILDCARD_VALUE;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static codechicken.lib.inventory.InventoryUtils.actualDamage;
import static codechicken.lib.inventory.InventoryUtils.newItemStack;
import static net.minecraftforge.oredict.OreDictionary.WILDCARD_VALUE;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import com.google.common.base.Objects;
/**
* A maplike class for ItemStack keys with wildcard damage/NBT. Optimised for lookup
*/
public class ItemStackMap<T>
{
public static class StackMetaKey
{
public class ItemStackMap<T> {
public static class StackMetaKey {
public final int damage;
public final NBTTagCompound tag;
@@ -38,15 +39,14 @@ public class ItemStackMap<T>
}
public boolean equals(Object o) {
if (!(o instanceof StackMetaKey))
return false;
if (!(o instanceof StackMetaKey)) return false;
StackMetaKey t = (StackMetaKey) o;
return damage == t.damage && Objects.equal(tag, t.tag);
}
}
public static class Entry<T>
{
public static class Entry<T> {
public final ItemStack key;
public final T value;
@@ -56,8 +56,8 @@ public class ItemStackMap<T>
}
}
public class DetailMap
{
public class DetailMap {
private boolean hasWildcard;
private T wildcard;
private HashMap<Integer, T> damageMap;
@@ -66,8 +66,7 @@ public class ItemStackMap<T>
private int size;
public T get(ItemStack key) {
if (wildcard != null)
return wildcard;
if (wildcard != null) return wildcard;
if (damageMap != null) {
final T ret = damageMap.get(actualDamage(key));
@@ -77,8 +76,7 @@ public class ItemStackMap<T>
final T ret = tagMap.get(key.stackTagCompound);
if (ret != null) return ret;
}
if (metaMap != null)
return metaMap.get(new StackMetaKey(key));
if (metaMap != null) return metaMap.get(new StackMetaKey(key));
return null;
}
@@ -129,63 +127,50 @@ public class ItemStackMap<T>
}
private void updateSize() {
int newSize = (hasWildcard ? 1 : 0) +
(metaMap != null ? metaMap.size() : 0) +
(tagMap != null ? tagMap.size() : 0) +
(damageMap != null ? damageMap.size() : 0);
int newSize = (hasWildcard ? 1 : 0) + (metaMap != null ? metaMap.size() : 0)
+ (tagMap != null ? tagMap.size() : 0)
+ (damageMap != null ? damageMap.size() : 0);
if(newSize != size) {
ItemStackMap.this.size += newSize-size;
if (newSize != size) {
ItemStackMap.this.size += newSize - size;
size = newSize;
}
}
public void addKeys(Item item, List<ItemStack> list) {
if (wildcard != null)
list.add(wildcard(item));
if (wildcard != null) list.add(wildcard(item));
if (damageMap != null)
for (int damage : damageMap.keySet())
list.add(newItemStack(item, 1, damage, WILDCARD_TAG));
for (int damage : damageMap.keySet()) list.add(newItemStack(item, 1, damage, WILDCARD_TAG));
if (tagMap != null)
for (NBTTagCompound tag : tagMap.keySet())
list.add(newItemStack(item, 1, WILDCARD_VALUE, tag));
for (NBTTagCompound tag : tagMap.keySet()) list.add(newItemStack(item, 1, WILDCARD_VALUE, tag));
if (metaMap != null)
for (StackMetaKey key : metaMap.keySet())
list.add(newItemStack(item, 1, key.damage, key.tag));
for (StackMetaKey key : metaMap.keySet()) list.add(newItemStack(item, 1, key.damage, key.tag));
}
public void addValues(List<T> list) {
if (wildcard != null)
list.add(wildcard);
if (damageMap != null)
list.addAll(damageMap.values());
if (tagMap != null)
list.addAll(tagMap.values());
if (metaMap != null)
list.addAll(metaMap.values());
if (wildcard != null) list.add(wildcard);
if (damageMap != null) list.addAll(damageMap.values());
if (tagMap != null) list.addAll(tagMap.values());
if (metaMap != null) list.addAll(metaMap.values());
}
public void addEntries(Item item, List<Entry<T>> list) {
if (wildcard != null)
list.add(new Entry<>(newItemStack(item, 1, WILDCARD_VALUE, WILDCARD_TAG), wildcard));
if (damageMap != null)
for (Map.Entry<Integer, T> entry : damageMap.entrySet())
list.add(new Entry<>(newItemStack(item, 1, entry.getKey(), WILDCARD_TAG), entry.getValue()));
if (tagMap != null)
for (Map.Entry<NBTTagCompound, T> entry : tagMap.entrySet())
list.add(new Entry<>(newItemStack(item, 1, WILDCARD_VALUE, entry.getKey()), entry.getValue()));
if (metaMap != null)
for (Map.Entry<StackMetaKey, T> entry : metaMap.entrySet())
list.add(new Entry<>(newItemStack(item, 1, entry.getKey().damage, entry.getKey().tag), entry.getValue()));
if (wildcard != null) list.add(new Entry<>(newItemStack(item, 1, WILDCARD_VALUE, WILDCARD_TAG), wildcard));
if (damageMap != null) for (Map.Entry<Integer, T> entry : damageMap.entrySet())
list.add(new Entry<>(newItemStack(item, 1, entry.getKey(), WILDCARD_TAG), entry.getValue()));
if (tagMap != null) for (Map.Entry<NBTTagCompound, T> entry : tagMap.entrySet())
list.add(new Entry<>(newItemStack(item, 1, WILDCARD_VALUE, entry.getKey()), entry.getValue()));
if (metaMap != null) for (Map.Entry<StackMetaKey, T> entry : metaMap.entrySet()) list.add(
new Entry<>(newItemStack(item, 1, entry.getKey().damage, entry.getKey().tag), entry.getValue()));
}
}
public static int getKeyType(int damage, NBTTagCompound tag) {
int i = 0;
if (isWildcard(damage)) i = 1;
if (isWildcard(tag)) i |= 2;
return i;
}
int i = 0;
if (isWildcard(damage)) i = 1;
if (isWildcard(tag)) i |= 2;
return i;
}
public static ItemStack wildcard(Item item) {
return newItemStack(item, 1, WILDCARD_VALUE, WILDCARD_TAG);
@@ -219,12 +204,10 @@ public class ItemStackMap<T>
}
public void put(ItemStack key, T value) {
if (key == null || key.getItem() == null)
return;
if (key == null || key.getItem() == null) return;
DetailMap map = itemMap.get(key.getItem());
if (map == null)
itemMap.put(key.getItem(), map = new DetailMap());
if (map == null) itemMap.put(key.getItem(), map = new DetailMap());
map.put(key, value);
}
@@ -233,8 +216,7 @@ public class ItemStackMap<T>
}
public T remove(ItemStack key) {
if (key == null || key.getItem() == null)
return null;
if (key == null || key.getItem() == null) return null;
DetailMap map = itemMap.get(key.getItem());
return map == null ? null : map.remove(key);
@@ -242,22 +224,19 @@ public class ItemStackMap<T>
public List<ItemStack> keys() {
LinkedList<ItemStack> list = new LinkedList<>();
for (Map.Entry<Item, DetailMap> entry : itemMap.entrySet())
entry.getValue().addKeys(entry.getKey(), list);
for (Map.Entry<Item, DetailMap> entry : itemMap.entrySet()) entry.getValue().addKeys(entry.getKey(), list);
return list;
}
public List<T> values() {
LinkedList<T> list = new LinkedList<>();
for (DetailMap map : itemMap.values())
map.addValues(list);
for (DetailMap map : itemMap.values()) map.addValues(list);
return list;
}
public List<Entry<T>> entries() {
LinkedList<Entry<T>> list = new LinkedList<>();
for (Map.Entry<Item, DetailMap> entry : itemMap.entrySet())
entry.getValue().addEntries(entry.getKey(), list);
for (Map.Entry<Item, DetailMap> entry : itemMap.entrySet()) entry.getValue().addEntries(entry.getKey(), list);
return list;
}
@@ -1,27 +1,25 @@
package codechicken.nei;
import codechicken.nei.api.ItemFilter;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class ItemStackSet extends ItemStackMap<ItemStack> implements ItemFilter
{
import codechicken.nei.api.ItemFilter;
public class ItemStackSet extends ItemStackMap<ItemStack> implements ItemFilter {
public ItemStackSet with(ItemStack... items) {
for(ItemStack item : items)
add(item);
for (ItemStack item : items) add(item);
return this;
}
public ItemStackSet with(Item... items) {
for(Item item : items)
add(ItemStackMap.wildcard(item));
for (Item item : items) add(ItemStackMap.wildcard(item));
return this;
}
public ItemStackSet with(Block... blocks) {
for(Block block : blocks)
add(ItemStackMap.wildcard(Item.getItemFromBlock(block)));
for (Block block : blocks) add(ItemStackMap.wildcard(Item.getItemFromBlock(block)));
return this;
}
+367 -106
View File
@@ -1,19 +1,41 @@
package codechicken.nei;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.ItemPanel.ItemPanelSlot;
import static codechicken.lib.gui.GuiDraw.drawRect;
import static codechicken.lib.gui.GuiDraw.getMousePosition;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.shader.Framebuffer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import static codechicken.lib.gui.GuiDraw.drawRect;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemPanel.ItemPanelSlot;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.BookmarkRecipeId;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.StackInfo;
public class ItemsGrid {
public class ItemsGrid
{
public static final int SLOT_SIZE = 18;
protected int width;
@@ -22,40 +44,42 @@ public class ItemsGrid
protected int marginLeft;
protected int marginTop;
protected int paddingLeft;
protected ArrayList<ItemStack> realItems = new ArrayList<>();
protected int page;
protected int perPage;
protected int firstIndex;
protected int numPages;
protected int rows;
protected int columns;
protected boolean showRecipeTooltips = false;
protected boolean[] validSlotMap;
protected boolean[] invalidSlotMap;
public ArrayList<ItemStack> getItems()
{
protected Label messageLabel = new Label(getMessageOnEmpty(), true);
@Nullable
private Framebuffer framebuffer = null;
protected boolean refreshBuffer = true;
public ArrayList<ItemStack> getItems() {
return realItems;
}
public ItemStack getItem(int idx)
{
public ItemStack getItem(int idx) {
return realItems.get(idx);
}
public int size()
{
public int size() {
return realItems.size();
}
public int indexOf(ItemStack stackA, boolean useNBT)
{
public int indexOf(ItemStack stackA, boolean useNBT) {
for (int idx = 0; idx < realItems.size(); idx++) {
if (StackInfo.equalItemAndNBT(stackA, realItems.get(idx), useNBT)) {
if (StackInfo.equalItemAndNBT(stackA, getItem(idx), useNBT)) {
return idx;
}
}
@@ -63,34 +87,36 @@ public class ItemsGrid
return -1;
}
public int getPage()
{
public void setPage(int page) {
this.page = Math.max(0, Math.min(page, getNumPages() - 1));
onGridChanged();
}
public int getPage() {
return page + 1;
}
public int getPerPage()
{
public int getPerPage() {
return perPage;
}
public int getNumPages()
{
return numPages;
public int getNumPages() {
if (perPage > 0) {
return (int) Math.ceil((float) realItems.size() / (float) perPage);
}
return 0;
}
public int getRows()
{
public int getRows() {
return rows;
}
public int getColumns()
{
public int getColumns() {
return columns;
}
public void setGridSize(int mleft, int mtop, int w, int h)
{
public void setGridSize(int mleft, int mtop, int w, int h) {
marginLeft = mleft;
marginTop = mtop;
@@ -100,18 +126,20 @@ public class ItemsGrid
columns = width / SLOT_SIZE;
rows = height / SLOT_SIZE;
paddingLeft = (width % SLOT_SIZE) / 2;
messageLabel.x = marginLeft + width / 2;
messageLabel.y = marginTop + height / 2;
}
public void shiftPage(int shift)
{
public void shiftPage(int shift) {
if (perPage == 0) {
numPages = 0;
page = 0;
return;
}
numPages = (int) Math.ceil((float) realItems.size() / (float) perPage);
final int numPages = getNumPages();
final int oldPage = page;
page += shift;
if (page >= numPages) {
@@ -123,145 +151,378 @@ public class ItemsGrid
}
page = Math.max(0, Math.min(page, numPages - 1));
if (page != oldPage) {
onGridChanged();
}
}
public void refresh(GuiContainer gui)
{
protected void onGridChanged() {
refreshBuffer = true;
}
public void setShowRecipeTooltips(boolean show) {
this.showRecipeTooltips = show;
}
public void refresh(GuiContainer gui) {
updateGuiOverlapSlots(gui);
shiftPage(0);
}
private void updateGuiOverlapSlots(GuiContainer gui)
{
protected void updateGuiOverlapSlots(GuiContainer gui) {
final boolean[] oldSlotMap = invalidSlotMap;
final int oldRows = rows;
final int oldColumns = columns;
invalidSlotMap = new boolean[rows * columns];
perPage = columns * rows;
checkGuiOverlap(gui, 0, columns - 2, 1);
checkGuiOverlap(gui, columns - 1, 1, -1);
if (NEIClientConfig.optimizeGuiOverlapComputation()) {
checkGuiOverlap(gui, 0, columns - 2, 1);
checkGuiOverlap(gui, columns - 1, 1, -1);
} else {
checkGuiOverlap(gui, 0, columns, 1);
}
if (oldRows != rows || oldColumns != columns || !Arrays.equals(oldSlotMap, invalidSlotMap)) {
onGridChanged();
}
}
private void checkGuiOverlap(GuiContainer gui, int start, int end, int dir)
{
private void checkGuiOverlap(GuiContainer gui, int start, int end, int dir) {
boolean validColumn = false;
for (int c = start; c != end && !validColumn; c += dir) {
for (int c = start; c != end && (!NEIClientConfig.optimizeGuiOverlapComputation() || !validColumn); c += dir) {
validColumn = true;
for (int r = 0; r < rows; r++) {
final int idx = columns * r + c;
if (!slotValid(gui, r, c) && idx >= 0 && idx < invalidSlotMap.length && !invalidSlotMap[idx]) {
if (GuiInfo.hideItemPanelSlot(gui, getSlotRect(r, c)) && idx >= 0
&& idx < invalidSlotMap.length
&& !invalidSlotMap[idx]) {
invalidSlotMap[idx] = true;
validColumn = false;
perPage--;
}
}
}
}
private boolean slotValid(GuiContainer gui, int row, int column)
{
Rectangle4i rect = getSlotRect(row, column);
try {
GuiInfo.readLock.lock();
if (GuiInfo.guiHandlers.stream().anyMatch(handler -> handler.hideItemPanelSlot(gui, rect.x, rect.y, rect.w, rect.h))) {
return false;
public Rectangle4i getItemRect(int idx) {
final List<Integer> mask = getMask();
for (int i = 0; i < mask.size(); i++) {
if (mask.get(i) != null && idx == mask.get(i)) {
return getSlotRect(i);
}
} finally {
GuiInfo.readLock.unlock();
}
return true;
return null;
}
public Rectangle4i getSlotRect(int i)
{
public Rectangle4i getSlotRect(int i) {
return getSlotRect(i / columns, i % columns);
}
public Rectangle4i getSlotRect(int row, int column)
{
return new Rectangle4i(marginLeft + (width % SLOT_SIZE) / 2 + column * SLOT_SIZE, marginTop + row * SLOT_SIZE, SLOT_SIZE, SLOT_SIZE);
public Rectangle4i getSlotRect(int row, int column) {
return new Rectangle4i(
marginLeft + paddingLeft + column * SLOT_SIZE,
marginTop + row * SLOT_SIZE,
SLOT_SIZE,
SLOT_SIZE);
}
public boolean isInvalidSlot(int idx)
{
return invalidSlotMap[idx];
public boolean isInvalidSlot(int index) {
return invalidSlotMap[index];
}
public void draw(int mousex, int mousey)
{
if (getPerPage() == 0) {
return;
}
ItemPanelSlot slot = getSlotMouseOver(mousex, mousey);
GuiContainerManager.enableMatrixStackLogging();
protected List<Integer> getMask() {
List<Integer> mask = new ArrayList<>();
int idx = page * perPage;
for (int i = 0; i < rows * columns && idx < size(); i++) {
mask.add(isInvalidSlot(i) ? null : idx++);
}
if (!invalidSlotMap[i]) {
drawItem(getSlotRect(i), idx, slot);
idx ++;
return mask;
}
private void drawSlotOutlines(int mousex, int mousey) {
ItemPanelSlot focused = getSlotMouseOver(mousex, mousey);
final List<Integer> mask = getMask();
for (int i = 0; i < mask.size(); i++) {
if (mask.get(i) != null) {
drawSlotOutline(focused, mask.get(i), getSlotRect(i));
}
}
}
private int recipeTooltipSlotIdx = -1;
private int recipeTooltipLines = 2;
private Runnable recipeTooltipUpdater = null;
private GuiRecipe<?> recipeTooltipGui = null;
public void update() {
if (recipeTooltipUpdater != null) {
recipeTooltipUpdater.run();
recipeTooltipUpdater = null;
}
if (recipeTooltipGui != null) {
recipeTooltipGui.updateAsTooltip();
}
}
private static <T> List<T> listOrEmptyList(final List<T> listOrNull) {
return listOrNull == null ? Collections.emptyList() : listOrNull;
}
private void drawRecipeTooltip(int mousex, int mousey, List<String> itemTooltip) {
if (!NEIClientConfig.isLoaded()) {
return;
}
final Minecraft mc = Minecraft.getMinecraft();
ItemPanelSlot focused = getSlotMouseOver(mousex, mousey);
if (focused == null) {
recipeTooltipSlotIdx = -1;
recipeTooltipGui = null;
return;
}
final List<Integer> mask = getMask();
int slotIdx = -1;
for (int i = 0; i < mask.size(); i++) {
if (mask.get(i) == null) {
continue;
}
if (focused.slotIndex != mask.get(i)) {
continue;
}
slotIdx = i;
break;
}
if (slotIdx == -1) {
recipeTooltipSlotIdx = -1;
recipeTooltipGui = null;
return;
}
final Point mouseover = getMousePosition();
final ItemPanelSlot panelSlot = ItemPanels.bookmarkPanel.getSlotMouseOver(mouseover.x, mouseover.y);
final BookmarkRecipeId recipeId;
if (panelSlot != null) {
recipeId = ItemPanels.bookmarkPanel.getBookmarkRecipeId(panelSlot.slotIndex);
} else {
recipeId = ItemPanels.bookmarkPanel.getBookmarkRecipeId(focused.item);
}
if (recipeId == null) {
return;
}
if (slotIdx != recipeTooltipSlotIdx) {
recipeTooltipSlotIdx = slotIdx;
recipeTooltipGui = null;
recipeTooltipUpdater = () -> {
recipeTooltipGui = GuiCraftingRecipe.createRecipeGui("item", false, false, false, focused.item);
if (recipeTooltipGui != null) {
recipeTooltipGui.limitToOneRecipe();
recipeTooltipGui.initGui(true);
recipeTooltipGui.guiTop = 0;
recipeTooltipGui.guiLeft = 0;
}
recipeTooltipLines = Math.max(1, itemTooltip.size());
};
}
if (recipeTooltipGui == null) {
return;
}
GL11.glPushMatrix();
final float tooltipYOffset;
if (mousey - marginTop > height / 2) {
tooltipYOffset = mousey - recipeTooltipGui.getHeightAsWidget() + 8;
} else {
tooltipYOffset = mousey + ((recipeTooltipLines < 2) ? 1 : 3 + ((recipeTooltipLines - 1) * 10));
}
GL11.glTranslatef(mousex, tooltipYOffset, 500);
final GuiContainer gui;
if (mc.currentScreen instanceof GuiRecipe) {
gui = ((GuiRecipe<?>) mc.currentScreen).firstGui;
} else if (mc.currentScreen instanceof GuiContainer) {
gui = (GuiContainer) mc.currentScreen;
} else {
gui = null;
}
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
RenderHelper.disableStandardItemLighting();
recipeTooltipGui.drawGuiContainerBackgroundLayer(0.0f, -100, -100);
GL11.glPopAttrib();
if (recipeTooltipGui.slotcontainer != null) {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
RenderHelper.enableGUIStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
@SuppressWarnings("unchecked")
List<Slot> slots = (List<Slot>) recipeTooltipGui.slotcontainer.inventorySlots;
for (Slot slot : slots) {
if (slot != null && slot.getStack() != null) {
GuiContainerManager.drawItem(slot.xDisplayPosition, slot.yDisplayPosition, slot.getStack());
}
}
GL11.glPopAttrib();
}
recipeTooltipGui.drawGuiContainerForegroundLayer(-100, -100);
for (GuiButton btn : recipeTooltipGui.getOverlayButtons()) {
btn.drawButton(mc, -100, -100);
}
GL11.glPopMatrix();
}
protected void drawSlotOutline(@Nullable ItemPanelSlot focused, int slotIdx, Rectangle4i rect) {
if (focused != null && focused.slotIndex == slotIdx) {
drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555); // highlight
}
}
private void blitExistingBuffer() {
Minecraft minecraft = Minecraft.getMinecraft();
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
getFrameBuffer().bindFramebufferTexture();
GL11.glEnable(GL11.GL_TEXTURE_2D);
ScaledResolution res = new ScaledResolution(minecraft, minecraft.displayWidth, minecraft.displayHeight);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0, res.getScaledHeight_double(), 0.0, 0, 0);
tessellator.addVertexWithUV(res.getScaledWidth_double(), res.getScaledHeight_double(), 0.0, 1, 0);
tessellator.addVertexWithUV(res.getScaledWidth_double(), 0, 0.0, 1, 1);
tessellator.addVertexWithUV(0, 0, 0, 0, 1);
tessellator.draw();
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
private Framebuffer getFrameBuffer() {
if (framebuffer == null) {
framebuffer = new Framebuffer(1, 1, true);
framebuffer.setFramebufferColor(0.0F, 0.0F, 0.0F, 0.0F);
}
return framebuffer;
}
private void drawItems() {
GuiContainerManager.enableMatrixStackLogging();
final List<Integer> mask = getMask();
for (int i = 0; i < mask.size(); i++) {
if (mask.get(i) != null) {
drawItem(getSlotRect(i), mask.get(i));
}
}
GuiContainerManager.disableMatrixStackLogging();
}
protected void drawItem(Rectangle4i rect, int idx, ItemPanelSlot focus)
{
if (focus != null && focus.slotIndex == idx) {
drawRect(rect.x, rect.y, rect.w, rect.h, 0xee555555);//highlight
public void draw(int mousex, int mousey) {
if (getPerPage() == 0) {
return;
}
if (NEIClientConfig.shouldCacheItemRendering()) {
if (refreshBuffer) {
Minecraft minecraft = Minecraft.getMinecraft();
Framebuffer framebuffer = getFrameBuffer();
framebuffer.createBindFramebuffer(minecraft.displayWidth, minecraft.displayHeight);
framebuffer.framebufferClear();
framebuffer.bindFramebuffer(false);
/* Set up some rendering state needed for items to work correctly */
GL11.glDisable(GL11.GL_BLEND);
GL11.glDepthMask(true);
OpenGlHelper.glBlendFunc(
GL11.GL_SRC_ALPHA,
GL11.GL_ONE_MINUS_SRC_ALPHA,
GL11.GL_SRC_ALPHA,
GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
drawItems();
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
refreshBuffer = false;
}
drawSlotOutlines(mousex, mousey);
blitExistingBuffer();
} else {
drawSlotOutlines(mousex, mousey);
drawItems();
}
}
public void postDrawTooltips(int mousex, int mousey, List<String> tooltip) {
if (NEIClientConfig.showRecipeTooltips() && showRecipeTooltips) {
try {
drawRecipeTooltip(mousex, mousey, tooltip);
} catch (Exception e) {
NEIClientConfig.logger.warn("Cannot draw recipe tooltip", e);
}
}
}
public void setVisible() {
if (getItems().isEmpty() && getMessageOnEmpty() != null) {
LayoutManager.addWidget(messageLabel);
}
}
protected void drawItem(Rectangle4i rect, int idx) {
GuiContainerManager.drawItem(rect.x + 1, rect.y + 1, getItem(idx));
}
public ItemPanelSlot getSlotMouseOver(int mousex, int mousey)
{
public ItemPanelSlot getSlotMouseOver(int mousex, int mousey) {
if (!contains(mousex, mousey)) {
return null;
}
final int overRow = (int) ((mousey - marginTop) / SLOT_SIZE);
final int overColumn = (int) ((mousex - marginLeft - (width % SLOT_SIZE) / 2) / SLOT_SIZE);
final int overColumn = (int) ((mousex - marginLeft - paddingLeft) / SLOT_SIZE);
final int slt = columns * overRow + overColumn;
int idx = page * perPage + slt;
if (overRow >= rows || overColumn >= columns) {
return null;
}
for (int i = 0; i < slt; i++) {
if (invalidSlotMap[i]) {
idx--;
}
final List<Integer> mask = getMask();
if (mask.size() > slt && mask.get(slt) != null) {
final int idx = mask.get(slt);
return new ItemPanelSlot(idx, getItem(idx));
}
return idx < size()? new ItemPanelSlot(idx, realItems.get(idx)): null;
return null;
}
public boolean contains(int px, int py)
{
public boolean contains(int px, int py) {
if (!(new Rectangle4i(marginLeft, marginTop, width, height)).contains(px, py)) {
if (!(new Rectangle4i(marginLeft + paddingLeft, marginTop, columns * SLOT_SIZE, height)).contains(px, py)) {
return false;
}
final int r = (int) ((py - marginTop) / SLOT_SIZE);
final int c = (int) ((px - marginLeft - (width % SLOT_SIZE) / 2) / SLOT_SIZE);
final int c = (int) ((px - marginLeft - paddingLeft) / SLOT_SIZE);
final int slt = columns * r + c;
return r >= rows || c >= columns || !invalidSlotMap[slt];
return r >= rows || c >= columns || !isInvalidSlot(slt);
}
}
public String getMessageOnEmpty() {
return null;
}
}
+19 -26
View File
@@ -1,7 +1,5 @@
package codechicken.nei;
import org.lwjgl.input.Keyboard;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
@@ -9,44 +7,39 @@ import java.util.Map.Entry;
/**
* Good old down/held/up keystate tracker
*/
public class KeyManager
{
public static interface IKeyStateTracker
{
public class KeyManager {
public static interface IKeyStateTracker {
public void tickKeyStates();
}
public static class KeyState
{
public static class KeyState {
public boolean down;
public boolean held;
public boolean up;
}
public static HashMap<String, KeyState> keyStates = new HashMap<>();
public static LinkedList<IKeyStateTracker> trackers = new LinkedList<>();
public static void tickKeyStates()
{
for(Entry<String, KeyState> entry : keyStates.entrySet())
{
int keyCode = NEIClientConfig.getKeyBinding(entry.getKey());
boolean down = keyCode != 0 && Keyboard.isKeyDown(keyCode);
KeyState state = entry.getValue();
if(down)
{
public static void tickKeyStates() {
for (Entry<String, KeyState> entry : keyStates.entrySet()) {
final boolean down = NEIClientConfig.isKeyHashDown(entry.getKey());
final KeyState state = entry.getValue();
if (down) {
state.down = !state.held;
state.up = false;
}
else
{
} else {
state.up = state.held;
state.down = false;
}
state.held = down;
}
for(IKeyStateTracker tracker : trackers)
tracker.tickKeyStates();
for (IKeyStateTracker tracker : trackers) tracker.tickKeyStates();
}
}
+10 -15
View File
@@ -3,30 +3,25 @@ package codechicken.nei;
import static codechicken.lib.gui.GuiDraw.drawString;
import static codechicken.lib.gui.GuiDraw.drawStringC;
public class Label extends Widget
{
public class Label extends Widget {
final boolean centered;
final int colour;
public String text;
public Label(String s, boolean center, int color)
{
public Label(String s, boolean center, int color) {
text = s;
centered = center;
colour = color;
}
public Label(String s, boolean center)
{
public Label(String s, boolean center) {
this(s, center, 0xFFFFFFFF);
}
@Override
public void draw(int mousex, int mousey)
{
if(centered)
drawStringC(text, x, y, colour);
else
drawString(text, x, y, colour);
public void draw(int mousex, int mousey) {
if (centered) drawStringC(text, x, y, colour);
else drawString(text, x, y, colour);
}
}
+218 -274
View File
@@ -1,44 +1,10 @@
package codechicken.nei;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.KeyManager.IKeyStateTracker;
import codechicken.nei.api.API;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IRecipeOverlayRenderer;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.api.LayoutStyle;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerDrawHandler;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerObjectHandler;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.RecipeCatalysts;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import static codechicken.lib.gui.GuiDraw.changeTexture;
import static codechicken.lib.gui.GuiDraw.drawRect;
import static codechicken.lib.gui.GuiDraw.drawTexturedModalRect;
import static codechicken.nei.NEIClientConfig.canPerformAction;
import static codechicken.nei.NEIClientConfig.disabledActions;
import static codechicken.nei.NEIClientConfig.getItemQuantity;
import static codechicken.nei.NEIClientConfig.getKeyBinding;
import static codechicken.nei.NEIClientConfig.getOptionList;
import static codechicken.nei.NEIClientConfig.getSearchExpression;
import static codechicken.nei.NEIClientConfig.hasSMPCounterPart;
@@ -49,7 +15,6 @@ import static codechicken.nei.NEIClientConfig.isHidden;
import static codechicken.nei.NEIClientConfig.showIDs;
import static codechicken.nei.NEIClientConfig.toggleBooleanSetting;
import static codechicken.nei.NEIClientConfig.world;
import static codechicken.nei.NEIClientUtils.controlKey;
import static codechicken.nei.NEIClientUtils.cycleGamemode;
import static codechicken.nei.NEIClientUtils.decreaseSlotStack;
import static codechicken.nei.NEIClientUtils.deleteEverything;
@@ -67,8 +32,43 @@ import static codechicken.nei.NEIClientUtils.toggleMagnetMode;
import static codechicken.nei.NEIClientUtils.toggleRaining;
import static codechicken.nei.NEIClientUtils.translate;
public class LayoutManager implements IContainerInputHandler, IContainerTooltipHandler, IContainerDrawHandler, IContainerObjectHandler, IKeyStateTracker
{
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.KeyManager.IKeyStateTracker;
import codechicken.nei.api.API;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IRecipeOverlayRenderer;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.api.LayoutStyle;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerDrawHandler;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerObjectHandler;
import codechicken.nei.guihook.IContainerTooltipHandler;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.RecipeCatalysts;
public class LayoutManager implements IContainerInputHandler, IContainerTooltipHandler, IContainerDrawHandler,
IContainerObjectHandler, IKeyStateTracker {
private static LayoutManager instance;
/** Note: this variable isn't actually used by this mod, but NEI add-ons might need it. */
@@ -77,23 +77,28 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
/**
* Sorted bottom first
*/
private static TreeSet<Widget> drawWidgets;
private static TreeSet<Widget> drawWidgets = new TreeSet<>(new WidgetZOrder(false));
/**
* Sorted top first
*/
private static TreeSet<Widget> controlWidgets;
private static TreeSet<Widget> controlWidgets = new TreeSet<>(new WidgetZOrder(true));
public static ItemPanel itemPanel;
public static BookmarkPanel bookmarkPanel;
public static SubsetWidget dropDown;
public static PresetsWidget presetsPanel;
public static TextField searchField;
public static SearchField searchField;
public static ButtonCycled options;
public static ButtonCycled bookmarksButton;
@Deprecated
public static Button more;
@Deprecated
public static Button less;
@Deprecated
public static ItemQuantityField quantity;
public static Button delete;
@@ -107,6 +112,11 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
public static HashMap<Integer, LayoutStyle> layoutStyles = new HashMap<>();
/**
* This is set to true immediately after item loading thread is started, to prevent duplicated loading thread from
* being executed. If you want to know if item list is actually finished loading, Use {@link ItemList#loadFinished}
* instead.
*/
public static boolean itemsLoaded = false;
/**
@@ -128,7 +138,9 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public void onPreDraw(GuiContainer gui) {
if (!isHidden() && isEnabled() && gui instanceof InventoryEffectRenderer)//Reset the gui to the center of the screen, for potion effect offsets etc
if (!isHidden() && isEnabled() && gui instanceof InventoryEffectRenderer) // Reset the gui to the center of the
// screen, for potion effect offsets
// etc
{
gui.guiLeft = (gui.width - gui.xSize) / 2;
gui.guiTop = (gui.height - gui.ySize) / 2;
@@ -142,33 +154,33 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
}
@Deprecated
public static int getSideWidth(GuiContainer gui) {
return gui.width - 3;
}
@Deprecated
public static int getLeftSize(GuiContainer gui) {
return getSideWidth(gui);
}
@Override
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
if (isHidden())
return;
if (isHidden()) return;
for (Widget widget : controlWidgets)
widget.onGuiClick(mousex, mousey);
for (Widget widget : controlWidgets) widget.onGuiClick(mousex, mousey);
}
@Override
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
if (isHidden())
return false;
if (isHidden()) return false;
if (!isEnabled())
return options.contains(mousex, mousey) && options.handleClick(mousex, mousey, button);
if (!isEnabled()) return options.contains(mousex, mousey) && options.handleClick(mousex, mousey, button);
for (Widget widget : controlWidgets) {
widget.onGuiClick(mousex, mousey);
if (widget.contains(mousex, mousey) ? widget.handleClick(mousex, mousey, button) : widget.handleClickExt(mousex, mousey, button))
if (widget.contains(mousex, mousey) ? widget.handleClick(mousex, mousey, button)
: widget.handleClickExt(mousex, mousey, button))
return true;
}
@@ -178,61 +190,63 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public boolean objectUnderMouse(GuiContainer gui, int mousex, int mousey) {
if (!isHidden() && isEnabled())
for (Widget widget : drawWidgets)
if (widget.contains(mousex, mousey))
return true;
for (Widget widget : drawWidgets) if (widget.contains(mousex, mousey)) return true;
return false;
}
public boolean keyTyped(GuiContainer gui, char keyChar, int keyID) {
if (isEnabled() && !isHidden()) {
if (inputFocused != null)
return inputFocused.handleKeyPress(keyID, keyChar);
if (inputFocused != null) return inputFocused.handleKeyPress(keyID, keyChar);
for (Widget widget : controlWidgets)
if (widget.handleKeyPress(keyID, keyChar))
return true;
for (Widget widget : controlWidgets) if (widget.handleKeyPress(keyID, keyChar)) return true;
}
return false;
}
@Override
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID) {
}
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID) {}
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (keyID == getKeyBinding("gui.hide")) {
if (NEIClientConfig.isKeyHashDown("gui.hide")) {
toggleBooleanSetting("inventory.hidden");
return true;
}
if (keyID == getKeyBinding("gui.hide_bookmarks")) {
if (NEIClientConfig.isKeyHashDown("gui.hide_bookmarks")) {
toggleBooleanSetting("inventory.bookmarksEnabled");
return true;
}
if (isEnabled() && !isHidden()) {
for (Widget widget : controlWidgets)
if (inputFocused == null)
widget.lastKeyTyped(keyID, keyChar);
if (NEIClientConfig.isKeyHashDown("gui.next_tooltip")) {
GuiContainerManager.incrementTooltipPage();
return true;
}
if (NEIClientConfig.isKeyHashDown("gui.bookmark_pull_items")) {
return bookmarkPanel.pullBookmarkItems();
}
if (isEnabled() && !isHidden()) {
for (Widget widget : controlWidgets) if (inputFocused == null) widget.lastKeyTyped(keyID, keyChar);
}
return false;
}
public void onMouseUp(GuiContainer gui, int mx, int my, int button) {
if (!isHidden() && isEnabled()) {
for (Widget widget : controlWidgets)
widget.mouseUp(mx, my, button);
for (Widget widget : controlWidgets) widget.mouseUp(mx, my, button);
}
}
@Override
public void onMouseDragged(GuiContainer gui, int mx, int my, int button, long heldTime) {
if (!isHidden() && isEnabled()) {
for (Widget widget : controlWidgets)
widget.mouseDragged(mx, my, button, heldTime);
for (Widget widget : controlWidgets) widget.mouseDragged(mx, my, button, heldTime);
}
}
@@ -241,8 +255,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (!isHidden() && isEnabled()) {
for (Widget widget : drawWidgets) {
ItemStack stack = widget.getStackMouseOver(mousex, mousey);
if (stack != null)
return stack;
if (stack != null) return stack;
}
}
return null;
@@ -253,8 +266,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
layout(gui);
if (isEnabled()) {
getLayoutStyle().drawBackground(GuiContainerManager.getManager(gui));
for (Widget widget : drawWidgets)
widget.draw(mousex, mousey);
for (Widget widget : drawWidgets) widget.draw(mousex, mousey);
} else {
options.draw(mousex, mousey);
bookmarksButton.draw(mousex, mousey);
@@ -268,16 +280,21 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public void postRenderObjects(GuiContainer gui, int mousex, int mousey) {
if (!isHidden() && isEnabled()) {
for (Widget widget : drawWidgets)
widget.postDraw(mousex, mousey);
for (Widget widget : drawWidgets) widget.postDraw(mousex, mousey);
}
}
@Override
public void postRenderTooltips(GuiContainer gui, int mousex, int mousey, List<String> tooltip) {
if (!isHidden() && isEnabled()) {
for (Widget widget : drawWidgets) widget.postDrawTooltips(mousex, mousey, tooltip);
}
}
@Override
public List<String> handleTooltip(GuiContainer gui, int mousex, int mousey, List<String> currenttip) {
if (!isHidden() && isEnabled() && GuiContainerManager.shouldShowTooltip(gui)) {
for (Widget widget : drawWidgets)
currenttip = widget.handleTooltip(mousex, mousey, currenttip);
for (Widget widget : drawWidgets) currenttip = widget.handleTooltip(mousex, mousey, currenttip);
}
return currenttip;
}
@@ -285,14 +302,12 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public List<String> handleItemDisplayName(GuiContainer gui, ItemStack stack, List<String> currenttip) {
String overridename = ItemInfo.getNameOverride(stack);
if (overridename != null)
currenttip.set(0, overridename);
if (overridename != null) currenttip.set(0, overridename);
String mainname = currenttip.get(0);
if (showIDs()) {
mainname += " " + Item.getIdFromItem(stack.getItem());
if (stack.getItemDamage() != 0)
mainname += ":" + stack.getItemDamage();
if (stack.getItemDamage() != 0) mainname += ":" + stack.getItemDamage();
currenttip.set(0, mainname);
}
@@ -301,29 +316,26 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
@Override
public List<String> handleItemTooltip(GuiContainer gui, ItemStack itemstack, int mousex, int mousey, List<String> currenttip) {
public List<String> handleItemTooltip(GuiContainer gui, ItemStack itemstack, int mousex, int mousey,
List<String> currenttip) {
return currenttip;
}
public static void layout(GuiContainer gui) {
VisiblityData visiblity = new VisiblityData();
if (isHidden())
visiblity.showNEI = false;
if (isBookmarkPanelHidden())
visiblity.showBookmarkPanel = false;
if (isHidden()) visiblity.showNEI = false;
if (gui.height - gui.ySize <= 40)
visiblity.showSearchSection = false;
if (isBookmarkPanelHidden()) visiblity.showBookmarkPanel = false;
if (visiblity.showBookmarkPanel || gui.guiTop <= 20)
visiblity.showSubsetDropdown = false;
if (gui.height - gui.ySize <= 40) visiblity.showSearchSection = false;
if (!visiblity.showBookmarkPanel || gui.guiTop <= 20)
visiblity.showPresetsDropdown = false;
if (visiblity.showBookmarkPanel || gui.guiTop <= 20) visiblity.showSubsetDropdown = false;
if (!visiblity.showBookmarkPanel || gui.guiTop <= 20) visiblity.showPresetsDropdown = false;
if (gui.guiLeft - 4 < 76) visiblity.showWidgets = false;
if (gui.guiLeft - 4 < 76)
visiblity.showWidgets = false;
try {
GuiInfo.readLock.lock();
GuiInfo.guiHandlers.forEach(handler -> handler.modifyVisiblity(gui, visiblity));
@@ -349,8 +361,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
presetsPanel = new PresetsWidget();
searchField = new SearchField("search");
options = new ButtonCycled(3)
{
options = new ButtonCycled(3) {
@Override
public void init() {
this.icons[0] = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 32, 0, 16, 16).build();
@@ -358,13 +370,22 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
this.icons[2] = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 64, 0, 16, 16).build();
}
private boolean getIsAccessibleControlEventKey() {
if (Minecraft.isRunningOnMac) {
return Keyboard.getEventKey() == Keyboard.KEY_LMETA || Keyboard.getEventKey() == Keyboard.KEY_RMETA;
}
return Keyboard.getEventKey() == Keyboard.KEY_LCONTROL
|| Keyboard.getEventKey() == Keyboard.KEY_RCONTROL;
}
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
if (Keyboard.getEventKeyState() && (Keyboard.getEventKey() == Keyboard.KEY_LCONTROL || Keyboard.getEventKey() == Keyboard.KEY_RCONTROL)) {
if (Keyboard.getEventKeyState() && getIsAccessibleControlEventKey()) {
NEIClientConfig.cycleSetting("inventory.cheatmode", 3);
} else {
if (Keyboard.getEventKeyState() && (Keyboard.getEventKey() == Keyboard.KEY_LSHIFT || Keyboard.getEventKey() == Keyboard.KEY_RSHIFT)) {
if (Keyboard.getEventKeyState() && (Keyboard.getEventKey() == Keyboard.KEY_LSHIFT
|| Keyboard.getEventKey() == Keyboard.KEY_RSHIFT)) {
GuiRecipeTab.loadHandlerInfo();
RecipeCatalysts.loadCatalystInfo();
}
@@ -380,14 +401,11 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
tooltip.add(translate("inventory.options.tip"));
String modeColor = "";
final int cheatMode = NEIClientConfig.getCheatMode();
if (cheatMode == 1)
modeColor = EnumChatFormatting.GOLD.toString();
else if (cheatMode == 2)
modeColor = EnumChatFormatting.RED.toString();
if (cheatMode == 1) modeColor = EnumChatFormatting.GOLD.toString();
else if (cheatMode == 2) modeColor = EnumChatFormatting.RED.toString();
String controlKeyLocalization = translate(Minecraft.isRunningOnMac ? "key.ctrl.mac" : "key.ctrl");
tooltip.add(modeColor + translate("inventory.options.tip.cheatmode." + cheatMode));
tooltip.add(modeColor + translate("inventory.options.tip.cheatmode.disable", controlKeyLocalization));
}
@Override
@@ -396,8 +414,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
};
bookmarksButton = new ButtonCycled(2)
{
bookmarksButton = new ButtonCycled(2) {
@Override
public void init() {
this.icons[0] = new DrawableBuilder("nei:textures/nei_tabbed_sprites.png", 0, 0, 16, 16).build();
@@ -419,85 +437,49 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
return translate("bookmark.toggle");
}
};
more = new Button("+")
{
more = ItemPanels.itemPanel.more;
less = ItemPanels.itemPanel.less;
quantity = ItemPanels.itemPanel.quantity;
delete = new Button() {
@Override
public boolean onButtonPress(boolean rightclick) {
if (rightclick)
return false;
int modifier = controlKey() ? 64 : shiftKey() ? 10 : 1;
int quantity = getItemQuantity() + modifier;
if (quantity < 0)
quantity = 0;
LayoutManager.quantity.setText(Integer.toString(quantity));
return true;
}
};
less = new Button("-")
{
@Override
public boolean onButtonPress(boolean rightclick) {
if (rightclick)
return false;
int modifier = controlKey() ? -64 : shiftKey() ? -10 : -1;
int quantity = getItemQuantity() + modifier;
if (quantity < 0)
quantity = 0;
LayoutManager.quantity.setText(Integer.toString(quantity));
return true;
}
};
quantity = new ItemQuantityField("quantity");
delete = new Button()
{
@Override
public boolean onButtonPress(boolean rightclick) {
if ((state & 0x3) == 2)
return false;
if ((state & 0x3) == 2) return false;
ItemStack held = getHeldItem();
if (held != null) {
if (shiftKey()) {
deleteHeldItem();
deleteItemsOfType(held);
} else if (rightclick)
decreaseSlotStack(-999);
else
deleteHeldItem();
} else if (shiftKey())
deleteEverything();
else
NEIController.toggleDeleteMode();
} else if (rightclick) decreaseSlotStack(-999);
else deleteHeldItem();
} else if (shiftKey()) deleteEverything();
else NEIController.toggleDeleteMode();
return true;
}
public String getButtonTip() {
if ((state & 0x3) != 2) {
if (shiftKey())
return translate("inventory.delete.inv");
if (NEIController.canUseDeleteMode())
return getStateTip("delete", state);
if (shiftKey()) return translate("inventory.delete.inv");
if (NEIController.canUseDeleteMode()) return getStateTip("delete", state);
}
return null;
}
@Override
public void postDraw(int mousex, int mousey) {
if(contains(mousex, mousey) && getHeldItem() != null && (state & 0x3) != 2)
GuiDraw.drawTip(mousex + 9, mousey, translate("inventory.delete." + (shiftKey() ? "all" : "one"), GuiContainerManager.itemDisplayNameShort(getHeldItem())));
if (contains(mousex, mousey) && getHeldItem() != null && (state & 0x3) != 2) GuiDraw.drawTip(
mousex + 9,
mousey,
translate(
"inventory.delete." + (shiftKey() ? "all" : "one"),
GuiContainerManager.itemDisplayNameShort(getHeldItem())));
}
};
gamemode = new ButtonCycled(3)
{
gamemode = new ButtonCycled(3) {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
@@ -506,18 +488,17 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
return false;
}
public void addTooltips(List<String> tooltip) {
tooltip.add(translate("inventory.current.gamemode." + getGamemode()));
tooltip.add(EnumChatFormatting.GRAY + translate("inventory.gamemode." + getNextGamemode()));
}
};
rain = new Button()
{
rain = new Button() {
@Override
public boolean onButtonPress(boolean rightclick) {
if (handleDisabledButtonPress("rain", rightclick))
return true;
if (handleDisabledButtonPress("rain", rightclick)) return true;
if (!rightclick) {
toggleRaining();
@@ -530,8 +511,8 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
return getStateTip("rain", state);
}
};
magnet = new Button()
{
magnet = new Button() {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
@@ -547,12 +528,11 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
};
for (int i = 0; i < 4; i++) {
final int zone = i;
timeButtons[i] = new Button()
{
timeButtons[i] = new Button() {
@Override
public boolean onButtonPress(boolean rightclick) {
if (handleDisabledButtonPress(NEIActions.timeZones[zone], rightclick))
return true;
if (handleDisabledButtonPress(NEIActions.timeZones[zone], rightclick)) return true;
if (!rightclick) {
setHourForward(zone * 6);
@@ -562,14 +542,13 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
@Override
public String getButtonTip() {
return getTimeTip(NEIActions.timeZones[zone], state);
public void addTooltips(List<String> tooltip) {
addTimeTip(NEIActions.timeZones[zone], state, tooltip);
}
};
}
heal = new Button()
{
heal = new Button() {
@Override
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
@@ -592,22 +571,23 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
private static String getStateTip(String name, int state) {
String sfx = (state & 0x3) == 2 ? "enable" :
(state & 0x3) == 1 ? "0" : "1";
String sfx = (state & 0x3) == 2 ? "enable" : (state & 0x3) == 1 ? "0" : "1";
return translate("inventory." + name + "." + sfx);
}
private static String getTimeTip(String name, int state) {
String sfx = (state & 0x3) == 2 ? "enable" : "set";
return translate("inventory." + name + "." + sfx);
private static void addTimeTip(String name, int state, List<String> tooltip) {
if ((state & 0x3) == 2) {
tooltip.add(translate("inventory." + name + ".enable"));
} else {
tooltip.add(translate("inventory." + name + ".set"));
tooltip.add(EnumChatFormatting.GRAY + translate("inventory." + name + ".disable"));
}
}
private static boolean handleDisabledButtonPress(String ident, boolean rightclick) {
if (!NEIActions.canDisable.contains(ident))
return false;
if (rightclick != disabledActions.contains(ident))
return setPropertyDisabled(ident, rightclick);
if (!NEIActions.canDisable.contains(ident)) return false;
if (rightclick != disabledActions.contains(ident)) return setPropertyDisabled(ident, rightclick);
return false;
}
@@ -615,14 +595,11 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (disable && NEIActions.base(ident).equals("time")) {
int count = 0;
for (int i = 0; i < 4; i++) {
if (disabledActions.contains(NEIActions.timeZones[i]))
count++;
if (disabledActions.contains(NEIActions.timeZones[i])) count++;
}
if (count == 3)
return false;
if (count == 3) return false;
}
if (hasSMPCounterPart())
NEICPH.sendSetPropertyDisabled(ident, disable);
if (hasSMPCounterPart()) NEICPH.sendSetPropertyDisabled(ident, disable);
return true;
}
@@ -637,7 +614,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
if (isEnabled()) {
setInputFocused(null);
if(!itemsLoaded) {
if (!itemsLoaded) {
ItemList.loadItems.restart();
itemsLoaded = true;
}
@@ -649,13 +626,13 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
NEIController.load(gui);
if (checkCreativeInv(gui) && gui.mc.currentScreen instanceof GuiContainerCreative)//override creative with creative+
gui.mc.displayGuiScreen(null);//close the screen and wait for the server to open it for us
if (checkCreativeInv(gui) && gui.mc.currentScreen instanceof GuiContainerCreative) // override creative with
// creative+
gui.mc.displayGuiScreen(null); // close the screen and wait for the server to open it for us
}
@Override
public void refresh(GuiContainer gui) {
}
public void refresh(GuiContainer gui) {}
public boolean checkCreativeInv(GuiContainer gui) {
if (gui instanceof GuiContainerCreative && invCreativeMode()) {
@@ -672,9 +649,7 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
drawWidgets = new TreeSet<>(new WidgetZOrder(false));
controlWidgets = new TreeSet<>(new WidgetZOrder(true));
if (!visiblity.showNEI)
return;
if (!visiblity.showNEI) return;
addWidget(options);
addWidget(bookmarksButton);
@@ -687,10 +662,6 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
itemPanel.setVisible();
addWidget(more);
addWidget(less);
addWidget(quantity);
}
if (visiblity.showBookmarkPanel) {
@@ -702,27 +673,21 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
addWidget(presetsPanel);
}
searchField.setVisible(visiblity.showSearchSection);
if (visiblity.showSearchSection) {
addWidget(searchField);
}
if (visiblity.showUtilityButtons) {
if (canPerformAction("time")) {
for (int i = 0; i < 4; i++)
addWidget(timeButtons[i]);
for (int i = 0; i < 4; i++) addWidget(timeButtons[i]);
}
if (canPerformAction("rain"))
addWidget(rain);
if (canPerformAction("heal"))
addWidget(heal);
if (canPerformAction("magnet"))
addWidget(magnet);
if (isValidGamemode("creative") ||
isValidGamemode("creative+") ||
isValidGamemode("adventure"))
if (canPerformAction("rain")) addWidget(rain);
if (canPerformAction("heal")) addWidget(heal);
if (canPerformAction("magnet")) addWidget(magnet);
if (isValidGamemode("creative") || isValidGamemode("creative+") || isValidGamemode("adventure"))
addWidget(gamemode);
if (canPerformAction("delete"))
addWidget(delete);
if (canPerformAction("delete")) addWidget(delete);
}
if (visiblity.showSubsetDropdown) {
@@ -731,11 +696,9 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
}
}
public static LayoutStyle getLayoutStyle(int id) {
LayoutStyle style = layoutStyles.get(id);
if (style == null)
style = layoutStyles.get(0);
if (style == null) style = layoutStyles.get(0);
return style;
}
@@ -750,31 +713,24 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public void guiTick(GuiContainer gui) {
if (checkCreativeInv(gui))
return;
if (checkCreativeInv(gui)) return;
if (!isEnabled())
return;
if (!isEnabled()) return;
for (Widget widget : drawWidgets)
widget.update();
for (Widget widget : drawWidgets) widget.update();
}
@Override
public boolean mouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {
if (isHidden() || !isEnabled())
return false;
if (isHidden() || !isEnabled()) return false;
for (Widget widget : drawWidgets)
if (widget.onMouseWheel(scrolled, mousex, mousey))
return true;
for (Widget widget : drawWidgets) if (widget.onMouseWheel(scrolled, mousex, mousey)) return true;
return false;
}
@Override
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {
}
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {}
@Override
public boolean shouldShowTooltip(GuiContainer gui) {
@@ -788,51 +744,48 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
/** Note: this method isn't actually used by this mod, but NEI add-ons might need it. */
public static void setInputFocused(Widget widget) {
if (inputFocused != null)
inputFocused.loseFocus();
if (inputFocused != null) inputFocused.loseFocus();
inputFocused = widget;
if (inputFocused != null)
inputFocused.gainFocus();
if (inputFocused != null) inputFocused.gainFocus();
}
@Override
public void renderSlotUnderlay(GuiContainer gui, Slot slot) {
if (overlayRenderer != null)
overlayRenderer.renderOverlay(GuiContainerManager.getManager(gui), slot);
if (overlayRenderer != null) overlayRenderer.renderOverlay(GuiContainerManager.getManager(gui), slot);
}
@Override
public void renderSlotOverlay(GuiContainer window, Slot slot) {
ItemStack item = slot.getStack();
if (world.nbt.getBoolean("searchinventories") && (item == null ? !getSearchExpression().equals("") : !ItemList.getItemListFilter().matches(item))) {
if (world.nbt.getBoolean("searchinventories") && (item == null ? !getSearchExpression().equals("")
: !((SearchField) searchField).getFilter().matches(item))) {
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glTranslatef(0, 0, 150);
drawRect(slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, 0x80000000);
GL11.glTranslatef(0, 0, -150);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
}
}
public static void drawIcon(int x, int y, Image image) {
final boolean isDrawableResource = image instanceof DrawableResource;
if (!isDrawableResource)
changeTexture("nei:textures/nei_sprites.png");
if (!isDrawableResource) changeTexture("nei:textures/nei_sprites.png");
GL11.glColor4f(1, 1, 1, 1);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(!isDrawableResource)
drawTexturedModalRect(x, y, image.x, image.y, image.width, image.height);
else
((DrawableResource)image).draw(x, y);
if (!isDrawableResource) drawTexturedModalRect(x, y, image.x, image.y, image.width, image.height);
else((DrawableResource) image).draw(x, y);
GL11.glDisable(GL11.GL_BLEND);
}
public static void drawButtonBackground(int x, int y, int w, int h, boolean edges, int type) {
int wTiles = 0;
int ew = w;//end width
int ew = w; // end width
if (w / 2 > 100) {
wTiles = (w - 200) / 50 + 1;
ew = 200;
@@ -847,27 +800,27 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
final int y2 = y + h - h2;
final int ty = 46 + type * 20;
final int te = (edges ? 0 : 1);//tex edges
final int te = (edges ? 0 : 1); // tex edges
final int ty1 = ty + te;
final int tx1 = te;
final int tx3 = 75;
//halfway the 1 is for odd number adjustment
// halfway the 1 is for odd number adjustment
final int ty2 = ty + 20 - h2 - te;
final int tx2 = 200 - w2 - te;
changeTexture("textures/gui/widgets.png");
drawTexturedModalRect(x, y, tx1, ty1, w1, h1);//top left
drawTexturedModalRect(x, y2, tx1, ty2, w1, h2);//bottom left
drawTexturedModalRect(x, y, tx1, ty1, w1, h1); // top left
drawTexturedModalRect(x, y2, tx1, ty2, w1, h2); // bottom left
for (int tile = 0; tile < wTiles; tile++) {
final int tileX = x + w1 + 50 * tile;
drawTexturedModalRect(tileX, y, tx3, ty1, 50, h1);//top
drawTexturedModalRect(tileX, y2, tx3, ty2, 50, h2);//bottom
drawTexturedModalRect(tileX, y, tx3, ty1, 50, h1); // top
drawTexturedModalRect(tileX, y2, tx3, ty2, 50, h2); // bottom
}
drawTexturedModalRect(x2, y, tx2, ty1, w2, h1);//top right
drawTexturedModalRect(x2, y2, tx2, ty2, w2, h2);//bottom right
drawTexturedModalRect(x2, y, tx2, ty1, w2, h1); // top right
drawTexturedModalRect(x2, y2, tx2, ty2, w2, h2); // bottom right
}
public static void drawItemPresenceOverlay(int slotX, int slotY, boolean isPresent) {
@@ -881,23 +834,14 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public void tickKeyStates() {
if (Minecraft.getMinecraft().currentScreen != null)
return;
if (Minecraft.getMinecraft().currentScreen != null) return;
if (KeyManager.keyStates.get("world.dawn").down)
timeButtons[0].onButtonPress(false);
if (KeyManager.keyStates.get("world.noon").down)
timeButtons[1].onButtonPress(false);
if (KeyManager.keyStates.get("world.dusk").down)
timeButtons[2].onButtonPress(false);
if (KeyManager.keyStates.get("world.midnight").down)
timeButtons[3].onButtonPress(false);
if (KeyManager.keyStates.get("world.rain").down)
rain.onButtonPress(false);
if (KeyManager.keyStates.get("world.heal").down)
heal.onButtonPress(false);
if (KeyManager.keyStates.get("world.creative").down)
gamemode.onButtonPress(false);
if (KeyManager.keyStates.get("world.dawn").down) timeButtons[0].onButtonPress(false);
if (KeyManager.keyStates.get("world.noon").down) timeButtons[1].onButtonPress(false);
if (KeyManager.keyStates.get("world.dusk").down) timeButtons[2].onButtonPress(false);
if (KeyManager.keyStates.get("world.midnight").down) timeButtons[3].onButtonPress(false);
if (KeyManager.keyStates.get("world.rain").down) rain.onButtonPress(false);
if (KeyManager.keyStates.get("world.heal").down) heal.onButtonPress(false);
if (KeyManager.keyStates.get("world.creative").down) gamemode.onButtonPress(false);
}
}
@@ -1,10 +1,5 @@
package codechicken.nei;
import codechicken.nei.api.LayoutStyle;
import codechicken.nei.drawable.DrawableBuilder;
import net.minecraft.client.gui.inventory.GuiContainer;
import org.lwjgl.opengl.GL11;
import static codechicken.lib.gui.GuiDraw.drawStringC;
import static codechicken.nei.LayoutManager.bookmarkPanel;
import static codechicken.nei.LayoutManager.bookmarksButton;
@@ -14,11 +9,9 @@ import static codechicken.nei.LayoutManager.gamemode;
import static codechicken.nei.LayoutManager.heal;
import static codechicken.nei.LayoutManager.itemPanel;
import static codechicken.nei.LayoutManager.itemPresenceOverlays;
import static codechicken.nei.LayoutManager.less;
import static codechicken.nei.LayoutManager.magnet;
import static codechicken.nei.LayoutManager.more;
import static codechicken.nei.LayoutManager.options;
import static codechicken.nei.LayoutManager.quantity;
import static codechicken.nei.LayoutManager.presetsPanel;
import static codechicken.nei.LayoutManager.rain;
import static codechicken.nei.LayoutManager.searchField;
import static codechicken.nei.LayoutManager.timeButtons;
@@ -27,8 +20,15 @@ import static codechicken.nei.NEIClientConfig.disabledActions;
import static codechicken.nei.NEIClientConfig.getMagnetMode;
import static codechicken.nei.NEIClientConfig.isEnabled;
public class LayoutStyleMinecraft extends LayoutStyle
{
import net.minecraft.client.gui.inventory.GuiContainer;
import org.lwjgl.opengl.GL11;
import codechicken.nei.api.LayoutStyle;
import codechicken.nei.drawable.DrawableBuilder;
public class LayoutStyleMinecraft extends LayoutStyle {
public int buttonCount;
public int leftSize;
public int numButtons;
@@ -68,66 +68,44 @@ public class LayoutStyleMinecraft extends LayoutStyle
numButtons = Math.max(leftSize / 18, 1);
delete.state = 0x4;
if (NEIController.getDeleteMode())
delete.state |= 1;
else if (!visiblity.enableDeleteMode)
delete.state |= 2;
if (NEIController.getDeleteMode()) delete.state |= 1;
else if (!visiblity.enableDeleteMode) delete.state |= 2;
rain.state = 0x4;
if (disabledActions.contains("rain"))
rain.state |= 2;
else if (NEIClientUtils.isRaining())
rain.state |= 1;
if (disabledActions.contains("rain")) rain.state |= 2;
else if (NEIClientUtils.isRaining()) rain.state |= 1;
gamemode.state = 0x4;
if (NEIClientUtils.getGamemode() != 0) {
gamemode.state |= 0x1;
gamemode.index = NEIClientUtils.getGamemode() - 1;
} else {
if (NEIClientUtils.isValidGamemode("creative"))
gamemode.index = 0;
else if (NEIClientUtils.isValidGamemode("creative+"))
gamemode.index = 1;
else if (NEIClientUtils.isValidGamemode("adventure"))
gamemode.index = 2;
if (NEIClientUtils.isValidGamemode("creative")) gamemode.index = 0;
else if (NEIClientUtils.isValidGamemode("creative+")) gamemode.index = 1;
else if (NEIClientUtils.isValidGamemode("adventure")) gamemode.index = 2;
}
bookmarksButton.index = NEIClientConfig.isBookmarkPanelHidden() ? 0 : 1;
options.index = NEIClientConfig.getCheatMode();
magnet.state = 0x4 | (getMagnetMode() ? 1 : 0);
if (canPerformAction("delete"))
layoutButton(delete);
if (canPerformAction("rain"))
layoutButton(rain);
if (NEIClientUtils.isValidGamemode("creative") ||
NEIClientUtils.isValidGamemode("creative+") ||
NEIClientUtils.isValidGamemode("adventure"))
if (canPerformAction("delete")) layoutButton(delete);
if (canPerformAction("rain")) layoutButton(rain);
if (NEIClientUtils.isValidGamemode("creative") || NEIClientUtils.isValidGamemode("creative+")
|| NEIClientUtils.isValidGamemode("adventure"))
layoutButton(gamemode);
if (canPerformAction("magnet"))
layoutButton(magnet);
if (canPerformAction("magnet")) layoutButton(magnet);
if (canPerformAction("time")) {
for (int i = 0; i < 4; i++) {
timeButtons[i].state = disabledActions.contains(NEIActions.timeZones[i]) ? 2 : 0;
layoutButton(timeButtons[i]);
}
}
if (canPerformAction("heal"))
layoutButton(heal);
if (canPerformAction("heal")) layoutButton(heal);
itemPanel.resize(gui);
bookmarkPanel.resize(gui);
more.w = more.h = less.w = less.h = 16;
less.x = itemPanel.pagePrev.x;
more.x = gui.width - less.w - 2;
more.y = less.y = gui.height - more.h - 2;
quantity.x = less.x + less.w + 2;
quantity.y = less.y;
quantity.w = more.x - quantity.x - 2;
quantity.h = less.h;
options.x = isEnabled() ? 0 : 6;
options.y = isEnabled() ? gui.height - 22 : gui.height - 28;
options.w = 22;
@@ -138,25 +116,34 @@ public class LayoutStyleMinecraft extends LayoutStyle
bookmarksButton.w = 22;
bookmarksButton.h = 22;
searchField.y = gui.height - searchField.h - 2;
dropDown.h = 18;
dropDown.w = 150;
dropDown.y = 0;
dropDown.x = (gui.width - gui.xSize) / 2 + gui.xSize - dropDown.w;
presetsPanel.h = 16;
presetsPanel.w = 150;
presetsPanel.y = 2;
presetsPanel.x = (gui.width - gui.xSize) / 2 + gui.xSize - presetsPanel.w;
dropDown.x = Math.min(numButtons, buttonCount) * 20 + 3;
dropDown.h = 20;
dropDown.w = itemPanel.x - dropDown.x - 3;
searchField.h = 20;
searchField.w = 150;
searchField.x = (gui.width - searchField.w) / 2;
if (NEIClientConfig.isSearchWidgetCentered()) {
searchField.w = 150;
searchField.x = (gui.width - searchField.w) / 2;
} else {
searchField.w = (int) (itemPanel.w * (NEIClientConfig.showItemQuantityWidget() ? 0.7 : 1));
searchField.x = itemPanel.x;
}
searchField.y = gui.height - searchField.h - 2;
if (!visiblity.showItemSection) {
searchField.setFocus(false);
}
}
public void layoutButton(Button button) {
button.x = 2 + (buttonCount % numButtons) * 20;
button.y = (buttonCount / numButtons) * 18;
button.x = 2 + (buttonCount % numButtons) * 19;
button.y = 2 + (buttonCount / numButtons) * 18;
button.h = 17;
button.w = button.contentWidth() + 6;
@@ -170,13 +157,11 @@ public class LayoutStyleMinecraft extends LayoutStyle
GL11.glColor4f(1, 1, 1, 1);
int tex;
if ((b.state & 0x3) == 2)
tex = 0;
else if ((b.state & 0x4) == 0 && b.contains(mousex, mousey) ||//not a state button and mouseover
(b.state & 0x3) == 1)//state active
if ((b.state & 0x3) == 2) tex = 0;
else if ((b.state & 0x4) == 0 && b.contains(mousex, mousey) || // not a state button and mouseover
(b.state & 0x3) == 1) // state active
tex = 2;
else
tex = 1;
else tex = 1;
LayoutManager.drawButtonBackground(b.x, b.y, b.w, b.h, true, tex);
Image icon = b.getRenderIcon();
@@ -196,12 +181,9 @@ public class LayoutStyleMinecraft extends LayoutStyle
@Override
public void drawSubsetTag(String text, int x, int y, int w, int h, int state, boolean mouseover) {
if(state == 1)
GL11.glColor4f(0.65F, 0.65F, 0.65F, 1.0F);
else
GL11.glColor4f(1, 1, 1, 1);
if (state == 1) GL11.glColor4f(0.65F, 0.65F, 0.65F, 1.0F);
else GL11.glColor4f(1, 1, 1, 1);
LayoutManager.drawButtonBackground(x, y, w, h, false, state == 0 ? 0 : 1);
if(text != null)
drawStringC(text, x, y, w, h, state == 2 ? 0xFFE0E0E0 : 0xFFA0A0A0);
if (text != null) drawStringC(text, x, y, w, h, state == 2 ? 0xFFE0E0E0 : 0xFFA0A0A0);
}
}
+20 -31
View File
@@ -5,47 +5,40 @@ import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
public class NEIActions
{
public class NEIActions {
public static final int protocol = 0;
public static HashMap<String, NEIActions> nameActionMap = new HashMap<>();
public static HashSet<String> canDisable = new HashSet<>();
public static void addAction(String name, String base, boolean smpreq)
{
public static void addAction(String name, String base, boolean smpreq) {
NEIActions action = new NEIActions(name, base, smpreq);
nameActionMap.put(name, action);
}
private static void addAction(String name, String base)
{
private static void addAction(String name, String base) {
addAction(name, base, false);
}
public static void addAction(String name)
{
public static void addAction(String name) {
addAction(name, name);
}
private static void addAction(String name, boolean smpreq)
{
private static void addAction(String name, boolean smpreq) {
addAction(name, name, smpreq);
}
public static String base(String name)
{
public static String base(String name) {
NEIActions action = nameActionMap.get(name);
return action == null ? name : action.base;
}
public static boolean smpRequired(String name)
{
public static boolean smpRequired(String name) {
return nameActionMap.get(name).smpreq;
}
public static void init()
{
public static void init() {
addAction("time");
addAction("dawn", "time");
addAction("noon", "time");
@@ -68,27 +61,23 @@ public class NEIActions
canDisable.add("midnight");
canDisable.add("rain");
}
public static final String[] timeZones = new String[]{"dawn", "noon", "dusk", "midnight"};
public static final String[] gameModes = new String[]{"survival", "creative", "creative+", "adventure"};
public static final String[] timeZones = new String[] { "dawn", "noon", "dusk", "midnight" };
public static final String[] gameModes = new String[] { "survival", "creative", "creative+", "adventure" };
public String name;
public String base;
public boolean smpreq;
public NEIActions(String name, String base, boolean smpreq)
{
public NEIActions(String name, String base, boolean smpreq) {
this.name = name;
this.base = base;
this.smpreq = smpreq;
}
public static List<String> baseActions()
{
public static List<String> baseActions() {
List<String> list = new LinkedList<>();
for(NEIActions a : nameActionMap.values())
if(a.base.equals(a.name))
list.add(a.name);
for (NEIActions a : nameActionMap.values()) if (a.base.equals(a.name)) list.add(a.name);
return list;
}
}
+39 -39
View File
@@ -1,10 +1,5 @@
package codechicken.nei;
import codechicken.core.ClientUtils;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IClientPacketHandler;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.item.ItemStack;
@@ -12,8 +7,14 @@ import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.world.World;
public class NEICPH implements IClientPacketHandler
{
import codechicken.core.ClientUtils;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IClientPacketHandler;
import cpw.mods.fml.relauncher.Side;
public class NEICPH implements IClientPacketHandler {
public static final String channel = "NEI";
@Override
@@ -38,13 +39,16 @@ public class NEICPH implements IClientPacketHandler
handleGamemode(mc, packet.readUByte());
break;
case 21:
ClientUtils.openSMPGui(packet.readUByte(), new GuiEnchantmentModifier(mc.thePlayer.inventory, mc.theWorld, 0, 0, 0));
ClientUtils.openSMPGui(
packet.readUByte(),
new GuiEnchantmentModifier(mc.thePlayer.inventory, mc.theWorld, 0, 0, 0));
break;
case 23:
if (packet.readBoolean())
ClientUtils.openSMPGui(packet.readUByte(), new GuiExtendedCreativeInv(new ContainerCreativeInv(mc.thePlayer, new ExtendedCreativeInv(null, Side.CLIENT))));
else
mc.displayGuiScreen(new GuiInventory(mc.thePlayer));
if (packet.readBoolean()) ClientUtils.openSMPGui(
packet.readUByte(),
new GuiExtendedCreativeInv(
new ContainerCreativeInv(mc.thePlayer, new ExtendedCreativeInv(null, Side.CLIENT))));
else mc.displayGuiScreen(new GuiInventory(mc.thePlayer));
break;
case 24:
ClientUtils.openSMPGui(packet.readUByte(), new GuiPotionCreator(mc.thePlayer.inventory));
@@ -58,40 +62,32 @@ public class NEICPH implements IClientPacketHandler
private void handleActionEnabled(PacketCustom packet) {
String name = packet.readString();
if (packet.readBoolean())
NEIClientConfig.enabledActions.add(name);
else
NEIClientConfig.enabledActions.remove(name);
if (packet.readBoolean()) NEIClientConfig.enabledActions.add(name);
else NEIClientConfig.enabledActions.remove(name);
}
private void handleActionDisabled(PacketCustom packet) {
String name = packet.readString();
if (packet.readBoolean())
NEIClientConfig.disabledActions.add(name);
else
NEIClientConfig.disabledActions.remove(name);
if (packet.readBoolean()) NEIClientConfig.disabledActions.add(name);
else NEIClientConfig.disabledActions.remove(name);
}
private void handleLoginState(PacketCustom packet) {
NEIClientConfig.permissableActions.clear();
int num = packet.readUByte();
for (int i = 0; i < num; i++)
NEIClientConfig.permissableActions.add(packet.readString());
for (int i = 0; i < num; i++) NEIClientConfig.permissableActions.add(packet.readString());
NEIClientConfig.disabledActions.clear();
num = packet.readUByte();
for (int i = 0; i < num; i++)
NEIClientConfig.disabledActions.add(packet.readString());
for (int i = 0; i < num; i++) NEIClientConfig.disabledActions.add(packet.readString());
NEIClientConfig.enabledActions.clear();
num = packet.readUByte();
for (int i = 0; i < num; i++)
NEIClientConfig.enabledActions.add(packet.readString());
for (int i = 0; i < num; i++) NEIClientConfig.enabledActions.add(packet.readString());
NEIClientConfig.bannedBlocks.clear();
num = packet.readInt();
for(int i = 0; i < num; i++)
NEIClientConfig.bannedBlocks.add(packet.readItemStack());
for (int i = 0; i < num; i++) NEIClientConfig.bannedBlocks.add(packet.readItemStack());
if (NEIClientUtils.getGuiContainer() != null)
LayoutManager.instance().refresh(NEIClientUtils.getGuiContainer());
@@ -106,7 +102,7 @@ public class NEICPH implements IClientPacketHandler
try {
ClientHandler.instance().loadWorld(world, true);
NEIClientConfig.setHasSMPCounterPart(true);
NEIClientConfig.loadWorld(getSaveName(worldName));
NEIClientConfig.loadWorld(getSaveName());
sendRequestLoginInfo();
} catch (Exception e) {
NEIClientConfig.logger.error("Error handling SMP Check", e);
@@ -114,11 +110,10 @@ public class NEICPH implements IClientPacketHandler
}
}
private static String getSaveName(String worldName) {
if (Minecraft.getMinecraft().isSingleplayer())
return "local/" + ClientUtils.getWorldSaveName();
private static String getSaveName() {
if (Minecraft.getMinecraft().isSingleplayer()) return "local/" + ClientUtils.getWorldSaveName();
return "remote/" + ClientUtils.getServerIP().replace(':', '~') + "/" + worldName;
return "remote/" + ClientUtils.getServerIP().replace(':', '~');
}
public static void sendGiveItem(ItemStack spawnstack, boolean infinite, boolean doSpawn) {
@@ -148,6 +143,12 @@ public class NEICPH implements IClientPacketHandler
packet.sendToServer();
}
public static void sendRequestContainer() {
PacketCustom packet = new PacketCustom(channel, 16);
packet.writeInt(Minecraft.getMinecraft().thePlayer.openContainer.getInventory().size());
packet.sendToServer();
}
public static void sendSetSlot(int slot, ItemStack stack, boolean container) {
PacketCustom packet = new PacketCustom(channel, 5);
packet.writeBoolean(container);
@@ -203,9 +204,7 @@ public class NEICPH implements IClientPacketHandler
}
public static void sendGamemode(int mode) {
new PacketCustom(channel, 13)
.writeByte(mode)
.sendToServer();
new PacketCustom(channel, 13).writeByte(mode).sendToServer();
}
public static void sendCreativeInv(boolean open) {
@@ -229,10 +228,11 @@ public class NEICPH implements IClientPacketHandler
public static void sendOpenPotionWindow() {
ItemStack[] potionStore = new ItemStack[9];
InventoryUtils.readItemStacksFromTag(potionStore, NEIClientConfig.global.nbt.getCompoundTag("potionStore").getTagList("items", 10));
InventoryUtils.readItemStacksFromTag(
potionStore,
NEIClientConfig.global.nbt.getCompoundTag("potionStore").getTagList("items", 10));
PacketCustom packet = new PacketCustom(channel, 24);
for (ItemStack stack : potionStore)
packet.writeItemStack(stack);
for (ItemStack stack : potionStore) packet.writeItemStack(stack);
packet.sendToServer();
}
@@ -1,17 +1,18 @@
package codechicken.nei;
import codechicken.nei.api.INEIGuiAdapter;
import codechicken.nei.api.TaggedInventoryArea;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiChest;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.ContainerChest;
import net.minecraft.item.ItemStack;
import java.util.Collections;
import java.util.List;
import codechicken.nei.api.INEIGuiAdapter;
import codechicken.nei.api.TaggedInventoryArea;
public class NEIChestGuiHandler extends INEIGuiAdapter {
public class NEIChestGuiHandler extends INEIGuiAdapter
{
public int chestSize(GuiContainer gui) {
return ((ContainerChest) gui.inventorySlots).getLowerChestInventory().getSizeInventory();
}
@@ -23,6 +24,8 @@ public class NEIChestGuiHandler extends INEIGuiAdapter
@Override
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer gui) {
return gui instanceof GuiChest ? Collections.singletonList(new TaggedInventoryArea("Chest", 0, chestSize(gui), gui.inventorySlots)) : null;
return gui instanceof GuiChest
? Collections.singletonList(new TaggedInventoryArea("Chest", 0, chestSize(gui), gui.inventorySlots))
: null;
}
}
+264 -100
View File
@@ -1,5 +1,28 @@
package codechicken.nei;
import java.io.File;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.storage.SaveFormatComparator;
import net.minecraftforge.common.MinecraftForge;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.input.Keyboard;
import com.google.common.base.Objects;
import codechicken.core.CCUpdateChecker;
import codechicken.core.ClassDiscoverer;
import codechicken.core.ClientUtils;
@@ -16,6 +39,7 @@ import codechicken.nei.config.ConfigSet;
import codechicken.nei.config.GuiHighlightTips;
import codechicken.nei.config.GuiNEIOptionList;
import codechicken.nei.config.GuiOptionList;
import codechicken.nei.config.GuiPanelSettings;
import codechicken.nei.config.OptionCycled;
import codechicken.nei.config.OptionGamemodes;
import codechicken.nei.config.OptionList;
@@ -30,28 +54,11 @@ import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.RecipeCatalysts;
import codechicken.nei.recipe.RecipeInfo;
import codechicken.obfuscator.ObfuscationRun;
import com.google.common.base.Objects;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.storage.SaveFormatComparator;
import net.minecraftforge.common.MinecraftForge;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.input.Keyboard;
import java.io.File;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Pattern;
public class NEIClientConfig {
private static boolean configLoaded;
private static boolean mainNEIConfigLoaded;
private static boolean pluginNEIConfigLoaded;
private static boolean enabledOverride;
private static String worldPath;
@@ -84,17 +91,22 @@ public class NEIClientConfig {
// Function that extracts the handler ID from a handler, with special logic for
// TemplateRecipeHandler: prefer using the overlay ID if it exists.
public static final Function<IRecipeHandler, String> HANDLER_ID_FUNCTION =
handler -> Objects.firstNonNull(
handler.getOverlayIdentifier(),
handler.getHandlerId());
public static final Function<IRecipeHandler, String> HANDLER_ID_FUNCTION = handler -> Objects
.firstNonNull(handler.getOverlayIdentifier(), handler.getHandlerId());
public static int getHandlerOrder(IRecipeHandler handler) {
if (handlerOrdering.get(handler.getOverlayIdentifier()) != null) {
return handlerOrdering.get(handler.getOverlayIdentifier());
}
if (handlerOrdering.get(handler.getHandlerId()) != null) {
return handlerOrdering.get(handler.getHandlerId());
}
return 0;
}
// Comparator that compares handlers using the handlerOrdering map.
public static final Comparator<IRecipeHandler> HANDLER_COMPARATOR =
Comparator.comparingInt(
handler -> handlerOrdering.getOrDefault(
HANDLER_ID_FUNCTION.apply(handler), 0));
public static final Comparator<IRecipeHandler> HANDLER_COMPARATOR = Comparator
.comparingInt(NEIClientConfig::getHandlerOrder);
public static ItemStack[] creativeInv;
@@ -106,17 +118,18 @@ public class NEIClientConfig {
public static ItemStackSet bannedBlocks = new ItemStackSet();
static {
if (global.config.getTag("checkUpdates").getBooleanValue(true))
CCUpdateChecker.updateCheck("NotEnoughItems");
if (global.config.getTag("checkUpdates").getBooleanValue(true)) CCUpdateChecker.updateCheck("NotEnoughItems");
linkOptionList();
setDefaults();
}
private static void setDefaults() {
ConfigTagParent tag = global.config;
tag.setComment("Main configuration of NEI.\nMost of these options can be changed ingame.\nDeleting any element will restore it to it's default value");
tag.setComment(
"Main configuration of NEI.\nMost of these options can be changed ingame.\nDeleting any element will restore it to it's default value");
tag.getTag("command").useBraces().setComment("Change these options if you have a different mod installed on the server that handles the commands differently, Eg. Bukkit Essentials");
tag.getTag("command").useBraces().setComment(
"Change these options if you have a different mod installed on the server that handles the commands differently, Eg. Bukkit Essentials");
tag.setNewLineMode(1);
tag.getTag("inventory.widgetsenabled").getBooleanValue(true);
@@ -124,9 +137,11 @@ public class NEIClientConfig {
tag.getTag("inventory.hidden").getBooleanValue(false);
tag.getTag("inventory.cheatmode").getIntValue(2);
tag.getTag("inventory.lockmode").setComment("For those who can't help themselves.\nSet this to a mode and you will be unable to change it ingame").getIntValue(-1);
API.addOption(new OptionCycled("inventory.cheatmode", 3)
{
tag.getTag("inventory.lockmode").setComment(
"For those who can't help themselves.\nSet this to a mode and you will be unable to change it ingame")
.getIntValue(-1);
API.addOption(new OptionCycled("inventory.cheatmode", 3) {
@Override
public boolean optionValid(int index) {
return getLockedMode() == -1 || getLockedMode() == index && NEIInfo.isValidMode(index);
@@ -140,7 +155,6 @@ public class NEIClientConfig {
tag.getTag("inventory.gamemodes").setDefaultValue("creative, creative+, adventure");
API.addOption(new OptionGamemodes("inventory.gamemodes"));
ItemSorter.initConfig(tag);
tag.getTag("inventory.itemIDs").getIntValue(1);
@@ -154,6 +168,18 @@ public class NEIClientConfig {
tag.getTag("world.highlight_tips.y").getIntValue(100);
API.addOption(new OptionOpenGui("world.highlight_tips", GuiHighlightTips.class));
tag.getTag("world.panels.bookmarks.left").getIntValue(0);
tag.getTag("world.panels.bookmarks.right").getIntValue(0);
tag.getTag("world.panels.bookmarks.top").getIntValue(0);
tag.getTag("world.panels.bookmarks.bottom").getIntValue(0);
tag.getTag("world.panels.items.left").getIntValue(0);
tag.getTag("world.panels.items.right").getIntValue(0);
tag.getTag("world.panels.items.top").getIntValue(0);
tag.getTag("world.panels.items.bottom").getIntValue(0);
API.addOption(new OptionOpenGui("world.panels", GuiPanelSettings.class));
tag.getTag("inventory.profileRecipes").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.profileRecipes", true));
@@ -162,12 +188,16 @@ public class NEIClientConfig {
tag.getTag("inventory.invertMouseScrollTransfer").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.invertMouseScrollTransfer", true) {
@Override
public boolean isEnabled() {
return isMouseScrollTransferEnabled();
}
});
tag.getTag("inventory.cacheItemRendering").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.cacheItemRendering", true));
tag.getTag("itemLoadingTimeout").getIntValue(500);
tag.getTag("command.creative").setDefaultValue("/gamemode {0} {1}");
@@ -181,8 +211,10 @@ public class NEIClientConfig {
tag.getTag("command.heal").setDefaultValue("");
API.addOption(new OptionTextField("command.heal"));
tag.getTag("inventory.worldSpecificBookmarks").setComment("Global or world specific bookmarks").getBooleanValue(false);
tag.getTag("inventory.worldSpecificBookmarks").setComment("Global or world specific bookmarks")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.worldSpecificBookmarks", true) {
@Override
public boolean onClick(int button) {
super.onClick(button);
@@ -191,8 +223,10 @@ public class NEIClientConfig {
}
});
tag.getTag("inventory.worldSpecificPresets").setComment("Global or world specific presets").getBooleanValue(false);
tag.getTag("inventory.worldSpecificPresets").setComment("Global or world specific presets")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.worldSpecificPresets", true) {
@Override
public boolean onClick(int button) {
super.onClick(button);
@@ -203,24 +237,55 @@ public class NEIClientConfig {
tag.getTag("inventory.bookmarksEnabled").setComment("Enable/disable bookmarks").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.bookmarksEnabled", true));
tag.getTag("inventory.saveCurrentRecipeInBookmarksEnabled").setComment("Save Current Recipe in Bookmarks").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.saveCurrentRecipeInBookmarksEnabled", true));
tag.getTag("inventory.useNBTInBookmarks").setComment("Use NBT in Bookmarks").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.useNBTInBookmarks", true));
tag.getTag("inventory.bookmarksAnimationEnabled").setComment("REI Style Animation in Bookmarks")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.bookmarksAnimationEnabled", true));
tag.getTag("inventory.recipeTooltipsEnabled").setComment("Show recipe tooltips in Bookmarks")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.recipeTooltipsEnabled", true));
tag.getTag("inventory.showRecipeMarker").setComment("Show Recipe Marker").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.showRecipeMarker", true));
tag.getTag("inventory.showItemQuantityWidget").setComment("Show Item Quantity Widget").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.showItemQuantityWidget", true));
tag.getTag("inventory.centerSearchWidget").setComment("Center Search Widget").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.centerSearchWidget", true));
tag.getTag("inventory.jei_style_tabs").setComment("Enable/disable JEI Style Tabs").getBooleanValue(true);
API.addOption(new OptionToggleButtonBoubs("inventory.jei_style_tabs", true));
tag.getTag("inventory.jei_style_item_presence_overlay").setComment("Enable/disable JEI Style item presence overlay on ?-hover").getBooleanValue(true);
tag.getTag("inventory.jei_style_item_presence_overlay")
.setComment("Enable/disable JEI Style item presence overlay on ?-hover").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.jei_style_item_presence_overlay", true));
tag.getTag("inventory.jei_style_recipe_catalyst").setComment("Enable/disable JEI Style Recipe Catalysts").getBooleanValue(true);
tag.getTag("inventory.jei_style_recipe_catalyst").setComment("Enable/disable JEI Style Recipe Catalysts")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.jei_style_recipe_catalyst", true));
tag.getTag("inventory.creative_tab_style").setComment("Creative or JEI style tabs").getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.creative_tab_style", true));
tag.getTag("tools.handler_load_from_config").setComment("ADVANCED: Load handlers from config").getBooleanValue(false);
tag.getTag("inventory.ignore_potion_overlap").setComment("Ignore overlap with potion effect HUD")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.ignore_potion_overlap", true));
tag.getTag("inventory.optimize_gui_overlap_computation").setComment("Optimize computation for GUI overlap")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("inventory.optimize_gui_overlap_computation", true));
tag.getTag("inventory.jei_style_cycled_ingredients").setComment("JEI styled cycled ingredients")
.getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.jei_style_cycled_ingredients", true));
tag.getTag("inventory.shift_overlay_recipe")
.setComment("Require holding shift to move items when overlaying recipe").getBooleanValue(true);
API.addOption(new OptionToggleButton("inventory.shift_overlay_recipe", true));
tag.getTag("tools.handler_load_from_config").setComment("ADVANCED: Load handlers from config")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("tools.handler_load_from_config", true) {
@Override
public boolean onClick(int button) {
super.onClick(button);
@@ -229,8 +294,10 @@ public class NEIClientConfig {
}
});
tag.getTag("tools.catalyst_load_from_config").setComment("ADVANCED: Load catalysts from config").getBooleanValue(false);
tag.getTag("tools.catalyst_load_from_config").setComment("ADVANCED: Load catalysts from config")
.getBooleanValue(false);
API.addOption(new OptionToggleButton("tools.catalyst_load_from_config", true) {
@Override
public boolean onClick(int button) {
super.onClick(button);
@@ -243,8 +310,8 @@ public class NEIClientConfig {
}
private static void linkOptionList() {
OptionList.setOptionList(new OptionList("nei.options")
{
OptionList.setOptionList(new OptionList("nei.options") {
@Override
public ConfigSet globalConfigSet() {
return global;
@@ -268,21 +335,34 @@ public class NEIClientConfig {
}
private static void setDefaultKeyBindings() {
API.addKeyBind("gui.recipe", Keyboard.KEY_R);
API.addKeyBind("gui.usage", Keyboard.KEY_U);
API.addHashBind("gui.recipe", Keyboard.KEY_R);
API.addHashBind("gui.usage", Keyboard.KEY_U);
API.addKeyBind("gui.back", Keyboard.KEY_BACK);
API.addKeyBind("gui.enchant", Keyboard.KEY_X);
API.addKeyBind("gui.potion", Keyboard.KEY_P);
API.addHashBind("gui.enchant", Keyboard.KEY_X);
API.addHashBind("gui.potion", Keyboard.KEY_P);
API.addKeyBind("gui.prev", Keyboard.KEY_PRIOR);
API.addKeyBind("gui.next", Keyboard.KEY_NEXT);
API.addKeyBind("gui.prev_machine", Keyboard.KEY_UP);
API.addKeyBind("gui.next_machine", Keyboard.KEY_DOWN);
API.addKeyBind("gui.prev_recipe", Keyboard.KEY_LEFT);
API.addKeyBind("gui.next_recipe", Keyboard.KEY_RIGHT);
API.addKeyBind("gui.hide", Keyboard.KEY_O);
API.addKeyBind("gui.search", Keyboard.KEY_F);
API.addKeyBind("gui.bookmark", Keyboard.KEY_A);
API.addKeyBind("gui.hide_bookmarks", Keyboard.KEY_B);
API.addHashBind("gui.hide", Keyboard.KEY_O);
API.addHashBind("gui.search", Keyboard.KEY_F);
API.addHashBind("gui.bookmark", Keyboard.KEY_A);
API.addHashBind("gui.bookmark_recipe", Keyboard.KEY_A + NEIClientUtils.SHIFT_HASH);
API.addHashBind("gui.bookmark_count", Keyboard.KEY_A + NEIClientUtils.CTRL_HASH);
API.addHashBind(
"gui.bookmark_recipe_count",
Keyboard.KEY_A + NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.bookmark_pull_items", Keyboard.KEY_V);
API.addHashBind("gui.overlay", Keyboard.KEY_S);
API.addHashBind("gui.overlay_use", Keyboard.KEY_S + NEIClientUtils.SHIFT_HASH);
API.addHashBind("gui.overlay_hide", Keyboard.KEY_S + NEIClientUtils.CTRL_HASH);
API.addHashBind("gui.hide_bookmarks", Keyboard.KEY_B);
API.addKeyBind("gui.getprevioussearch", Keyboard.KEY_UP);
API.addKeyBind("gui.getnextsearch", Keyboard.KEY_DOWN);
API.addHashBind("gui.next_tooltip", Keyboard.KEY_Z);
API.addKeyBind("world.chunkoverlay", Keyboard.KEY_F9);
API.addKeyBind("world.moboverlay", Keyboard.KEY_F7);
API.addKeyBind("world.highlight_tips", Keyboard.KEY_NUMPAD0);
@@ -303,7 +383,7 @@ public class NEIClientConfig {
NEIClientConfig.worldPath = worldPath;
setInternalEnabled(true);
logger.debug("Loading "+(Minecraft.getMinecraft().isSingleplayer() ? "Local" : "Remote")+" World");
logger.debug("Loading " + (Minecraft.getMinecraft().isSingleplayer() ? "Local" : "Remote") + " World");
bootNEI(ClientUtils.getWorld());
final File specificDir = new File(CommonUtils.getMinecraftDir(), "saves/NEI/" + worldPath);
@@ -320,16 +400,17 @@ public class NEIClientConfig {
}
private static void onWorldLoad(boolean newWorld) {
world.config.setComment("World based configuration of NEI.\nMost of these options can be changed ingame.\nDeleting any element will restore it to it's default value");
world.config.setComment(
"World based configuration of NEI.\nMost of these options can be changed ingame.\nDeleting any element will restore it to it's default value");
setWorldDefaults();
creativeInv = new ItemStack[54];
LayoutManager.searchField.setText(getSearchExpression());
LayoutManager.quantity.setText(Integer.toString(getItemQuantity()));
ItemPanels.itemPanel.quantity.setText(Integer.toString(getItemQuantity()));
SubsetWidget.loadHidden();
if (newWorld && Minecraft.getMinecraft().isSingleplayer())
world.config.getTag("inventory.cheatmode").setIntValue(NEIClientUtils.mc().playerController.isInCreativeMode() ? 2 : 0);
if (newWorld && Minecraft.getMinecraft().isSingleplayer()) world.config.getTag("inventory.cheatmode")
.setIntValue(NEIClientUtils.mc().playerController.isInCreativeMode() ? 2 : 0);
NEIInfo.load(ClientUtils.getWorld());
}
@@ -344,30 +425,69 @@ public class NEIClientConfig {
}
public static int getKeyBinding(String string) {
return getSetting("keys." + string).getIntValue();
return getSetting("keys." + string).getIntValue(Keyboard.KEY_NONE);
}
public static void setDefaultKeyBinding(String string, int key) {
getSetting("keys." + string).getIntValue(key);
}
public static void bootNEI(World world) {
if (configLoaded)
return;
public static boolean isKeyHashDown(String string) {
final int hash = getKeyBinding(string);
return hash != Keyboard.CHAR_NONE && hash == NEIClientUtils.getKeyHash();
}
public static String getKeyName(int keyBind, boolean useHash) {
return getKeyName(keyBind, useHash, false);
}
public static String getKeyName(int keyBind, boolean useHash, boolean showOnlyHash) {
String keyText = "";
if (useHash) {
final String DELIMITER = " + ";
if ((keyBind & NEIClientUtils.CTRL_HASH) != 0) {
keyText += NEIClientUtils.translate(Minecraft.isRunningOnMac ? "key.ctrl.mac" : "key.ctrl") + DELIMITER;
}
if ((keyBind & NEIClientUtils.SHIFT_HASH) != 0) {
keyText += "SHIFT" + DELIMITER;
}
if ((keyBind & NEIClientUtils.ALT_HASH) != 0) {
keyText += "ALT" + DELIMITER;
}
}
if (!showOnlyHash) {
keyText += Keyboard.getKeyName(unHashKey(keyBind));
}
return keyText;
}
public static int unHashKey(int keyBind) {
return keyBind & ~(NEIClientUtils.CTRL_HASH | NEIClientUtils.SHIFT_HASH | NEIClientUtils.ALT_HASH);
}
public static void bootNEI(World world) {
if (mainNEIConfigLoaded) return;
// main NEI config loading
ItemInfo.load(world);
GuiInfo.load();
RecipeInfo.load();
LayoutManager.load();
NEIController.load();
RecipeCatalysts.loadCatalystInfo();
configLoaded = true;
BookmarkContainerInfo.load();
mainNEIConfigLoaded = true;
new Thread("NEI Plugin Loader") {
@Override
public void run() {
ClassDiscoverer classDiscoverer = new ClassDiscoverer(test -> test.startsWith("NEI") && test.endsWith("Config.class"), IConfigureNEI.class);
logger.debug("Started NEI plugin loading");
ClassDiscoverer classDiscoverer = new ClassDiscoverer(
test -> test.startsWith("NEI") && test.endsWith("Config.class"),
IConfigureNEI.class);
classDiscoverer.findClasses();
@@ -382,15 +502,21 @@ public class NEIClientConfig {
}
}
// Set pluginNEIConfigLoaded here before posting the NEIConfigsLoadedEvent. This used to be the other
// way around, but apparently if your modpack includes 800 mods the event poster might not return in
// time and cause issues when loading a world for a second time as configLoaded is still false. This may
// cause issues in case one of the event handler calls the (non-thread-safe) NEI API. I don't expect any
// handler to do this, but who knows what modders have come up with...
pluginNEIConfigLoaded = true;
logger.debug("NEI plugin loading finished");
MinecraftForge.EVENT_BUS.post(new NEIConfigsLoadedEvent());
}
}.start();
ItemSorter.loadConfig();
}
private static void initBookmarkFile(String worldPath)
{
private static void initBookmarkFile(String worldPath) {
if (!global.config.getTag("inventory.worldSpecificBookmarks").getBooleanValue()) {
worldPath = "global";
}
@@ -398,9 +524,8 @@ public class NEIClientConfig {
ItemPanels.bookmarkPanel.setBookmarkFile(worldPath);
}
private static void initPresetsFile(String worldPath)
{
private static void initPresetsFile(String worldPath) {
if (!global.config.getTag("inventory.worldSpecificPresets").getBooleanValue()) {
worldPath = "global";
}
@@ -409,7 +534,7 @@ public class NEIClientConfig {
}
public static boolean isWorldSpecific(String setting) {
if(world == null) return false;
if (world == null) return false;
ConfigTag tag = world.config.getTag(setting, false);
return tag != null && tag.value != null;
}
@@ -425,33 +550,79 @@ public class NEIClientConfig {
public static boolean isHidden() {
return !enabledOverride || getBooleanSetting("inventory.hidden");
}
public static boolean isBookmarkPanelHidden() {
return !getBooleanSetting("inventory.bookmarksEnabled");
}
public static boolean saveCurrentRecipeInBookmarksEnabled() {
return getBooleanSetting("inventory.saveCurrentRecipeInBookmarksEnabled");
}
public static boolean useNBTInBookmarks() {
return getBooleanSetting("inventory.useNBTInBookmarks");
}
public static boolean areBookmarksAnimated() {
return getBooleanSetting("inventory.bookmarksAnimationEnabled");
}
public static boolean showRecipeTooltips() {
return getBooleanSetting("inventory.recipeTooltipsEnabled");
}
public static boolean showRecipeMarker() {
return getBooleanSetting("inventory.showRecipeMarker");
}
public static boolean showItemQuantityWidget() {
return getBooleanSetting("inventory.showItemQuantityWidget");
}
public static boolean isSearchWidgetCentered() {
return getBooleanSetting("inventory.centerSearchWidget");
}
public static boolean areJEIStyleTabsVisible() {
return getBooleanSetting("inventory.jei_style_tabs");
}
public static boolean isJEIStyleItemPresenceOverlayVisible() {
return getBooleanSetting("inventory.jei_style_item_presence_overlay");
}
public static boolean areJEIStyleRecipeCatalystsVisible() {
return getBooleanSetting("inventory.jei_style_recipe_catalyst");
}
public static boolean useCreativeTabStyle() {
return getBooleanSetting("inventory.creative_tab_style");
}
public static boolean ignorePotionOverlap() {
return getBooleanSetting("inventory.ignore_potion_overlap");
}
public static boolean optimizeGuiOverlapComputation() {
return getBooleanSetting("inventory.optimize_gui_overlap_computation");
}
public static boolean useJEIStyledCycledIngredients() {
return getBooleanSetting("inventory.jei_style_cycled_ingredients");
}
public static boolean requireShiftForOverlayRecipe() {
return getBooleanSetting("inventory.shift_overlay_recipe");
}
public static boolean isEnabled() {
return enabledOverride && getBooleanSetting("inventory.widgetsenabled");
}
public static boolean isLoaded() {
return mainNEIConfigLoaded && pluginNEIConfigLoaded;
}
public static boolean loadHandlersFromJar() {
return !getBooleanSetting("tools.handler_load_from_config");
}
public static boolean loadCatalystsFromJar() {
return !getBooleanSetting("tools.catalyst_load_from_config");
}
@@ -469,8 +640,7 @@ public class NEIClientConfig {
}
private static void checkCheatMode() {
if (getLockedMode() != -1)
setIntSetting("inventory.cheatmode", getLockedMode());
if (getLockedMode() != -1) setIntSetting("inventory.cheatmode", getLockedMode());
}
public static int getLockedMode() {
@@ -489,7 +659,7 @@ public class NEIClientConfig {
int i = getIntSetting("inventory.itemIDs");
return i == 2 || (i == 1 && isEnabled() && !isHidden());
}
public static int getItemLoadingTimeout() {
return getIntSetting("itemLoadingTimeout");
}
@@ -529,6 +699,10 @@ public class NEIClientConfig {
return !getBooleanSetting("inventory.invertMouseScrollTransfer");
}
public static boolean shouldCacheItemRendering() {
return getBooleanSetting("inventory.cacheItemRendering") && OpenGlHelper.framebufferSupported;
}
public static boolean getMagnetMode() {
return enabledActions.contains("magnet");
}
@@ -558,18 +732,14 @@ public class NEIClientConfig {
}
public static boolean canPerformAction(String name) {
if (!isEnabled())
return false;
if (!isEnabled()) return false;
if (!modePermitsAction(name))
return false;
if (!modePermitsAction(name)) return false;
String base = NEIActions.base(name);
if (hasSMPCounterpart)
return permissableActions.contains(base);
if (hasSMPCounterpart) return permissableActions.contains(base);
if (NEIActions.smpRequired(name))
return false;
if (NEIActions.smpRequired(name)) return false;
String cmd = getStringSetting("command." + base);
return cmd != null && cmd.startsWith("/");
@@ -580,9 +750,7 @@ public class NEIClientConfig {
if (getCheatMode() == 2) return true;
String[] actions = getStringArrSetting("inventory.utilities");
for (String action : actions)
if (action.equalsIgnoreCase(name))
return true;
for (String action : actions) if (action.equalsIgnoreCase(name)) return true;
return false;
}
@@ -597,8 +765,7 @@ public class NEIClientConfig {
public static void reloadSaves() {
File saveDir = new File(CommonUtils.getMinecraftDir(), "saves/NEI/local");
if (!saveDir.exists())
return;
if (!saveDir.exists()) return;
List<SaveFormatComparator> saves;
try {
@@ -608,12 +775,9 @@ public class NEIClientConfig {
return;
}
HashSet<String> saveFileNames = new HashSet<>();
for (SaveFormatComparator save : saves)
saveFileNames.add(save.getFileName());
for (SaveFormatComparator save : saves) saveFileNames.add(save.getFileName());
for (File file : saveDir.listFiles())
if (file.isDirectory() && !saveFileNames.contains(file.getName()))
ObfuscationRun.deleteDir(file, true);
if (file.isDirectory() && !saveFileNames.contains(file.getName())) ObfuscationRun.deleteDir(file, true);
}
}
+218 -109
View File
@@ -1,46 +1,68 @@
package codechicken.nei;
import static codechicken.nei.NEIClientConfig.canCheatItem;
import static codechicken.nei.NEIClientConfig.canPerformAction;
import static codechicken.nei.NEIClientConfig.getStringArrSetting;
import static codechicken.nei.NEIClientConfig.getStringSetting;
import static codechicken.nei.NEIClientConfig.hasSMPCounterPart;
import static codechicken.nei.NEIClientConfig.invCreativeMode;
import static codechicken.nei.NEIClientConfig.world;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import com.google.common.collect.Iterables;
import codechicken.lib.inventory.InventoryRange;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.util.LangProxy;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IInfiniteItemHandler;
import codechicken.nei.api.ItemInfo;
import com.google.common.collect.Iterables;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class NEIClientUtils extends NEIServerUtils {
import static codechicken.nei.NEIClientConfig.canCheatItem;
import static codechicken.nei.NEIClientConfig.canPerformAction;
import static codechicken.nei.NEIClientConfig.getItemQuantity;
import static codechicken.nei.NEIClientConfig.getStringArrSetting;
import static codechicken.nei.NEIClientConfig.getStringSetting;
import static codechicken.nei.NEIClientConfig.hasSMPCounterPart;
import static codechicken.nei.NEIClientConfig.invCreativeMode;
import static codechicken.nei.NEIClientConfig.world;
public class NEIClientUtils extends NEIServerUtils
{
public static LangProxy lang = new LangProxy("nei");
/** Formats a number with group separator and at most 2 fraction digits. */
private static final Map<Locale, DecimalFormat> decimalFormatters = new HashMap<>();
public static final int ALT_HASH = 1 << 27;
public static final int SHIFT_HASH = 1 << 26;
public static final int CTRL_HASH = 1 << 25;
public static Minecraft mc() {
return Minecraft.getMinecraft();
}
@@ -50,8 +72,33 @@ public class NEIClientUtils extends NEIServerUtils
}
public static void printChatMessage(IChatComponent msg) {
if (mc().ingameGUI != null)
mc().ingameGUI.getChatGUI().printChatMessage(msg);
if (mc().ingameGUI != null) mc().ingameGUI.getChatGUI().printChatMessage(msg);
}
private static DecimalFormat getDecimalFormat() {
return decimalFormatters.computeIfAbsent(Locale.getDefault(Locale.Category.FORMAT), locale -> {
DecimalFormat numberFormat = new DecimalFormat(); // uses the necessary locale inside anyway
numberFormat.setGroupingUsed(true);
numberFormat.setMaximumFractionDigits(2);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
DecimalFormatSymbols decimalFormatSymbols = numberFormat.getDecimalFormatSymbols();
decimalFormatSymbols.setGroupingSeparator(','); // Use sensible separator for best clarity.
numberFormat.setDecimalFormatSymbols(decimalFormatSymbols);
return numberFormat;
});
}
public static String formatNumbers(BigInteger aNumber) {
return getDecimalFormat().format(aNumber);
}
public static String formatNumbers(long aNumber) {
return getDecimalFormat().format(aNumber);
}
public static String formatNumbers(double aNumber) {
return getDecimalFormat().format(aNumber);
}
public static void deleteHeldItem() {
@@ -59,7 +106,8 @@ public class NEIClientUtils extends NEIServerUtils
}
public static void dropHeldItem() {
mc().playerController.windowClick(((GuiContainer) mc().currentScreen).inventorySlots.windowId, -999, 0, 0, mc().thePlayer);
mc().playerController
.windowClick(((GuiContainer) mc().currentScreen).inventorySlots.windowId, -999, 0, 0, mc().thePlayer);
}
public static void deleteSlotStack(int slotNumber) {
@@ -67,12 +115,11 @@ public class NEIClientUtils extends NEIServerUtils
}
public static void decreaseSlotStack(int slotNumber) {
ItemStack stack = slotNumber == -999 ? getHeldItem() : mc().thePlayer.openContainer.getSlot(slotNumber).getStack();
if (stack == null)
return;
ItemStack stack = slotNumber == -999 ? getHeldItem()
: mc().thePlayer.openContainer.getSlot(slotNumber).getStack();
if (stack == null) return;
if (stack.stackSize == 1)
deleteSlotStack(slotNumber);
if (stack.stackSize == 1) deleteSlotStack(slotNumber);
else {
stack = stack.copy();
stack.stackSize--;
@@ -88,8 +135,7 @@ public class NEIClientUtils extends NEIServerUtils
Container c = getGuiContainer().inventorySlots;
for (int i = 0; i < c.inventorySlots.size(); i++) {
Slot slot = c.getSlot(i);
if (slot == null)
continue;
if (slot == null) continue;
ItemStack stack = slot.getStack();
if (stack != null && stack.getItem() == type.getItem() && stack.getItemDamage() == type.getItemDamage()) {
@@ -106,21 +152,18 @@ public class NEIClientUtils extends NEIServerUtils
public static void setSlotContents(int slot, ItemStack item, boolean containerInv) {
NEICPH.sendSetSlot(slot, item, containerInv);
if (slot == -999)
mc().thePlayer.inventory.setItemStack(item);
if (slot == -999) mc().thePlayer.inventory.setItemStack(item);
}
/**
* @param mode -1 = normal cheats, 0 = no infinites, 1 = replenish stack
* @param mode -1 = normal cheats, 0 = no infinites, 1 = replenish stack
*/
public static void cheatItem(ItemStack stack, int button, int mode) {
if (!canCheatItem(stack))
return;
if (!canCheatItem(stack)) return;
if (mode == -1 && button == 0 && shiftKey() && NEIClientConfig.hasSMPCounterPart()) {
for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers) {
if (!handler.canHandleItem(stack))
continue;
if (!handler.canHandleItem(stack)) continue;
ItemStack inf = handler.getInfiniteItem(stack);
if (inf != null) {
@@ -152,25 +195,24 @@ public class NEIClientUtils extends NEIServerUtils
ItemStack stack = copyStack(base, i);
if (hasSMPCounterPart()) {
ItemStack typestack = copyStack(stack, 1);
if (!infinite && !canItemFitInInventory(mc().thePlayer, stack) && (mc().currentScreen instanceof GuiContainer)) {
if (!infinite && !canItemFitInInventory(mc().thePlayer, stack)
&& (mc().currentScreen instanceof GuiContainer)) {
GuiContainer gui = getGuiContainer();
final List<Iterable<Integer>> handlerSlots;
try {
GuiInfo.readLock.lock();
handlerSlots = GuiInfo.guiHandlers.stream()
.map(handler -> handler.getItemSpawnSlots(gui, typestack))
.filter(x -> x != null)
.collect(Collectors.toCollection(LinkedList::new));
.map(handler -> handler.getItemSpawnSlots(gui, typestack)).filter(x -> x != null)
.collect(Collectors.toCollection(LinkedList::new));
} finally {
GuiInfo.readLock.unlock();
}
int increment = typestack.getMaxStackSize();
int given = 0;
for(int slotNo : Iterables.concat(handlerSlots)) {
for (int slotNo : Iterables.concat(handlerSlots)) {
Slot slot = gui.inventorySlots.getSlot(slotNo);
if(!slot.isItemValid(typestack) || !InventoryUtils.canStack(slot.getStack(), typestack))
continue;
if (!slot.isItemValid(typestack) || !InventoryUtils.canStack(slot.getStack(), typestack)) continue;
int qty = Math.min(stack.stackSize - given, increment);
int current = slot.getHasStack() ? slot.getStack().stackSize : 0;
@@ -180,17 +222,15 @@ public class NEIClientUtils extends NEIServerUtils
slot.putStack(newStack);
setSlotContents(slotNo, newStack, true);
given += qty;
if(given >= stack.stackSize)
break;
if (given >= stack.stackSize) break;
}
if(given > 0)
NEICPH.sendGiveItem(copyStack(typestack, given), false, false);
} else
NEICPH.sendGiveItem(stack, infinite, true);
if (given > 0) NEICPH.sendGiveItem(copyStack(typestack, given), false, false);
} else NEICPH.sendGiveItem(stack, infinite, true);
} else {
for (int given = 0; given < stack.stackSize; ) {
for (int given = 0; given < stack.stackSize;) {
int qty = Math.min(stack.stackSize - given, stack.getMaxStackSize());
sendCommand(getStringSetting("command.item"),
sendCommand(
getStringSetting("command.item"),
mc().thePlayer.getCommandSenderName(),
Item.getIdFromItem(stack.getItem()),
qty,
@@ -211,24 +251,22 @@ public class NEIClientUtils extends NEIServerUtils
}
public static boolean controlKey() {
if (Minecraft.isRunningOnMac) {
return Keyboard.isKeyDown(Keyboard.KEY_LMETA) || Keyboard.isKeyDown(Keyboard.KEY_RMETA);
}
return Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL);
}
public static int getGamemode() {
if (invCreativeMode())
return 2;
else if (mc().playerController.isInCreativeMode())
return 1;
else if (mc().playerController.currentGameType.isAdventure())
return 3;
else
return 0;
if (invCreativeMode()) return 2;
else if (mc().playerController.isInCreativeMode()) return 1;
else if (mc().playerController.currentGameType.isAdventure()) return 3;
else return 0;
}
public static boolean isValidGamemode(String s) {
return s.equals("survival") ||
canPerformAction(s) &&
Arrays.asList(getStringArrSetting("inventory.gamemodes")).contains(s);
return s.equals("survival")
|| canPerformAction(s) && Arrays.asList(getStringArrSetting("inventory.gamemodes")).contains(s);
}
public static int getNextGamemode() {
@@ -236,8 +274,7 @@ public class NEIClientUtils extends NEIServerUtils
int nmode = mode;
while (true) {
nmode = (nmode + 1) % NEIActions.gameModes.length;
if (nmode == mode || isValidGamemode(NEIActions.gameModes[nmode]))
break;
if (nmode == mode || isValidGamemode(NEIActions.gameModes[nmode])) break;
}
return nmode;
}
@@ -245,13 +282,13 @@ public class NEIClientUtils extends NEIServerUtils
public static void cycleGamemode() {
int mode = getGamemode();
int nmode = getNextGamemode();
if (mode == nmode)
return;
if (mode == nmode) return;
if (hasSMPCounterPart())
NEICPH.sendGamemode(nmode);
else
sendCommand(getStringSetting("command.creative"), getGameType(nmode), mc().thePlayer.getCommandSenderName());
if (hasSMPCounterPart()) NEICPH.sendGamemode(nmode);
else sendCommand(
getStringSetting("command.creative"),
getGameType(nmode),
mc().thePlayer.getCommandSenderName());
}
public static long getTime() {
@@ -266,22 +303,18 @@ public class NEIClientUtils extends NEIServerUtils
long day = (getTime() / 24000L) * 24000L;
long newTime = day + 24000L + hour * 1000;
if (hasSMPCounterPart())
NEICPH.sendSetTime(hour);
else
sendCommand(getStringSetting("command.time"), newTime);
if (hasSMPCounterPart()) NEICPH.sendSetTime(hour);
else sendCommand(getStringSetting("command.time"), newTime);
}
public static void sendCommand(String command, Object... args) {
if (command.length() == 0)
return;
if (command.length() == 0) return;
NumberFormat numberformat = NumberFormat.getIntegerInstance();
numberformat.setGroupingUsed(false);
MessageFormat messageformat = new MessageFormat(command);
for (int i = 0; i < args.length; i++)
if (args[i] instanceof Integer || args[i] instanceof Long)
messageformat.setFormatByArgumentIndex(i, numberformat);
for (int i = 0; i < args.length; i++) if (args[i] instanceof Integer || args[i] instanceof Long)
messageformat.setFormatByArgumentIndex(i, numberformat);
mc().thePlayer.sendChatMessage(messageformat.format(args));
}
@@ -291,22 +324,17 @@ public class NEIClientUtils extends NEIServerUtils
}
public static void toggleRaining() {
if (hasSMPCounterPart())
NEICPH.sendToggleRain();
else
sendCommand(getStringSetting("command.rain"), isRaining() ? 0 : 1);
if (hasSMPCounterPart()) NEICPH.sendToggleRain();
else sendCommand(getStringSetting("command.rain"), isRaining() ? 0 : 1);
}
public static void healPlayer() {
if (hasSMPCounterPart())
NEICPH.sendHeal();
else
sendCommand(getStringSetting("command.heal"), mc().thePlayer.getCommandSenderName());
if (hasSMPCounterPart()) NEICPH.sendHeal();
else sendCommand(getStringSetting("command.heal"), mc().thePlayer.getCommandSenderName());
}
public static void toggleMagnetMode() {
if (hasSMPCounterPart())
NEICPH.sendToggleMagnetMode();
if (hasSMPCounterPart()) NEICPH.sendToggleMagnetMode();
}
public static ArrayList<int[]> concatIntegersToRanges(List<Integer> damages) {
@@ -322,24 +350,40 @@ public class NEIClientUtils extends NEIServerUtils
continue;
}
if (next + 1 != i) {
ranges.add(new int[]{start, next});
ranges.add(new int[] { start, next });
start = next = i;
continue;
}
next = i;
}
ranges.add(new int[]{start, next});
ranges.add(new int[] { start, next });
return ranges;
}
public static ArrayList<int[]> addIntegersToRanges(List<int[]> ranges, List<Integer> damages) {
for (int[] range : ranges)
for (int integer = range[0]; integer <= range[1]; integer++)
damages.add(integer);
for (int[] range : ranges) for (int integer = range[0]; integer <= range[1]; integer++) damages.add(integer);
return concatIntegersToRanges(damages);
}
public static String cropText(FontRenderer fontRenderer, String text, int containerWidth) {
int textWidth = fontRenderer.getStringWidth(text);
if (textWidth > containerWidth) {
textWidth += fontRenderer.getStringWidth("...");
while (textWidth > containerWidth) {
textWidth -= fontRenderer.getCharWidth(text.charAt(text.length() - 1));
text = text.substring(0, text.length() - 1);
}
return text + "...";
}
return text;
}
public static boolean safeKeyDown(int keyCode) {
try {
return Keyboard.isKeyDown(keyCode);
@@ -354,8 +398,7 @@ public class NEIClientUtils extends NEIServerUtils
}
public static GuiContainer getGuiContainer() {
if (mc().currentScreen instanceof GuiContainer)
return (GuiContainer) mc().currentScreen;
if (mc().currentScreen instanceof GuiContainer) return (GuiContainer) mc().currentScreen;
return null;
}
@@ -364,7 +407,73 @@ public class NEIClientUtils extends NEIServerUtils
return Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU);
}
public static int getMetaHash() {
if (Keyboard.getEventKeyState()) {
int hash = 0;
if (altKey()) {
hash = hash | ALT_HASH;
}
if (shiftKey()) {
hash = hash | SHIFT_HASH;
}
if (controlKey()) {
hash = hash | CTRL_HASH;
}
return hash;
}
return 0;
}
public static int getKeyHash() {
if (Keyboard.getEventKeyState()) {
final int keycode = Keyboard.getEventKey();
if (keycode != Keyboard.KEY_LSHIFT && keycode != Keyboard.KEY_RSHIFT
&& keycode != Keyboard.KEY_LCONTROL
&& keycode != Keyboard.KEY_RCONTROL
&& keycode != Keyboard.KEY_LMENU
&& keycode != Keyboard.KEY_RMENU) {
return getMetaHash() + keycode;
}
}
return Keyboard.CHAR_NONE;
}
public static void playClickSound() {
mc().getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F));
mc().getSoundHandler()
.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F));
}
public static void reportErrorBuffered(Throwable e, Set<String> buffer, String cause) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stackTrace = cause + sw;
if (buffer.contains(stackTrace)) return;
System.err.println("Error while rendering: " + cause);
e.printStackTrace();
buffer.add(stackTrace);
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player != null) {
IChatComponent chat = new ChatComponentTranslation("nei.chat.render.error");
chat.getChatStyle().setColor(EnumChatFormatting.RED);
player.addChatComponentMessage(chat);
}
}
public static void reportErrorBuffered(Throwable e, Set<String> buffer, ItemStack cause) {
if (cause != null) {
reportErrorBuffered(e, buffer, cause.toString());
} else {
reportErrorBuffered(e, buffer, "null");
}
}
}
@@ -1,5 +1,4 @@
package codechicken.nei;
public class NEICompatibility
{
public class NEICompatibility {
}
@@ -1,5 +1,17 @@
package codechicken.nei;
import static codechicken.lib.gui.GuiDraw.getMousePosition;
import java.awt.Point;
import java.util.LinkedList;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.ItemStack;
import codechicken.nei.api.API;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.IInfiniteItemHandler;
@@ -8,20 +20,10 @@ import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerSlotClickHandler;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.ItemStack;
import codechicken.nei.recipe.GuiRecipe;
import java.awt.Point;
import java.util.LinkedList;
public class NEIController implements IContainerSlotClickHandler, IContainerInputHandler {
import static codechicken.lib.gui.GuiDraw.getMousePosition;
public class NEIController implements IContainerSlotClickHandler, IContainerInputHandler
{
private static final NEIController instance = new NEIController();
public static GuiContainerManager manager;
@@ -44,12 +46,10 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
deleteMode = false;
GuiInfo.clearGuiHandlers();
fastTransferManager = null;
if (!NEIClientConfig.isEnabled())
return;
if (!NEIClientConfig.isEnabled()) return;
fastTransferManager = new FastTransferManager();
if (gui instanceof INEIGuiHandler)
API.registerNEIGuiHandler((INEIGuiHandler) gui);
if (gui instanceof INEIGuiHandler) API.registerNEIGuiHandler((INEIGuiHandler) gui);
}
public static boolean isSpreading(GuiContainer gui) {
@@ -57,8 +57,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
}
public static void updateUnlimitedItems(InventoryPlayer inventory) {
if (!NEIClientConfig.canPerformAction("item") || !NEIClientConfig.hasSMPCounterPart())
return;
if (!NEIClientConfig.canPerformAction("item") || !NEIClientConfig.hasSMPCounterPart()) return;
LinkedList<ItemStack> beforeStacks = new LinkedList<>();
for (int i = 0; i < inventory.getSizeInventory(); i++)
@@ -66,8 +65,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack stack = inventory.getStackInSlot(i);
if (stack == null)
continue;
if (stack == null) continue;
for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers)
if (handler.canHandleItem(stack) && handler.isItemInfinite(stack))
@@ -78,8 +76,8 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
ItemStack newstack = inventory.getStackInSlot(i);
if (!NEIServerUtils.areStacksIdentical(beforeStacks.get(i), newstack)) {
inventory.setInventorySlotContents(i, beforeStacks.get(i));//restore in case of SMP fail
NEIClientUtils.setSlotContents(i, newstack, false);//sends via SMP handler ;)
inventory.setInventorySlotContents(i, beforeStacks.get(i)); // restore in case of SMP fail
NEIClientUtils.setSlotContents(i, newstack, false); // sends via SMP handler ;)
}
}
}
@@ -87,14 +85,15 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
public static void processCreativeCycling(InventoryPlayer inventory) {
if (NEIClientConfig.invCreativeMode() && NEIClientUtils.controlKey()) {
if (selectedItem != inventory.currentItem) {
if (inventory.currentItem == selectedItem + 1 || (inventory.currentItem == 0 && selectedItem == 8))//foward
if (inventory.currentItem == selectedItem + 1 || (inventory.currentItem == 0 && selectedItem == 8)) // foward
{
NEICPH.sendCreativeScroll(1);
inventory.currentItem = selectedItem;
} else if (inventory.currentItem == selectedItem - 1 || (inventory.currentItem == 8 && selectedItem == 0)) {
NEICPH.sendCreativeScroll(-1);
inventory.currentItem = selectedItem;
}
} else if (inventory.currentItem == selectedItem - 1
|| (inventory.currentItem == 8 && selectedItem == 0)) {
NEICPH.sendCreativeScroll(-1);
inventory.currentItem = selectedItem;
}
}
}
@@ -103,51 +102,47 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
@Override
public void beforeSlotClick(GuiContainer gui, int slotIndex, int button, Slot slot, int modifier) {
if (!NEIClientConfig.isEnabled())
return;
if (!NEIClientConfig.isEnabled()) return;
firstheld = NEIClientUtils.getHeldItem();
}
@Override
public boolean handleSlotClick(GuiContainer gui, int slotIndex, int button, Slot slot, int modifier, boolean eventconsumed) {
if (eventconsumed ||
!NEIClientConfig.isEnabled() ||
isSpreading(gui))
return eventconsumed;
public boolean handleSlotClick(GuiContainer gui, int slotIndex, int button, Slot slot, int modifier,
boolean eventconsumed) {
if (eventconsumed || !NEIClientConfig.isEnabled() || isSpreading(gui)) return eventconsumed;
if (deleteMode && slotIndex >= 0 && slot != null) {
if (NEIClientUtils.shiftKey() && button == 0) {
ItemStack itemstack1 = slot.getStack();
if (itemstack1 != null)
NEIClientUtils.deleteItemsOfType(itemstack1);
if (itemstack1 != null) NEIClientUtils.deleteItemsOfType(itemstack1);
} else if (button == 1)
NEIClientUtils.decreaseSlotStack(slot.slotNumber);
else
NEIClientUtils.deleteSlotStack(slot.slotNumber);
} else if (button == 1) NEIClientUtils.decreaseSlotStack(slot.slotNumber);
else NEIClientUtils.deleteSlotStack(slot.slotNumber);
return true;
}
if (button == 1 && slot instanceof SlotCrafting)//right click
if (button == 1 && slot instanceof SlotCrafting) // right click
{
for (int i1 = 0; i1 < 64; i1++)//click this slot 64 times
for (int i1 = 0; i1 < 64; i1++) // click this slot 64 times
manager.handleSlotClick(slot.slotNumber, button, 0);
return true;
}
if (NEIClientUtils.controlKey()
&& modifier != 4//Drop key pressed: net.minecraft.client.gui.inventory.GuiContainer.keyTyped
&& slot != null && slot.getStack() != null
if (NEIClientUtils.controlKey() && modifier != 4 // Drop key pressed:
// net.minecraft.client.gui.inventory.GuiContainer.keyTyped
&& slot != null
&& slot.getStack() != null
&& slot.isItemValid(slot.getStack())) {
NEIClientUtils.cheatItem(slot.getStack(), button, 1);
return true;
}
if(GuiInfo.hasCustomSlots(gui))
return false;
if (GuiInfo.hasCustomSlots(gui)) return false;
if (slotIndex >= 0 && NEIClientUtils.shiftKey() && NEIClientUtils.getHeldItem() != null && !slot.getHasStack()) {
if (slotIndex >= 0 && NEIClientUtils.shiftKey()
&& NEIClientUtils.getHeldItem() != null
&& !slot.getHasStack()) {
ItemStack held = NEIClientUtils.getHeldItem();
manager.handleSlotClick(slot.slotNumber, button, 0);
if (slot.isItemValid(held) && !ItemInfo.fastTransferExemptions.contains(slot.getClass()))
@@ -166,16 +161,15 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
@Override
public void afterSlotClick(GuiContainer gui, int slotIndex, int button, Slot slot, int modifier) {
if (!NEIClientConfig.isEnabled())
return;
if (!NEIClientConfig.isEnabled()) return;
ItemStack nowHeld = NEIClientUtils.getHeldItem();
if (firstheld != nowHeld)
pickedUpFromSlot = slotIndex;
if (firstheld != nowHeld) pickedUpFromSlot = slotIndex;
if (NEIClientConfig.canPerformAction("item") && NEIClientConfig.hasSMPCounterPart()) {
if (heldStackInfinite != null && slot != null && slot.inventory == NEIClientUtils.mc().thePlayer.inventory) {
if (heldStackInfinite != null && slot != null
&& slot.inventory == NEIClientUtils.mc().thePlayer.inventory) {
ItemStack stack = slot.getStack();
if (stack != null) {
heldStackInfinite.onPlaceInfinite(stack);
@@ -183,8 +177,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
NEIClientUtils.setSlotContents(slotIndex, stack, true);
}
if (firstheld != nowHeld)
heldStackInfinite = null;
if (firstheld != nowHeld) heldStackInfinite = null;
if (firstheld != nowHeld && nowHeld != null) {
for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers) {
@@ -201,14 +194,10 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyCode) {
if (!NEIClientConfig.isEnabled() ||
GuiInfo.hasCustomSlots(gui) ||
isSpreading(gui))
return false;
if (!NEIClientConfig.isEnabled() || GuiInfo.hasCustomSlots(gui) || isSpreading(gui)) return false;
Slot slot = GuiContainerManager.getSlotMouseOver(gui);
if (slot == null)
return false;
if (slot == null) return false;
int slotIndex = slot.slotNumber;
@@ -225,19 +214,22 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
@Override
public boolean mouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {
if (!NEIClientConfig.isEnabled() || GuiInfo.hasCustomSlots(gui) || !NEIClientConfig.isMouseScrollTransferEnabled())
if (!NEIClientConfig.isEnabled() || GuiInfo.hasCustomSlots(gui)
|| !NEIClientConfig.isMouseScrollTransferEnabled())
return false;
// slot in GuiRecipe does not contain actual stack
// and scroll should be handled by GuiRecipe, not here
if (gui instanceof GuiRecipe) return false;
Point mousePos = getMousePosition();
Slot mouseover = manager.window.getSlotAtPosition(mousePos.x, mousePos.y);
if (mouseover != null && mouseover.getHasStack()) {
if(NEIClientConfig.shouldInvertMouseScrollTransfer()) {
if (NEIClientConfig.shouldInvertMouseScrollTransfer()) {
scrolled = -scrolled;
}
if (scrolled > 0)
fastTransferManager.transferItem(manager.window, mouseover.slotNumber);
else
fastTransferManager.retrieveItem(manager.window, mouseover.slotNumber);
if (scrolled > 0) fastTransferManager.transferItem(manager.window, mouseover.slotNumber);
else fastTransferManager.retrieveItem(manager.window, mouseover.slotNumber);
return true;
}
return false;
@@ -254,32 +246,26 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
}
@Override
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID) {
}
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID) {}
@Override
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
}
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button) {}
@Override
public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime) {
}
public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime) {}
@Override
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {
}
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {}
@Override
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button) {
}
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button) {}
public static boolean canUseDeleteMode() {
return !(NEIClientUtils.getGuiContainer() instanceof GuiContainerCreative);
}
public static void toggleDeleteMode() {
if(canUseDeleteMode())
deleteMode = !deleteMode;
if (canUseDeleteMode()) deleteMode = !deleteMode;
}
public static boolean getDeleteMode() {
@@ -1,22 +1,20 @@
package codechicken.nei;
import codechicken.nei.api.INEIGuiAdapter;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.creativetab.CreativeTabs;
public class NEICreativeGuiHandler extends INEIGuiAdapter
{
import codechicken.nei.api.INEIGuiAdapter;
public class NEICreativeGuiHandler extends INEIGuiAdapter {
@Override
public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility)
{
if(!(gui instanceof GuiContainerCreative))
return currentVisibility;
if(((GuiContainerCreative)gui).func_147056_g() != CreativeTabs.tabInventory.getTabIndex())
public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) {
if (!(gui instanceof GuiContainerCreative)) return currentVisibility;
if (((GuiContainerCreative) gui).func_147056_g() != CreativeTabs.tabInventory.getTabIndex())
currentVisibility.showItemSection = currentVisibility.enableDeleteMode = false;
return currentVisibility;
}
}
@@ -1,21 +1,21 @@
package codechicken.nei;
import codechicken.lib.inventory.ContainerExtended;
import codechicken.lib.inventory.SlotDummy;
import codechicken.nei.api.INEIGuiAdapter;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class NEIDummySlotHandler extends INEIGuiAdapter
{
import codechicken.lib.inventory.ContainerExtended;
import codechicken.lib.inventory.SlotDummy;
import codechicken.nei.api.INEIGuiAdapter;
public class NEIDummySlotHandler extends INEIGuiAdapter {
@Override
public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button)
{
public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) {
Slot slot = gui.getSlotAtPosition(mousex, mousey);
if(slot instanceof SlotDummy && slot.isItemValid(draggedStack) && gui.inventorySlots instanceof ContainerExtended)
{
((SlotDummy)slot).slotClick(draggedStack, button, NEIClientUtils.shiftKey());
if (slot instanceof SlotDummy && slot.isItemValid(draggedStack)
&& gui.inventorySlots instanceof ContainerExtended) {
((SlotDummy) slot).slotClick(draggedStack, button, NEIClientUtils.shiftKey());
NEICPH.sendDummySlotSet(slot.slotNumber, slot.getStack());
return true;
}
@@ -1,14 +1,19 @@
package codechicken.nei;
import java.io.File;
import java.util.*;
import net.minecraft.util.EnumChatFormatting;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import codechicken.core.CommonUtils;
import codechicken.core.launch.CodeChickenCorePlugin;
import codechicken.nei.api.IConfigureNEI;
import codechicken.nei.asm.NEICorePlugin;
import codechicken.nei.config.IMCHandler;
import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.RecipeCatalysts;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import cpw.mods.fml.client.FMLFileResourcePack;
import cpw.mods.fml.client.FMLFolderResourcePack;
import cpw.mods.fml.common.DummyModContainer;
@@ -22,13 +27,9 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.versioning.ArtifactVersion;
import cpw.mods.fml.common.versioning.VersionParser;
import cpw.mods.fml.common.versioning.VersionRange;
import net.minecraft.util.EnumChatFormatting;
import java.io.File;
import java.util.*;
public class NEIModContainer extends DummyModContainer {
public class NEIModContainer extends DummyModContainer
{
public static LinkedList<IConfigureNEI> plugins = new LinkedList<>();
private static boolean gregTech5Loaded;
@@ -40,10 +41,10 @@ public class NEIModContainer extends DummyModContainer
private static ModMetadata getModMetadata() {
final ModMetadata modMetadata = new ModMetadata();
modMetadata.name = "GRADLETOKEN_MODNAME";
modMetadata.modId = "GRADLETOKEN_MODID";
modMetadata.version = "GRADLETOKEN_VERSION";
modMetadata.authorList = Arrays.asList( "ChickenBones", "mitchej123" );
modMetadata.name = "NotEnoughItems";
modMetadata.modId = "NotEnoughItems";
modMetadata.version = Tags.VERSION;
modMetadata.authorList = Arrays.asList("ChickenBones", "mitchej123");
modMetadata.url = "https://github.com/GTNewHorizons/NotEnoughItems";
modMetadata.description = "Recipe Viewer, Inventory Manager, Item Spawner, Cheats and more; GTNH Version includes many enhancements.";
return modMetadata;
@@ -56,7 +57,7 @@ public class NEIModContainer extends DummyModContainer
@Override
public Set<ArtifactVersion> getRequirements() {
Set<ArtifactVersion> deps = new HashSet<>();
deps.add(VersionParser.parseVersionReference("CodeChickenCore@["+CodeChickenCorePlugin.version+",)"));
deps.add(VersionParser.parseVersionReference("CodeChickenCore@[" + CodeChickenCorePlugin.version + ",)"));
return deps;
}
@@ -66,8 +67,9 @@ public class NEIModContainer extends DummyModContainer
}
private String description;
private void loadMetadata() {
description = super.getMetadata().description.replace("Supporters:", EnumChatFormatting.AQUA+"Supporters:");
description = super.getMetadata().description.replace("Supporters:", EnumChatFormatting.AQUA + "Supporters:");
}
@Override
@@ -78,8 +80,7 @@ public class NEIModContainer extends DummyModContainer
} else {
s_plugins.append(EnumChatFormatting.GREEN).append("Installed plugins: ");
for (int i = 0; i < plugins.size(); i++) {
if (i > 0)
s_plugins.append(", ");
if (i > 0) s_plugins.append(", ");
IConfigureNEI plugin = plugins.get(i);
s_plugins.append(plugin.getName()).append(" ").append(plugin.getVersion());
}
@@ -100,22 +101,20 @@ public class NEIModContainer extends DummyModContainer
@Subscribe
public void preInit(FMLPreInitializationEvent event) {
gregTech5Loaded = Loader.isModLoaded("gregtech") && !Loader.isModLoaded("gregapi_post");
if (CommonUtils.isClient())
ClientHandler.preInit();
if (CommonUtils.isClient()) ClientHandler.preInit();
}
@Subscribe
public void init(FMLInitializationEvent event) {
if (CommonUtils.isClient())
ClientHandler.load();
if (CommonUtils.isClient()) ClientHandler.load();
ServerHandler.load();
}
@Subscribe
public void postInit(FMLPostInitializationEvent event) {
if (CommonUtils.isClient()) {
GuiRecipeTab.loadHandlerInfo();
RecipeCatalysts.loadCatalystInfo();
ClientHandler.postInit();
}
}
@@ -0,0 +1,53 @@
package codechicken.nei;
import java.util.Collection;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.potion.PotionEffect;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.api.INEIGuiAdapter;
/**
* Inspired by InventoryEffectRendererGuiHandler.java in JEI
*/
public class NEIPotionGuiHandler extends INEIGuiAdapter {
@Override
public boolean hideItemPanelSlot(GuiContainer guiContainer, int slotX, int slotY, int slotW, int slotH) {
if (NEIClientConfig.ignorePotionOverlap()) {
return false;
}
if (guiContainer instanceof InventoryEffectRenderer) {
int x = guiContainer.guiLeft - 124;
int y = guiContainer.guiTop;
Minecraft minecraft = guiContainer.mc;
if (minecraft == null) {
return false;
}
EntityPlayerSP player = minecraft.thePlayer;
if (player == null) {
return false;
}
Collection<PotionEffect> activePotionEffects = player.getActivePotionEffects();
if (activePotionEffects.isEmpty()) {
return false;
}
int height = 33;
if (activePotionEffects.size() > 5) {
height = 132 / (activePotionEffects.size() - 1);
}
Rectangle4i slotRect = new Rectangle4i(slotX, slotY, slotW, slotH);
for (PotionEffect potioneffect : activePotionEffects) {
Rectangle4i box = new Rectangle4i(x, y, 140, 32);
if (box.intersects(slotRect)) return true;
y += height;
}
}
return false;
}
}
+55 -51
View File
@@ -1,12 +1,8 @@
package codechicken.nei;
import codechicken.core.CommonUtils;
import codechicken.core.ServerUtils;
import codechicken.lib.inventory.SlotDummy;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IServerPacketHandler;
import codechicken.lib.vec.BlockCoord;
import cpw.mods.fml.relauncher.Side;
import java.util.LinkedList;
import java.util.Set;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.InventoryBasic;
@@ -17,15 +13,19 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.world.World;
import java.util.LinkedList;
import java.util.Set;
import codechicken.core.CommonUtils;
import codechicken.core.ServerUtils;
import codechicken.lib.inventory.SlotDummy;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IServerPacketHandler;
import codechicken.lib.vec.BlockCoord;
import cpw.mods.fml.relauncher.Side;
public class NEISPH implements IServerPacketHandler {
public class NEISPH implements IServerPacketHandler
{
@Override
public void handlePacket(PacketCustom packet, EntityPlayerMP sender, INetHandlerPlayServer netHandler) {
if (!NEIServerConfig.authenticatePacket(sender, packet))
return;
if (!NEIServerConfig.authenticatePacket(sender, packet)) return;
switch (packet.getType()) {
case 1:
@@ -67,6 +67,9 @@ public class NEISPH implements IServerPacketHandler
case 15:
handleMobSpawnerID(sender.worldObj, packet.readCoord(), packet.readString());
break;
case 16:
handleRequestContainer(sender, packet.readInt());
break;
case 21:
openEnchantmentGui(sender);
break;
@@ -90,8 +93,7 @@ public class NEISPH implements IServerPacketHandler
ItemStack stack = packet.readItemStack(true);
Slot slot = sender.openContainer.getSlot(slotNumber);
if (slot instanceof SlotDummy)
slot.putStack(stack);
if (slot instanceof SlotDummy) slot.putStack(stack);
}
private void handleMobSpawnerID(World world, BlockCoord coord, String mobtype) {
@@ -103,6 +105,11 @@ public class NEISPH implements IServerPacketHandler
}
}
private void handleRequestContainer(EntityPlayerMP sender, int containerSize) {
if (sender.openContainer.getInventory().size() != containerSize) return;
sender.sendContainerToPlayer(sender.openContainer);
}
private void handlePropertyChange(EntityPlayerMP sender, PacketCustom packet) {
String name = packet.readString();
if (NEIServerConfig.canPlayerPerformAction(sender.getCommandSenderName(), name))
@@ -111,12 +118,19 @@ public class NEISPH implements IServerPacketHandler
public static void processCreativeInv(EntityPlayerMP sender, boolean open) {
if (open) {
ServerUtils.openSMPContainer(sender, new ContainerCreativeInv(sender, new ExtendedCreativeInv(NEIServerConfig.forPlayer(sender.getCommandSenderName()), Side.SERVER)), (player, windowId) -> {
PacketCustom packet = new PacketCustom(channel, 23);
packet.writeBoolean(true);
packet.writeByte(windowId);
packet.sendToPlayer(player);
});
ServerUtils.openSMPContainer(
sender,
new ContainerCreativeInv(
sender,
new ExtendedCreativeInv(
NEIServerConfig.forPlayer(sender.getCommandSenderName()),
Side.SERVER)),
(player, windowId) -> {
PacketCustom packet = new PacketCustom(channel, 23);
packet.writeBoolean(true);
packet.writeByte(windowId);
packet.sendToPlayer(player);
});
} else {
sender.closeContainer();
PacketCustom packet = new PacketCustom(channel, 23);
@@ -135,7 +149,8 @@ public class NEISPH implements IServerPacketHandler
ItemStack item = packet.readItemStack();
ItemStack old = NEIServerUtils.getSlotContents(player, slot, container);
boolean deleting = item == null || old != null && NEIServerUtils.areStacksSameType(item, old) && item.stackSize < old.stackSize;
boolean deleting = item == null
|| old != null && NEIServerUtils.areStacksSameType(item, old) && item.stackSize < old.stackSize;
if (NEIServerConfig.canPlayerPerformAction(player.getCommandSenderName(), deleting ? "delete" : "item"))
NEIServerUtils.setSlotContents(player, slot, item, container);
}
@@ -150,17 +165,19 @@ public class NEISPH implements IServerPacketHandler
}
private void openEnchantmentGui(EntityPlayerMP player) {
ServerUtils.openSMPContainer(player, new ContainerEnchantmentModifier(player.inventory, player.worldObj, 0, 0, 0), (player1, windowId) -> {
PacketCustom packet = new PacketCustom(channel, 21);
packet.writeByte(windowId);
packet.sendToPlayer(player1);
});
ServerUtils.openSMPContainer(
player,
new ContainerEnchantmentModifier(player.inventory, player.worldObj, 0, 0, 0),
(player1, windowId) -> {
PacketCustom packet = new PacketCustom(channel, 21);
packet.writeByte(windowId);
packet.sendToPlayer(player1);
});
}
private void openPotionGui(EntityPlayerMP player, PacketCustom packet) {
InventoryBasic b = new InventoryBasic("potionStore", true, 9);
for (int i = 0; i < b.getSizeInventory(); i++)
b.setInventorySlotContents(i, packet.readItemStack());
for (int i = 0; i < b.getSizeInventory(); i++) b.setInventorySlotContents(i, packet.readItemStack());
ServerUtils.openSMPContainer(player, new ContainerPotionCreator(player.inventory, b), (player1, windowId) -> {
PacketCustom packet1 = new PacketCustom(channel, 24);
packet1.writeByte(windowId);
@@ -169,17 +186,11 @@ public class NEISPH implements IServerPacketHandler
}
public static void sendActionDisabled(int dim, String name, boolean disable) {
new PacketCustom(channel, 11)
.writeString(name)
.writeBoolean(disable)
.sendToDimension(dim);
new PacketCustom(channel, 11).writeString(name).writeBoolean(disable).sendToDimension(dim);
}
public static void sendActionEnabled(EntityPlayerMP player, String name, boolean enable) {
new PacketCustom(channel, 12)
.writeString(name)
.writeBoolean(enable)
.sendToPlayer(player);
new PacketCustom(channel, 12).writeString(name).writeBoolean(enable).sendToPlayer(player);
}
private void sendLoginState(EntityPlayerMP player) {
@@ -190,12 +201,9 @@ public class NEISPH implements IServerPacketHandler
PlayerSave playerSave = NEIServerConfig.forPlayer(player.getCommandSenderName());
for (String name : NEIActions.nameActionMap.keySet()) {
if (NEIServerConfig.canPlayerPerformAction(player.getCommandSenderName(), name))
actions.add(name);
if (NEIServerConfig.isActionDisabled(player.dimension, name))
disabled.add(name);
if (playerSave.isActionEnabled(name))
enabled.add(name);
if (NEIServerConfig.canPlayerPerformAction(player.getCommandSenderName(), name)) actions.add(name);
if (NEIServerConfig.isActionDisabled(player.dimension, name)) disabled.add(name);
if (playerSave.isActionEnabled(name)) enabled.add(name);
}
for (ItemStackMap.Entry<Set<String>> entry : NEIServerConfig.bannedItems.entries())
if (!NEIServerConfig.isPlayerInList(player.getCommandSenderName(), entry.value, true))
@@ -204,20 +212,16 @@ public class NEISPH implements IServerPacketHandler
PacketCustom packet = new PacketCustom(channel, 10);
packet.writeByte(actions.size());
for (String s : actions)
packet.writeString(s);
for (String s : actions) packet.writeString(s);
packet.writeByte(disabled.size());
for (String s : disabled)
packet.writeString(s);
for (String s : disabled) packet.writeString(s);
packet.writeByte(enabled.size());
for (String s : enabled)
packet.writeString(s);
for (String s : enabled) packet.writeString(s);
packet.writeInt(bannedItems.size());
for (ItemStack stack : bannedItems)
packet.writeItemStack(stack);
for (ItemStack stack : bannedItems) packet.writeItemStack(stack);
packet.sendToPlayer(player);
}
@@ -1,23 +1,5 @@
package codechicken.nei;
import codechicken.core.CommonUtils;
import codechicken.core.ServerUtils;
import codechicken.lib.config.ConfigFile;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
@@ -30,8 +12,29 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class NEIServerConfig
{
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import codechicken.core.CommonUtils;
import codechicken.core.ServerUtils;
import codechicken.lib.config.ConfigFile;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
public class NEIServerConfig {
private static MinecraftServer server;
public static Logger logger = LogManager.getLogger("NotEnoughItems");
@@ -62,7 +65,7 @@ public class NEIServerConfig
try {
File file = new File(getSaveDir(world), "world.dat");
NBTTagCompound tag = NEIServerUtils.readNBT(file);
if(tag == null) tag = new NBTTagCompound();
if (tag == null) tag = new NBTTagCompound();
dimTags.put(CommonUtils.getDimension(world), tag);
} catch (Exception e) {
throw new RuntimeException(e);
@@ -75,7 +78,8 @@ public class NEIServerConfig
serverConfig.setNewLineMode(1);
serverConfig.getTag("permissions").useBraces();
serverConfig.getTag("permissions").setComment("List of players who can use these features.\nEg. time=CodeChicken, Friend1");
serverConfig.getTag("permissions")
.setComment("List of players who can use these features.\nEg. time=CodeChicken, Friend1");
setDefaultFeature("time");
setDefaultFeature("rain");
@@ -93,13 +97,11 @@ public class NEIServerConfig
}
private static void setDefaultFeature(String featurename, String... names) {
if (names.length == 0)
names = new String[]{"OP"};
if (names.length == 0) names = new String[] { "OP" };
StringBuilder list = new StringBuilder();
for (int i = 0; i < names.length; i++) {
if (i >= 1)
list.append(", ");
if (i >= 1) list.append(", ");
list.append(names[i]);
}
serverConfig.getTag("permissions." + featurename).setDefaultValue(list.toString());
@@ -107,7 +109,11 @@ public class NEIServerConfig
private static void saveWorld(int dim) {
try {
File file = new File(getSaveDir(DimensionManager.getWorld(dim)), "world.dat");
final File saveDir = getSaveDir(DimensionManager.getWorld(dim));
if (!saveDir.isDirectory()) {
FileUtils.forceMkdir(saveDir);
}
File file = new File(saveDir, "world.dat");
NEIServerUtils.writeNBT(dimTags.get(dim), file);
} catch (Exception e) {
throw new RuntimeException(e);
@@ -119,14 +125,12 @@ public class NEIServerConfig
}
public static boolean isPlayerInList(String playername, Set<String> list, boolean allowCards) {
if (playername.equals("CONSOLE"))
return list.contains(playername);
if (playername.equals("CONSOLE")) return list.contains(playername);
playername = playername.toLowerCase();
if (allowCards) {
if (list.contains("ALL"))
return true;
if (list.contains("ALL")) return true;
if ((ServerUtils.isPlayerOP(playername) || ServerUtils.isPlayerOwner(playername)) && list.contains("OP"))
return true;
}
@@ -173,8 +177,7 @@ public class NEIServerConfig
StringBuilder sb = new StringBuilder();
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
if (i != 0)
sb.append(", ");
if (i != 0) sb.append(", ");
sb.append(iterator.next());
}
@@ -185,7 +188,7 @@ public class NEIServerConfig
private static void loadBannedItems() {
bannedItems.clear();
File file = new File(saveDir, "banneditems.cfg");
if(!file.exists()) {
if (!file.exists()) {
bannedItems.put(new ItemStack(Blocks.command_block), new HashSet<>(Collections.singletonList("NONE")));
saveBannedItems();
return;
@@ -193,22 +196,20 @@ public class NEIServerConfig
try {
FileReader r = new FileReader(file);
int line = 0;
for(String s : IOUtils.readLines(r)) {
if(s.charAt(0) == '#' || s.trim().length() == 0)
continue;
for (String s : IOUtils.readLines(r)) {
if (s.charAt(0) == '#' || s.trim().length() == 0) continue;
int delim = s.lastIndexOf('=');
if(delim < 0) {
logger.error("line "+line+": Missing =");
if (delim < 0) {
logger.error("line " + line + ": Missing =");
continue;
}
try {
NBTTagCompound key = (NBTTagCompound) JsonToNBT.func_150315_a(s.substring(0, delim));
Set<String> values = new HashSet<>();
for(String s2 : s.substring(delim+1).split(","))
values.add(s2.trim());
for (String s2 : s.substring(delim + 1).split(",")) values.add(s2.trim());
bannedItems.put(InventoryUtils.loadPersistant(key), values);
} catch (Exception e) {
logger.error("line "+line+": "+e.getMessage());
logger.error("line " + line + ": " + e.getMessage());
}
}
r.close();
@@ -220,22 +221,22 @@ public class NEIServerConfig
public static void saveBannedItems() {
File file = new File(saveDir, "banneditems.cfg");
try {
if(!file.exists())
file.createNewFile();
if (!file.exists()) file.createNewFile();
PrintWriter p = new PrintWriter(file);
p.println("#Saved in this format for external editing. The format isn't that hard to figure out. If you think you're up to it, modify it here!");
p.println(
"#Saved in this format for external editing. The format isn't that hard to figure out. If you think you're up to it, modify it here!");
for (ItemStackMap.Entry<Set<String>> entry : bannedItems.entries()) {
NBTTagCompound key = InventoryUtils.savePersistant(entry.key, new NBTTagCompound());
key.removeTag("Count");
if(key.getByte("Damage") == 0) key.removeTag("Damage");
if (key.getByte("Damage") == 0) key.removeTag("Damage");
p.print(key.toString());
p.print("=[");
int i = 0;
for (String s : entry.value) {
if(i++ != 0) p.print(", ");
if (i++ != 0) p.print(", ");
p.print(s);
}
p.println("]");
@@ -252,14 +253,15 @@ public class NEIServerConfig
public static void loadPlayer(EntityPlayer player) {
logger.debug("Loading Player: " + player.getGameProfile().getName());
playerSaves.put(player.getCommandSenderName(), new PlayerSave(player.getCommandSenderName(), new File(saveDir, "players")));
playerSaves.put(
player.getCommandSenderName(),
new PlayerSave(player.getCommandSenderName(), new File(saveDir, "players")));
}
public static void unloadPlayer(EntityPlayer player) {
logger.debug("Unloading Player: " + player.getCommandSenderName());
PlayerSave playerSave = playerSaves.remove(player.getCommandSenderName());
if (playerSave != null)
playerSave.save();
if (playerSave != null) playerSave.save();
}
public static boolean authenticatePacket(EntityPlayerMP sender, PacketCustom packet) {
+125 -141
View File
@@ -1,13 +1,17 @@
package codechicken.nei;
import codechicken.core.CommonUtils;
import codechicken.core.ServerUtils;
import codechicken.lib.inventory.InventoryRange;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.util.NBTHelper;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.registry.GameRegistry;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipException;
import net.minecraft.command.ICommandSender;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.player.EntityPlayer;
@@ -30,32 +34,29 @@ import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings.GameType;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.logging.log4j.Level;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipException;
import codechicken.core.CommonUtils;
import codechicken.core.ServerUtils;
import codechicken.lib.inventory.InventoryRange;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.util.NBTHelper;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.registry.GameRegistry;
public class NEIServerUtils {
public class NEIServerUtils
{
public static boolean isRaining(World world) {
return world.getWorldInfo().isRaining();
}
public static void toggleRaining(World world, boolean notify) {
boolean raining = !world.isRaining();
if (!raining)//turn off
if (!raining) // turn off
((WorldServer) world).provider.resetRainAndThunder();
else
world.getWorldInfo().setRaining(!isRaining(world));
else world.getWorldInfo().setRaining(!isRaining(world));
if (notify)
ServerUtils.sendChatToAll(new ChatComponentTranslation("nei.chat.rain." + (raining ? "on" : "off")));
@@ -76,27 +77,20 @@ public class NEIServerUtils
}
public static void setSlotContents(EntityPlayer player, int slot, ItemStack item, boolean containerInv) {
if (slot == -999)
player.inventory.setItemStack(item);
else if (containerInv)
player.openContainer.putStackInSlot(slot, item);
else
player.inventory.setInventorySlotContents(slot, item);
if (slot == -999) player.inventory.setItemStack(item);
else if (containerInv) player.openContainer.putStackInSlot(slot, item);
else player.inventory.setInventorySlotContents(slot, item);
}
public static ItemStack getSlotContents(EntityPlayer player, int slot, boolean containerInv) {
if (slot == -999)
return player.inventory.getItemStack();
else if (containerInv)
return player.openContainer.getSlot(slot).getStack();
else
return player.inventory.getStackInSlot(slot);
if (slot == -999) return player.inventory.getItemStack();
else if (containerInv) return player.openContainer.getSlot(slot).getStack();
else return player.inventory.getStackInSlot(slot);
}
@SuppressWarnings("unchecked")
public static void deleteAllItems(EntityPlayerMP player) {
for (Slot slot : (List<Slot>) player.openContainer.inventorySlots)
slot.putStack(null);
for (Slot slot : (List<Slot>) player.openContainer.inventorySlots) slot.putStack(null);
player.sendContainerAndContentsToPlayer(player.openContainer, player.openContainer.getInventory());
}
@@ -116,8 +110,7 @@ public class NEIServerUtils
while (NEIServerConfig.isActionDisabled(dim, NEIActions.timeZones[newhour / 6]))
newhour = ((newhour / 6 + 1) % 4) * 6;
if (newhour != hour)
setHourForward(world, newhour, false);
if (newhour != hour) setHourForward(world, newhour, false);
}
public static boolean canItemFitInInventory(EntityPlayer player, ItemStack itemstack) {
@@ -125,17 +118,18 @@ public class NEIServerUtils
}
public static void sendNotice(ICommandSender sender, IChatComponent msg, String permission) {
ChatComponentTranslation notice = new ChatComponentTranslation("chat.type.admin", sender.getCommandSenderName(), msg.createCopy());
ChatComponentTranslation notice = new ChatComponentTranslation(
"chat.type.admin",
sender.getCommandSenderName(),
msg.createCopy());
notice.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
if (NEIServerConfig.canPlayerPerformAction("CONSOLE", permission))
MinecraftServer.getServer().addChatMessage(notice);
for (EntityPlayer p : ServerUtils.getPlayers())
if(p == sender)
p.addChatComponentMessage(msg);
else if (NEIServerConfig.canPlayerPerformAction(p.getCommandSenderName(), permission))
p.addChatComponentMessage(notice);
for (EntityPlayer p : ServerUtils.getPlayers()) if (p == sender) p.addChatComponentMessage(msg);
else if (NEIServerConfig.canPlayerPerformAction(p.getCommandSenderName(), permission))
p.addChatComponentMessage(notice);
}
/**
@@ -144,54 +138,58 @@ public class NEIServerUtils
* @return whether the two items are the same in terms of damage and itemID.
*/
public static boolean areStacksSameType(ItemStack stack1, ItemStack stack2) {
return stack1 != null && stack2 != null &&
(stack1.getItem() == stack2.getItem() &&
(!stack2.getHasSubtypes() || stack2.getItemDamage() == stack1.getItemDamage()) &&
ItemStack.areItemStackTagsEqual(stack2, stack1));
return stack1 != null && stack2 != null
&& (stack1.getItem() == stack2.getItem()
&& (!stack2.getHasSubtypes() || stack2.getItemDamage() == stack1.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack2, stack1));
}
/**
* NBT-friendly version of {@link #areStacksSameType(ItemStack, ItemStack)}
*
* @param stack1 The {@link ItemStack} being compared.
* @param stack2 The {@link ItemStack} to compare to.
* @return whether the two items are the same in terms of itemID, damage and NBT.
*/
public static boolean areStacksSameTypeWithNBT(ItemStack stack1, ItemStack stack2) {
return stack1 != null && stack2 != null &&
stack1.getItem() == stack2.getItem() &&
(!stack2.getHasSubtypes() || stack2.getItemDamage() == stack1.getItemDamage()) &&
NBTHelper.matchTag(stack1.getTagCompound(), stack2.getTagCompound());
return stack1 != null && stack2 != null
&& stack1.getItem() == stack2.getItem()
&& (!stack2.getHasSubtypes() || stack2.getItemDamage() == stack1.getItemDamage())
&& NBTHelper.matchTag(stack1.getTagCompound(), stack2.getTagCompound());
}
/**
* {@link ItemStack}s with damage -1 are wildcards allowing all damages. Eg all colours of wool are allowed to create Beds.
* {@link ItemStack}s with damage -1 are wildcards allowing all damages. Eg all colours of wool are allowed to
* create Beds.
*
* @param stack1 The {@link ItemStack} being compared.
* @param stack2 The {@link ItemStack} to compare to.
* @return whether the two items are the same from the perspective of a crafting inventory.
*/
public static boolean areStacksSameTypeCrafting(ItemStack stack1, ItemStack stack2) {
return stack1 != null && stack2 != null &&
stack1.getItem() == stack2.getItem() &&
(stack1.getItemDamage() == stack2.getItemDamage() || stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack2.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack1.getItem().isDamageable());
return stack1 != null && stack2 != null
&& stack1.getItem() == stack2.getItem()
&& (stack1.getItemDamage() == stack2.getItemDamage()
|| stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE
|| stack2.getItemDamage() == OreDictionary.WILDCARD_VALUE
|| stack1.getItem().isDamageable());
}
/**
* NBT-friendly version of {@link #areStacksSameTypeCrafting(ItemStack, ItemStack)}
*
* @param stack1 The {@link ItemStack} being compared.
* @param stack2 The {@link ItemStack} to compare to.
* @return whether the two items are the same from the perspective of a crafting inventory.
*/
public static boolean areStacksSameTypeCraftingWithNBT(ItemStack stack1, ItemStack stack2) {
return stack1 != null && stack2 != null &&
stack1.getItem() == stack2.getItem() &&
(
stack1.getItemDamage() == stack2.getItemDamage() ||
stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE ||
stack2.getItemDamage() == OreDictionary.WILDCARD_VALUE ||
stack1.getItem().isDamageable()
) &&
NBTHelper.matchTag(stack1.getTagCompound(), stack2.getTagCompound());
return stack1 != null && stack2 != null
&& stack1.getItem() == stack2.getItem()
&& (stack1.getItemDamage() == stack2.getItemDamage()
|| stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE
|| stack2.getItemDamage() == OreDictionary.WILDCARD_VALUE
|| stack1.getItem().isDamageable())
&& NBTHelper.matchTag(stack1.getTagCompound(), stack2.getTagCompound());
}
/**
@@ -202,9 +200,10 @@ public class NEIServerUtils
* @return The ordering of stack1 relative to stack2.
*/
public static int compareStacks(ItemStack stack1, ItemStack stack2) {
if (stack1 == stack2) return 0;//catches both null
if (stack1 == null || stack2 == null) return stack1 == null ? -1 : 1;//null stack goes first
if (stack1.getItem() != stack2.getItem()) return Item.getIdFromItem(stack1.getItem()) - Item.getIdFromItem(stack2.getItem());
if (stack1 == stack2) return 0; // catches both null
if (stack1 == null || stack2 == null) return stack1 == null ? -1 : 1; // null stack goes first
if (stack1.getItem() != stack2.getItem())
return Item.getIdFromItem(stack1.getItem()) - Item.getIdFromItem(stack2.getItem());
if (stack1.stackSize != stack2.stackSize) return stack1.stackSize - stack2.stackSize;
return stack1.getItemDamage() - stack2.getItemDamage();
}
@@ -220,33 +219,37 @@ public class NEIServerUtils
public static void givePlayerItem(EntityPlayerMP player, ItemStack stack, boolean infinite, boolean doGive) {
if (stack.getItem() == null) {
player.addChatComponentMessage(setColour(new ChatComponentTranslation("nei.chat.give.noitem"), EnumChatFormatting.WHITE));
player.addChatComponentMessage(
setColour(new ChatComponentTranslation("nei.chat.give.noitem"), EnumChatFormatting.WHITE));
return;
}
int given = stack.stackSize;
if(doGive) {
if (infinite)
player.inventory.addItemStackToInventory(stack);
else
given -= InventoryUtils.insertItem(player.inventory, stack, false);
if (doGive) {
if (infinite) player.inventory.addItemStackToInventory(stack);
else given -= InventoryUtils.insertItem(player.inventory, stack, false);
}
sendNotice(player, new ChatComponentTranslation("commands.give.success", stack.func_151000_E(), infinite ? "\u221E" : Integer.toString(given), player.getCommandSenderName()), "notify-item");
sendNotice(
player,
new ChatComponentTranslation(
"commands.give.success",
stack.func_151000_E(),
infinite ? "\u221E" : Integer.toString(given),
player.getCommandSenderName()),
"notify-item");
player.openContainer.detectAndSendChanges();
}
public static ItemStack copyStack(ItemStack itemstack, int i) {
if (itemstack == null)
return null;
if (itemstack == null) return null;
itemstack.stackSize += i;
return itemstack.splitStack(i);
}
public static ItemStack copyStack(ItemStack itemstack) {
if (itemstack == null)
return null;
if (itemstack == null) return null;
return copyStack(itemstack, itemstack.stackSize);
}
@@ -257,14 +260,10 @@ public class NEIServerUtils
}
public static int getCreativeMode(EntityPlayerMP player) {
if (NEIServerConfig.forPlayer(player.getCommandSenderName()).isActionEnabled("creative+"))
return 2;
else if (player.theItemInWorldManager.isCreative())
return 1;
else if (player.theItemInWorldManager.getGameType().isAdventure())
return 3;
else
return 0;
if (NEIServerConfig.forPlayer(player.getCommandSenderName()).isActionEnabled("creative+")) return 2;
else if (player.theItemInWorldManager.isCreative()) return 1;
else if (player.theItemInWorldManager.getGameType().isAdventure()) return 3;
else return 0;
}
public static GameType getGameType(int mode) {
@@ -281,20 +280,21 @@ public class NEIServerUtils
}
public static void setGamemode(EntityPlayerMP player, int mode) {
if (mode < 0 || mode >= NEIActions.gameModes.length ||
NEIActions.nameActionMap.containsKey(NEIActions.gameModes[mode]) &&
!NEIServerConfig.canPlayerPerformAction(player.getCommandSenderName(), NEIActions.gameModes[mode]))
if (mode < 0 || mode >= NEIActions.gameModes.length
|| NEIActions.nameActionMap.containsKey(NEIActions.gameModes[mode]) && !NEIServerConfig
.canPlayerPerformAction(player.getCommandSenderName(), NEIActions.gameModes[mode]))
return;
//creative+
// creative+
NEIServerConfig.forPlayer(player.getCommandSenderName()).enableAction("creative+", mode == 2);
if(mode == 2 && !(player.openContainer instanceof ContainerCreativeInv))//open the container immediately for the client
if (mode == 2 && !(player.openContainer instanceof ContainerCreativeInv)) // open the container immediately for
// the client
NEISPH.processCreativeInv(player, true);
//change it on the server
// change it on the server
player.theItemInWorldManager.setGameType(getGameType(mode));
//tell the client to change it
// tell the client to change it
new PacketCustom(NEISPH.channel, 14).writeByte(mode).sendToPlayer(player);
player.addChatMessage(new ChatComponentTranslation("nei.chat.gamemode." + mode));
}
@@ -302,32 +302,29 @@ public class NEIServerUtils
public static void cycleCreativeInv(EntityPlayerMP player, int steps) {
InventoryPlayer inventory = player.inventory;
//top down [row][col]
// top down [row][col]
ItemStack[][] slots = new ItemStack[10][9];
PlayerSave playerSave = NEIServerConfig.forPlayer(player.getCommandSenderName());
//get
// get
System.arraycopy(inventory.mainInventory, 0, slots[9], 0, 9);
for (int row = 0; row < 3; row++)
System.arraycopy(inventory.mainInventory, (row + 1) * 9, slots[row + 6], 0, 9);
for (int row = 0; row < 6; row++)
System.arraycopy(playerSave.creativeInv, row * 9, slots[row], 0, 9);
for (int row = 0; row < 6; row++) System.arraycopy(playerSave.creativeInv, row * 9, slots[row], 0, 9);
ItemStack[][] newslots = new ItemStack[10][];
//put back
for (int row = 0; row < 10; row++)
newslots[(row + steps + 10) % 10] = slots[row];
// put back
for (int row = 0; row < 10; row++) newslots[(row + steps + 10) % 10] = slots[row];
System.arraycopy(newslots[9], 0, inventory.mainInventory, 0, 9);
for (int row = 0; row < 3; row++)
System.arraycopy(newslots[row + 6], 0, inventory.mainInventory, (row + 1) * 9, 9);
for (int row = 0; row < 6; row++)
System.arraycopy(newslots[row], 0, playerSave.creativeInv, row * 9, 9);
for (int row = 0; row < 6; row++) System.arraycopy(newslots[row], 0, playerSave.creativeInv, row * 9, 9);
playerSave.setDirty();
}
@@ -336,78 +333,66 @@ public class NEIServerUtils
ArrayList<int[]> arraylist = new ArrayList<>();
if (itemstack != null) {
NBTTagList nbttaglist = itemstack.getEnchantmentTagList();
if (nbttaglist != null)
for (int i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound tag = nbttaglist.getCompoundTagAt(i);
arraylist.add(new int[]{tag.getShort("id"), tag.getShort("lvl")});
}
if (nbttaglist != null) for (int i = 0; i < nbttaglist.tagCount(); i++) {
NBTTagCompound tag = nbttaglist.getCompoundTagAt(i);
arraylist.add(new int[] { tag.getShort("id"), tag.getShort("lvl") });
}
}
return arraylist;
}
public static boolean stackHasEnchantment(ItemStack itemstack, int e) {
List<int[]> allenchantments = getEnchantments(itemstack);
for (int[] ai : allenchantments)
if (ai[0] == e)
return true;
for (int[] ai : allenchantments) if (ai[0] == e) return true;
return false;
}
public static int getEnchantmentLevel(ItemStack itemstack, int e) {
List<int[]> allenchantments = getEnchantments(itemstack);
for (int[] ai : allenchantments)
if (ai[0] == e)
return ai[1];
for (int[] ai : allenchantments) if (ai[0] == e) return ai[1];
return -1;
}
public static boolean doesEnchantmentConflict(List<int[]> enchantments, Enchantment e) {
for (int[] ai : enchantments)
if (!e.canApplyTogether(Enchantment.enchantmentsList[ai[0]]))
return true;
for (int[] ai : enchantments) if (!e.canApplyTogether(Enchantment.enchantmentsList[ai[0]])) return true;
return false;
}
public static RuntimeException throwCME(String msg) {
if (CommonUtils.isClient())
return ClientHandler.throwCME(msg);
if (CommonUtils.isClient()) return ClientHandler.throwCME(msg);
throw new RuntimeException(msg);
}
@SuppressWarnings("unchecked")
public static ItemStack[] extractRecipeItems(Object obj) {
if (obj instanceof ItemStack)
return new ItemStack[]{(ItemStack) obj};
if (obj instanceof ItemStack[])
return (ItemStack[]) obj;
if (obj instanceof List)
return ((List<ItemStack>) obj).toArray(new ItemStack[0]);
if (obj instanceof ItemStack) return new ItemStack[] { (ItemStack) obj };
if (obj instanceof ItemStack[]) return (ItemStack[]) obj;
if (obj instanceof List) return ((List<ItemStack>) obj).toArray(new ItemStack[0]);
throw new ClassCastException(obj+" not an ItemStack, ItemStack[] or List<ItemStack?");
throw new ClassCastException(obj + " not an ItemStack, ItemStack[] or List<ItemStack?");
}
public static List<Integer> getRange(final int start, final int end) {
return new AbstractList<Integer>()
{
return new AbstractList<Integer>() {
@Override
public Integer get(int index) {
return start+index;
return start + index;
}
@Override
public int size() {
return end-start;
return end - start;
}
};
}
public static StringBuilder fixTrailingCommaList(StringBuilder sb) {
if(sb.charAt(sb.length()-1) == ',')
sb.deleteCharAt(sb.length()-1);
if (sb.charAt(sb.length() - 1) == ',') sb.deleteCharAt(sb.length() - 1);
return sb;
}
@@ -461,7 +446,8 @@ public class NEIServerUtils
}
itemStack.setTagCompound((NBTTagCompound) nbttag);
} catch (NBTException e) {
FMLLog.getLogger().log(Level.WARN, "Encountered an exception parsing ItemStack NBT string {}", nbtString, e);
FMLLog.getLogger()
.log(Level.WARN, "Encountered an exception parsing ItemStack NBT string {}", nbtString, e);
return null;
}
}
@@ -470,16 +456,14 @@ public class NEIServerUtils
}
public static NBTTagCompound readNBT(File file) throws IOException {
if(!file.exists()) return null;
if (!file.exists()) return null;
FileInputStream in = new FileInputStream(file);
NBTTagCompound tag;
try {
tag = CompressedStreamTools.readCompressed(in);
} catch(ZipException e) {
if(e.getMessage().equals("Not in GZIP format"))
tag = CompressedStreamTools.read(file);
else
throw e;
} catch (ZipException e) {
if (e.getMessage().equals("Not in GZIP format")) tag = CompressedStreamTools.read(file);
else throw e;
}
in.close();
return tag;
@@ -1,28 +1,25 @@
package codechicken.nei;
import codechicken.nei.api.IStackPositioner;
import java.util.ArrayList;
public class OffsetPositioner implements IStackPositioner
{
public OffsetPositioner(int x, int y)
{
import codechicken.nei.api.IStackPositioner;
public class OffsetPositioner implements IStackPositioner {
public OffsetPositioner(int x, int y) {
offsetx = x;
offsety = y;
}
@Override
public ArrayList<PositionedStack> positionStacks(ArrayList<PositionedStack> ai)
{
for(PositionedStack stack : ai)
{
stack.relx+=offsetx;
stack.rely+=offsety;
public ArrayList<PositionedStack> positionStacks(ArrayList<PositionedStack> ai) {
for (PositionedStack stack : ai) {
stack.relx += offsetx;
stack.rely += offsety;
}
return ai;
}
public int offsetx;
public int offsety;
}
@@ -0,0 +1,397 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemPanel.ItemPanelSlot;
import codechicken.nei.api.GuiInfo;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.GuiUsageRecipe;
public abstract class PanelWidget extends Widget {
protected static final int PADDING = 2;
public ItemStack draggedStack;
public int mouseDownSlot = -1;
public Button pagePrev;
public Button pageNext;
public Label pageLabel;
protected ItemsGrid grid;
public ArrayList<ItemStack> getItems() {
return grid.getItems();
}
public ItemsGrid getGrid() {
return grid;
}
public void init() {
pageLabel = new Label("0/0", true);
pagePrev = new Button("Prev") {
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
grid.shiftPage(-1);
return true;
}
return false;
}
@Override
public String getRenderLabel() {
return "<";
}
};
pageNext = new Button("Next") {
public boolean onButtonPress(boolean rightclick) {
if (!rightclick) {
grid.shiftPage(1);
return true;
}
return false;
}
@Override
public String getRenderLabel() {
return ">";
}
};
}
public abstract String getLabelText();
protected abstract String getPositioningSettingName();
public abstract int getMarginLeft(GuiContainer gui);
public abstract int getMarginTop(GuiContainer gui);
public abstract int getWidth(GuiContainer gui);
public abstract int getHeight(GuiContainer gui);
public void resize(GuiContainer gui) {
final Rectangle4i margin = new Rectangle4i(
getMarginLeft(gui),
getMarginTop(gui),
getWidth(gui),
getHeight(gui));
final int minWidth = 5 * ItemsGrid.SLOT_SIZE;
final int minHeight = 9 * ItemsGrid.SLOT_SIZE;
final String settingName = getPositioningSettingName();
int paddingLeft = (int) Math
.ceil(margin.w * NEIClientConfig.getSetting(settingName + ".left").getIntValue() / 100000.0);
int paddingTop = (int) Math
.ceil(margin.h * NEIClientConfig.getSetting(settingName + ".top").getIntValue() / 100000.0);
int paddingRight = (int) Math
.ceil(margin.w * NEIClientConfig.getSetting(settingName + ".right").getIntValue() / 100000.0);
int paddingBottom = (int) Math
.ceil(margin.h * NEIClientConfig.getSetting(settingName + ".bottom").getIntValue() / 100000.0);
int deltaHeight = Math.min(0, margin.h - paddingTop - paddingBottom - minHeight) / 2;
paddingLeft = Math.min(paddingLeft, Math.max(0, margin.w - paddingRight - minWidth));
paddingRight = Math.min(paddingRight, Math.max(0, margin.w - paddingLeft - minWidth));
paddingTop = Math.min(margin.h - minHeight, Math.max(0, paddingTop + deltaHeight));
paddingBottom = Math.min(margin.h - paddingTop - minHeight, Math.max(0, paddingBottom - deltaHeight));
x = margin.x + paddingLeft;
y = margin.y + paddingTop;
w = margin.w - paddingLeft - paddingRight;
h = margin.h - paddingTop - paddingBottom;
final int header = resizeHeader(gui);
final int footer = resizeFooter(gui);
grid.setGridSize(x, y + header, w, h - header - footer);
grid.refresh(gui);
}
protected int resizeHeader(GuiContainer gui) {
final int BUTTON_SIZE = 16;
int paddingLeft = 0;
int paddingRight = 0;
while (paddingLeft < w && GuiInfo.hideItemPanelSlot(
gui,
new Rectangle4i(x + paddingLeft, y, ItemsGrid.SLOT_SIZE, ItemsGrid.SLOT_SIZE))) {
paddingLeft += ItemsGrid.SLOT_SIZE;
}
while (paddingRight < w && GuiInfo.hideItemPanelSlot(
gui,
new Rectangle4i(
x + w - paddingRight - ItemsGrid.SLOT_SIZE,
y,
ItemsGrid.SLOT_SIZE,
ItemsGrid.SLOT_SIZE))) {
paddingRight += ItemsGrid.SLOT_SIZE;
}
if (paddingLeft + paddingRight >= w) {
return 0;
}
pagePrev.w = pageNext.w = BUTTON_SIZE;
pagePrev.h = pageNext.h = BUTTON_SIZE;
pagePrev.y = pageNext.y = y;
pagePrev.x = x + paddingLeft;
pageNext.x = x + w - pageNext.w - paddingRight;
pageLabel.x = x + paddingLeft + (w - paddingLeft - paddingRight) / 2;
pageLabel.y = y + 5;
pageLabel.text = getLabelText();
return BUTTON_SIZE + 2;
}
protected abstract int resizeFooter(GuiContainer gui);
public void setVisible() {
if (grid.getPerPage() > 0) {
LayoutManager.addWidget(pagePrev);
LayoutManager.addWidget(pageNext);
LayoutManager.addWidget(pageLabel);
grid.setVisible();
}
}
@Override
public void update() {
grid.update();
}
@Override
public void draw(int mousex, int mousey) {
grid.draw(mousex, mousey);
}
@Override
public void postDraw(int mousex, int mousey) {
if (draggedStack != null) {
GuiContainerManager.drawItems.zLevel += 100;
GuiContainerManager.drawItem(mousex - 8, mousey - 8, draggedStack);
GuiContainerManager.drawItems.zLevel -= 100;
}
}
@Override
public void postDrawTooltips(int mx, int my, List<String> tooltip) {
grid.postDrawTooltips(mx, my, tooltip);
}
@Override
public void mouseDragged(int mousex, int mousey, int button, long heldTime) {
if (mouseDownSlot >= 0 && draggedStack == null
&& NEIClientUtils.getHeldItem() == null
&& NEIClientConfig.hasSMPCounterPart()) {
ItemPanelSlot mouseOverSlot = getSlotMouseOver(mousex, mousey);
if (mouseOverSlot == null || mouseOverSlot.slotIndex != mouseDownSlot || heldTime > 500) {
draggedStack = getDraggedStackWithQuantity(mouseDownSlot);
mouseDownSlot = -1;
}
}
}
protected abstract ItemStack getDraggedStackWithQuantity(int mouseDownSlot);
@Override
public boolean handleClick(int mousex, int mousey, int button) {
if (handleClickExt(mousex, mousey, button)) return true;
if (NEIClientUtils.getHeldItem() != null) {
if (!grid.contains(mousex, mousey)) {
return false;
}
if (NEIClientConfig.canPerformAction("delete") && NEIClientConfig.canPerformAction("item")) {
if (button == 1) {
NEIClientUtils.decreaseSlotStack(-999);
} else {
NEIClientUtils.deleteHeldItem();
}
} else {
NEIClientUtils.dropHeldItem();
}
return true;
}
ItemPanelSlot hoverSlot = getSlotMouseOver(mousex, mousey);
if (hoverSlot != null) {
if (button == 2) {
if (hoverSlot.item != null) {
draggedStack = getDraggedStackWithQuantity(hoverSlot.slotIndex);
}
} else {
mouseDownSlot = hoverSlot.slotIndex;
}
return true;
}
return false;
}
@Override
public boolean handleClickExt(int mouseX, int mouseY, int button) {
if (ItemPanels.itemPanel.draggedStack != null && ItemPanels.bookmarkPanel.contains(mouseX, mouseY)) {
ItemPanels.bookmarkPanel.addOrRemoveItem(ItemPanels.itemPanel.draggedStack, null, null, false, true);
ItemPanels.itemPanel.draggedStack = null;
return true;
}
if (ItemPanels.itemPanel.draggedStack != null) {
return ItemPanels.itemPanel.handleDraggedClick(mouseX, mouseY, button);
}
if (ItemPanels.bookmarkPanel.draggedStack != null) {
return ItemPanels.bookmarkPanel.handleDraggedClick(mouseX, mouseY, button);
}
if (NEIClientUtils.getHeldItem() != null) {
final ItemStack draggedStack = NEIClientUtils.getHeldItem().copy();
return handleGUIContainerClick(draggedStack, mouseX, mouseY, button);
}
return false;
}
protected boolean handleDraggedClick(int mouseX, int mouseY, int button) {
if (draggedStack == null) {
return false;
}
if (handleGUIContainerClick(draggedStack, mouseX, mouseY, button)) {
if (draggedStack.stackSize == 0) {
draggedStack = null;
}
return true;
}
final GuiContainer gui = NEIClientUtils.getGuiContainer();
if (mouseX < gui.guiLeft || mouseY < gui.guiTop
|| mouseX >= gui.guiLeft + gui.xSize
|| mouseY >= gui.guiTop + gui.ySize) {
draggedStack = null;
}
return true;
}
protected boolean handleGUIContainerClick(final ItemStack draggedStack, int mouseX, int mouseY, int button) {
final GuiContainer gui = NEIClientUtils.getGuiContainer();
boolean handled = false;
try {
GuiInfo.readLock.lock();
for (INEIGuiHandler handler : GuiInfo.guiHandlers) {
if (handler.handleDragNDrop(gui, mouseX, mouseY, draggedStack, button)) {
handled = true;
break;
}
}
} finally {
GuiInfo.readLock.unlock();
}
return handled;
}
@Override
public void mouseUp(int mousex, int mousey, int button) {
ItemPanelSlot hoverSlot = getSlotMouseOver(mousex, mousey);
if (hoverSlot != null && hoverSlot.slotIndex == mouseDownSlot && draggedStack == null) {
ItemStack item = hoverSlot.item;
if (NEIController.manager.window instanceof GuiRecipe || !NEIClientConfig.canCheatItem(item)) {
if (button == 0) {
GuiCraftingRecipe.openRecipeGui("item", item);
} else if (button == 1) {
GuiUsageRecipe.openRecipeGui("item", item);
}
mouseDownSlot = -1;
return;
}
NEIClientUtils.cheatItem(getDraggedStackWithQuantity(hoverSlot.slotIndex), button, -1);
}
mouseDownSlot = -1;
}
@Override
public boolean onMouseWheel(int i, int mousex, int mousey) {
if (!contains(mousex, mousey)) return false;
grid.shiftPage(-i);
return true;
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
if (NEIClientConfig.isKeyHashDown("gui.next")) {
grid.shiftPage(1);
return true;
}
if (NEIClientConfig.isKeyHashDown("gui.prev")) {
grid.shiftPage(-1);
return true;
}
return false;
}
@Override
public ItemStack getStackMouseOver(int mousex, int mousey) {
ItemPanelSlot slot = getSlotMouseOver(mousex, mousey);
return slot == null ? null : slot.item;
}
public ItemPanelSlot getSlotMouseOver(int mousex, int mousey) {
return grid.getSlotMouseOver(mousex, mousey);
}
public int getPage() {
return grid.getPage();
}
public int getNumPages() {
return grid.getNumPages();
}
@Override
public boolean contains(int px, int py) {
return grid.contains(px, py);
}
}
+15 -21
View File
@@ -1,16 +1,17 @@
package codechicken.nei;
import codechicken.core.ServerUtils;
import codechicken.lib.inventory.InventoryUtils;
import java.io.File;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.io.File;
import codechicken.core.ServerUtils;
import codechicken.lib.inventory.InventoryUtils;
public class PlayerSave {
public class PlayerSave
{
public String username;
private File saveFile;
@@ -27,20 +28,17 @@ public class PlayerSave
wasOp = ServerUtils.isPlayerOP(playername);
saveFile = new File(saveLocation, username + ".dat");
if (!saveFile.getParentFile().exists())
saveFile.getParentFile().mkdirs();
if (!saveFile.getParentFile().exists()) saveFile.getParentFile().mkdirs();
load();
}
private void load() {
nbt = new NBTTagCompound();
try {
if (!saveFile.exists())
saveFile.createNewFile();
if (saveFile.length() > 0)
nbt = NEIServerUtils.readNBT(saveFile);
if (!saveFile.exists()) saveFile.createNewFile();
if (saveFile.length() > 0) nbt = NEIServerUtils.readNBT(saveFile);
} catch (Exception e) {
NEIClientConfig.logger.error("Error loading player save: "+username, e);
NEIClientConfig.logger.error("Error loading player save: " + username, e);
}
loadCreativeInv();
@@ -49,22 +47,19 @@ public class PlayerSave
private void loadCreativeInv() {
creativeInv = new ItemStack[54];
NBTTagList itemList = nbt.getTagList("creativeitems", 10);
if (itemList != null)
InventoryUtils.readItemStacksFromTag(creativeInv, itemList);
if (itemList != null) InventoryUtils.readItemStacksFromTag(creativeInv, itemList);
}
public void save() {
if (!isDirty)
return;
if (!isDirty) return;
if (creativeInvDirty)
saveCreativeInv();
if (creativeInvDirty) saveCreativeInv();
try {
NEIServerUtils.writeNBT(nbt, saveFile);
isDirty = false;
} catch (Exception e) {
NEIClientConfig.logger.error("Error saving player: "+username, e);
NEIClientConfig.logger.error("Error saving player: " + username, e);
}
}
@@ -97,8 +92,7 @@ public class PlayerSave
private NBTTagCompound getEnabledActions() {
NBTTagCompound tag = nbt.getCompoundTag("enabledActions");
if (!nbt.hasKey("enabledActions"))
nbt.setTag("enabledActions", tag);
if (!nbt.hasKey("enabledActions")) nbt.setTag("enabledActions", tag);
return tag;
}
@@ -1,69 +1,56 @@
package codechicken.nei;
import codechicken.nei.guihook.IContainerInputHandler;
import static codechicken.nei.NEIClientConfig.canPerformAction;
import net.minecraft.client.gui.inventory.GuiContainer;
import static codechicken.nei.NEIClientConfig.canPerformAction;
import static codechicken.nei.NEIClientConfig.getKeyBinding;
import codechicken.nei.guihook.IContainerInputHandler;
public class PopupInputHandler implements IContainerInputHandler {
public class PopupInputHandler implements IContainerInputHandler
{
@Override
public boolean keyTyped(GuiContainer gui, char keyChar, int keyCode)
{
public boolean keyTyped(GuiContainer gui, char keyChar, int keyCode) {
return false;
}
@Override
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button)
{
public boolean mouseClicked(GuiContainer gui, int mousex, int mousey, int button) {
return false;
}
@Override
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID)
{
}
public void onKeyTyped(GuiContainer gui, char keyChar, int keyID) {}
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID)
{
if(keyID == getKeyBinding("gui.enchant") && canPerformAction("enchant"))
{
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (NEIClientConfig.isKeyHashDown("gui.enchant") && canPerformAction("enchant")) {
NEICPH.sendOpenEnchantmentWindow();
return true;
}
if(keyID == getKeyBinding("gui.potion") && canPerformAction("potion"))
{
if (NEIClientConfig.isKeyHashDown("gui.potion") && canPerformAction("potion")) {
NEICPH.sendOpenPotionWindow();
return true;
}
return false;
}
@Override
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button)
{
}
public void onMouseClicked(GuiContainer gui, int mousex, int mousey, int button) {}
@Override
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button)
{
}
public void onMouseUp(GuiContainer gui, int mousex, int mousey, int button) {}
@Override
public boolean mouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled)
{
public boolean mouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {
return false;
}
@Override
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled)
{
}
public void onMouseScrolled(GuiContainer gui, int mousex, int mousey, int scrolled) {}
@Override
public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime)
{
}
public void onMouseDragged(GuiContainer gui, int mousex, int mousey, int button, long heldTime) {}
}
@@ -1,100 +1,91 @@
package codechicken.nei;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.ArrayList;
import java.util.List;
/**
* Simply an {@link ItemStack} with position.
* Mainly used in the recipe handlers.
* Simply an {@link ItemStack} with position. Mainly used in the recipe handlers.
*/
public class PositionedStack
{
public class PositionedStack {
public int relx;
public int rely;
public ItemStack[] items;
//compatibility dummy
// compatibility dummy
public ItemStack item;
private boolean permutated = false;
public PositionedStack(Object object, int x, int y, boolean genPerms) {
items = NEIServerUtils.extractRecipeItems(object);
relx = x;
rely = y;
if(genPerms)
generatePermutations();
else
setPermutationToRender(0);
if (genPerms) generatePermutations();
else setPermutationToRender(0);
}
public PositionedStack(Object object, int x, int y)
{
public PositionedStack(Object object, int x, int y) {
this(object, x, y, true);
}
public void generatePermutations() {
if(permutated)
return;
if (permutated) return;
ArrayList<ItemStack> stacks = new ArrayList<>();
for(ItemStack item : items) {
if(item == null || item.getItem() == null)
continue;
if(item.getItemDamage() == Short.MAX_VALUE) {
for (ItemStack item : items) {
if (item == null || item.getItem() == null) continue;
if (item.getItemDamage() == Short.MAX_VALUE) {
List<ItemStack> permutations = ItemList.itemMap.get(item.getItem());
if(!permutations.isEmpty()) {
for(ItemStack stack : permutations)
stacks.add(stack.copy());
}
else {
if (!permutations.isEmpty()) {
for (ItemStack stack : permutations) {
ItemStack toAdd = stack.copy();
toAdd.stackSize = item.stackSize;
stacks.add(toAdd);
}
} else {
ItemStack base = new ItemStack(item.getItem(), item.stackSize);
base.stackTagCompound = item.stackTagCompound;
stacks.add(base);
}
continue;
}
stacks.add(item.copy());
}
items = stacks.toArray(new ItemStack[0]);
if(items.length == 0)
items = new ItemStack[]{new ItemStack(Blocks.fire)};
if (items.length == 0) items = new ItemStack[] { new ItemStack(Blocks.fire) };
permutated = true;
setPermutationToRender(0);
}
public void setMaxSize(int i) {
for(ItemStack item : items)
if(item.stackSize > i)
item.stackSize = i;
for (ItemStack item : items) if (item.stackSize > i) item.stackSize = i;
}
public PositionedStack copy() {
return new PositionedStack(items, relx, rely);
}
public void setPermutationToRender(int index) {
item = items[index].copy();
if(item.getItem() == null)
item = new ItemStack(Blocks.fire);
else if(item.getItemDamage() == OreDictionary.WILDCARD_VALUE && item.getItem() != null && item.getItem().isRepairable())
if (item.getItem() == null) item = new ItemStack(Blocks.fire);
else if (item.getItemDamage() == OreDictionary.WILDCARD_VALUE && item.getItem() != null
&& item.getItem().isRepairable())
item.setItemDamage(0);
}
public boolean contains(ItemStack ingredient) {
for(ItemStack item : items)
if(NEIServerUtils.areStacksSameTypeCrafting(item, ingredient))
return true;
for (ItemStack item : items) if (NEIServerUtils.areStacksSameTypeCrafting(item, ingredient)) return true;
return false;
}
@@ -102,21 +93,17 @@ public class PositionedStack
* NBT-friendly version of {@link #contains(ItemStack)}
*/
public boolean containsWithNBT(ItemStack ingredient) {
for(ItemStack item : items)
if(NEIServerUtils.areStacksSameTypeCraftingWithNBT(item, ingredient))
return true;
for (ItemStack item : items) if (NEIServerUtils.areStacksSameTypeCraftingWithNBT(item, ingredient)) return true;
return false;
}
public boolean contains(Item ingred) {
for(ItemStack item : items)
if(item.getItem() == ingred)
return true;
for (ItemStack item : items) if (item.getItem() == ingred) return true;
return false;
}
@Override
public String toString() {
return "PositionedStack(output='" + item.toString() + "')";
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,7 @@
package codechicken.nei;
public abstract class RestartableTask
{
public abstract class RestartableTask {
public final String name;
private Thread thread;
private volatile boolean restart;
@@ -15,21 +15,22 @@ public abstract class RestartableTask
private void start() {
thread = new Thread(name) {
@Override
public void run() {
do {
while(stopped)
try { Thread.sleep(1); } catch (InterruptedException ignored) {}
if(!restart)
execute();
} while(!finish());
while (stopped) try {
Thread.sleep(1);
} catch (InterruptedException ignored) {}
if (!restart) execute();
} while (!finish());
}
};
thread.start();
}
private synchronized boolean finish() {
if(restart) {
if (restart) {
restart = false;
return false;
} else {
@@ -44,19 +45,18 @@ public abstract class RestartableTask
}
public synchronized void restart() {
if(thread != null) {
if (thread != null) {
stopped = false;
restart = true;
}
else
start();
} else start();
}
/**
* Stops execution until restart is called. If a thread is running, the restart flag will be set, and the thread will be paused once the execute method exits.
* Stops execution until restart is called. If a thread is running, the restart flag will be set, and the thread
* will be paused once the execute method exits.
*/
public synchronized void stop() {
if(thread != null) {
if (thread != null) {
stopped = true;
restart = true;
}
+65 -31
View File
@@ -1,5 +1,14 @@
package codechicken.nei;
import static codechicken.nei.NEIClientConfig.world;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import net.minecraft.util.EnumChatFormatting;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemList.AnyMultiItemFilter;
import codechicken.nei.ItemList.EverythingItemFilter;
@@ -7,22 +16,15 @@ import codechicken.nei.ItemList.PatternItemFilter;
import codechicken.nei.api.API;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import net.minecraft.util.EnumChatFormatting;
import codechicken.nei.util.TextHistory;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class SearchField extends TextField implements ItemFilterProvider {
import static codechicken.nei.NEIClientConfig.world;
public class SearchField extends TextField implements ItemFilterProvider
{
/**
* Interface for returning a custom filter based on search field text
*/
public static interface ISearchProvider
{
public static interface ISearchProvider {
/**
* @return false if this filter should only be used if no other non-default filters match the search string
*/
@@ -34,8 +36,8 @@ public class SearchField extends TextField implements ItemFilterProvider
public ItemFilter getFilter(String searchText);
}
private static class DefaultSearchProvider implements ISearchProvider
{
private static class DefaultSearchProvider implements ISearchProvider {
@Override
public boolean isPrimary() {
return false;
@@ -49,6 +51,8 @@ public class SearchField extends TextField implements ItemFilterProvider
}
public static List<ISearchProvider> searchProviders = new LinkedList<>();
private static final TextHistory history = new TextHistory();
private boolean isVisible = true;
long lastclicktime;
@@ -62,9 +66,16 @@ public class SearchField extends TextField implements ItemFilterProvider
return world.nbt.getBoolean("searchinventories");
}
public boolean isVisible() {
return isVisible;
}
public void setVisible(boolean visible) {
isVisible = visible;
}
@Override
public int getTextColour()
{
public int getTextColour() {
if (ItemPanels.itemPanel.getItems().isEmpty()) {
return focused() ? 0xFFcc3300 : 0xFF993300;
} else {
@@ -78,18 +89,17 @@ public class SearchField extends TextField implements ItemFilterProvider
super.draw(mousex, mousey);
if (searchInventories()) {
GuiDraw.drawGradientRect(x - 1, y - 1, 1, h + 2, 0xFFFFFF00, 0xFFC0B000); //Left
GuiDraw.drawGradientRect(x - 1, y - 1, w + 2, 1, 0xFFFFFF00, 0xFFC0B000); //Top
GuiDraw.drawGradientRect(x + w, y - 1, 1, h + 2, 0xFFFFFF00, 0xFFC0B000); //Left
GuiDraw.drawGradientRect(x - 1, y + h, w + 2, 1, 0xFFFFFF00, 0xFFC0B000); //Bottom
GuiDraw.drawGradientRect(x - 1, y - 1, 1, h + 2, 0xFFFFFF00, 0xFFC0B000); // Left
GuiDraw.drawGradientRect(x - 1, y - 1, w + 2, 1, 0xFFFFFF00, 0xFFC0B000); // Top
GuiDraw.drawGradientRect(x + w, y - 1, 1, h + 2, 0xFFFFFF00, 0xFFC0B000); // Left
GuiDraw.drawGradientRect(x - 1, y + h, w + 2, 1, 0xFFFFFF00, 0xFFC0B000); // Bottom
}
}
@Override
public boolean handleClick(int mousex, int mousey, int button) {
if (button == 0) {
if (focused() && (System.currentTimeMillis() - lastclicktime < 400)) { //double click
if (focused() && (System.currentTimeMillis() - lastclicktime < 400)) { // double click
NEIClientConfig.world.nbt.setBoolean("searchinventories", !searchInventories());
NEIClientConfig.world.saveNBT();
}
@@ -101,8 +111,7 @@ public class SearchField extends TextField implements ItemFilterProvider
@Override
public void onTextChange(String oldText) {
final String newText = text();
if( newText.length() > 0)
NEIClientConfig.logger.debug("Searching for " + text());
if (newText.length() > 0) NEIClientConfig.logger.debug("Searching for " + text());
NEIClientConfig.setSearchExpression(newText);
ItemList.updateFilter.restart();
@@ -110,8 +119,17 @@ public class SearchField extends TextField implements ItemFilterProvider
@Override
public void lastKeyTyped(int keyID, char keyChar) {
if (keyID == NEIClientConfig.getKeyBinding("gui.search"))
if (isVisible() && NEIClientConfig.isKeyHashDown("gui.search")) {
setFocus(true);
}
if (NEIClientConfig.isKeyHashDown("gui.getprevioussearch") && focused()) {
handleNavigateHistory(TextHistory.Direction.PREVIOUS);
}
if (NEIClientConfig.isKeyHashDown("gui.getnextsearch") && focused()) {
handleNavigateHistory(TextHistory.Direction.NEXT);
}
}
@Override
@@ -121,14 +139,11 @@ public class SearchField extends TextField implements ItemFilterProvider
public static Pattern getPattern(String search) {
switch (NEIClientConfig.getIntSetting("inventory.searchmode")) {
case 0://plain
case 0: // plain
search = "\\Q" + search + "\\E";
break;
case 1:
search = search
.replace(".", "")
.replace("?", ".")
.replace("*", ".+?");
search = search.replace(".", "").replace("?", ".").replace("*", ".+?");
break;
}
@@ -147,12 +162,31 @@ public class SearchField extends TextField implements ItemFilterProvider
List<ItemFilter> secondary = new LinkedList<>();
for (ISearchProvider p : searchProviders) {
ItemFilter filter = p.getFilter(s_filter);
if (filter != null)
(p.isPrimary() ? primary : secondary).add(filter);
if (filter != null) (p.isPrimary() ? primary : secondary).add(filter);
}
if (!primary.isEmpty()) return new AnyMultiItemFilter(primary);
if (!secondary.isEmpty()) return new AnyMultiItemFilter(secondary);
return new EverythingItemFilter();
}
@Override
public void setFocus(boolean focus) {
final boolean previousFocus = field.isFocused();
if (previousFocus != focus) {
history.add(text());
}
super.setFocus(focus);
}
private boolean handleNavigateHistory(TextHistory.Direction direction) {
if (focused()) {
return history.get(direction, text()).map(newText -> {
setText(newText);
return true;
}).orElse(false);
}
return false;
}
}
@@ -1,5 +1,13 @@
package codechicken.nei;
import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import codechicken.core.CommonUtils;
import codechicken.lib.packet.PacketCustom;
import cpw.mods.fml.common.FMLCommonHandler;
@@ -10,16 +18,9 @@ import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import java.util.List;
public class ServerHandler {
public class ServerHandler
{
private static ServerHandler instance;
public static void load() {
@@ -34,15 +35,15 @@ public class ServerHandler
@SubscribeEvent
public void tickEvent(TickEvent.WorldTickEvent event) {
if (event.phase == Phase.START && !event.world.isRemote &&
NEIServerConfig.dimTags.containsKey(CommonUtils.getDimension(event.world)))//fake worlds that don't call Load
if (event.phase == Phase.START && !event.world.isRemote
&& NEIServerConfig.dimTags.containsKey(CommonUtils.getDimension(event.world))) // fake worlds that don't
// call Load
processDisabledProperties(event.world);
}
@SubscribeEvent
public void loadEvent(WorldEvent.Load event) {
if(!event.world.isRemote)
NEIServerConfig.load(event.world);
if (!event.world.isRemote) NEIServerConfig.load(event.world);
}
@SubscribeEvent
@@ -50,8 +51,7 @@ public class ServerHandler
if (event.phase == Phase.START && event.player instanceof EntityPlayerMP) {
EntityPlayerMP player = (EntityPlayerMP) event.player;
PlayerSave save = NEIServerConfig.forPlayer(player.getCommandSenderName());
if (save == null)
return;
if (save == null) return;
updateMagneticPlayer(player, save);
save.updateOpChange(player);
save.save();
@@ -60,13 +60,13 @@ public class ServerHandler
private void processDisabledProperties(World world) {
NEIServerUtils.advanceDisabledTimes(world);
if (NEIServerUtils.isRaining(world) && NEIServerConfig.isActionDisabled(CommonUtils.getDimension(world), "rain"))
if (NEIServerUtils.isRaining(world)
&& NEIServerConfig.isActionDisabled(CommonUtils.getDimension(world), "rain"))
NEIServerUtils.toggleRaining(world, false);
}
private void updateMagneticPlayer(EntityPlayerMP player, PlayerSave save) {
if (!save.isActionEnabled("magnet") || player.isDead)
return;
if (!save.isActionEnabled("magnet") || player.isDead) return;
float distancexz = 16;
float distancey = 8;
@@ -74,7 +74,8 @@ public class ServerHandler
double maxspeedy = 0.5;
double speedxz = 0.05;
double speedy = 0.07;
List<EntityItem> items = player.worldObj.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.expand(distancexz, distancey, distancexz));
List<EntityItem> items = player.worldObj
.getEntitiesWithinAABB(EntityItem.class, player.boundingBox.expand(distancexz, distancey, distancexz));
for (EntityItem item : items) {
if (item.delayBeforeCanPickup > 0) continue;
if (!NEIServerUtils.canItemFitInInventory(player, item.getEntityItem())) continue;
+4 -4
View File
@@ -1,10 +1,10 @@
package codechicken.nei;
public abstract class SlotOP
{
public abstract class SlotOP {
public abstract String getDescription();
public abstract int[] getKeyBind();
public abstract void operate();
}
@@ -1,7 +1,5 @@
package codechicken.nei;
import codechicken.core.ClientUtils;
import codechicken.lib.render.CCRenderState;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
@@ -13,82 +11,75 @@ import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.client.IItemRenderer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class SpawnerRenderer implements IItemRenderer
{
import codechicken.core.ClientUtils;
import codechicken.lib.render.CCRenderState;
public class SpawnerRenderer implements IItemRenderer {
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type)
{
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
return true;
}
public void renderInventoryItem(RenderBlocks render, ItemStack item)
{
public void renderInventoryItem(RenderBlocks render, ItemStack item) {
int meta = item.getItemDamage();
if(meta == 0)
meta = ItemMobSpawner.idPig;
if (meta == 0) meta = ItemMobSpawner.idPig;
String bossName = BossStatus.bossName;
int bossTimeout = BossStatus.statusBarTime;
boolean bossHasColorModifier = BossStatus.hasColorModifier;
try
{
try {
World world = NEIClientUtils.mc().theWorld;
ItemMobSpawner.loadSpawners(world);
CCRenderState.changeTexture(TextureMap.locationBlocksTexture);
render.renderBlockAsItem(Blocks.mob_spawner, 0, 1F);
GL11.glPushMatrix();
Entity entity = ItemMobSpawner.getEntity(meta);
entity.setWorld(world);
float f1 = 0.4375F;
if(entity.getShadowSize() > 1.5)
f1 = 0.1F;
GL11.glRotatef((float) (ClientUtils.getRenderTime()*10), 0.0F, 1.0F, 0.0F);
if (entity.getShadowSize() > 1.5) f1 = 0.1F;
GL11.glRotatef((float) (ClientUtils.getRenderTime() * 10), 0.0F, 1.0F, 0.0F);
GL11.glRotatef(-20F, 1.0F, 0.0F, 0.0F);
GL11.glTranslatef(0.0F, -0.4F, 0.0F);
GL11.glScalef(f1, f1, f1);
entity.setLocationAndAngles(0, 0, 0, 0.0F, 0.0F);
RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, 0);
GL11.glPopMatrix();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GL11.glDisable(GL11.GL_TEXTURE_2D);
OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit);
}
catch(Exception e)
{
if(Tessellator.instance.isDrawing)
Tessellator.instance.draw();
} catch (Exception e) {
if (Tessellator.instance.isDrawing) Tessellator.instance.draw();
}
BossStatus.bossName = bossName;
BossStatus.statusBarTime = bossTimeout;
BossStatus.hasColorModifier = bossHasColorModifier;
}
@SuppressWarnings("incomplete-switch")
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
switch(type)
{
public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
switch (type) {
case EQUIPPED:
case EQUIPPED_FIRST_PERSON:
GL11.glTranslatef(0.5F, 0.5F, 0.5F);
case INVENTORY:
case ENTITY:
renderInventoryItem((RenderBlocks)data[0], item);
break;
renderInventoryItem((RenderBlocks) data[0], item);
break;
}
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper)
{
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
return true;
}
}
}
+170 -223
View File
@@ -1,22 +1,6 @@
package codechicken.nei;
import codechicken.core.gui.GuiScrollSlot;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemList.AnyMultiItemFilter;
import codechicken.nei.ItemList.ItemsLoadedCallback;
import codechicken.nei.ItemList.NothingItemFilter;
import codechicken.nei.SearchField.ISearchProvider;
import codechicken.nei.api.API;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.EnumChatFormatting;
import static codechicken.nei.NEIClientUtils.translate;
import java.awt.Point;
import java.util.ArrayList;
@@ -32,24 +16,41 @@ import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Pattern;
import static codechicken.nei.NEIClientUtils.translate;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.EnumChatFormatting;
import codechicken.core.gui.GuiScrollSlot;
import codechicken.lib.gui.GuiDraw;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.ItemList.AnyMultiItemFilter;
import codechicken.nei.ItemList.ItemsLoadedCallback;
import codechicken.nei.ItemList.NothingItemFilter;
import codechicken.nei.SearchField.ISearchProvider;
import codechicken.nei.api.API;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemFilter.ItemFilterProvider;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoadedCallback, ISearchProvider {
public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoadedCallback, ISearchProvider
{
public static ReentrantReadWriteLock hiddenItemLock = new ReentrantReadWriteLock();
public static Lock writeLock = hiddenItemLock.writeLock();
public static Lock readLock = hiddenItemLock.readLock();
public static class SubsetState
{
public static class SubsetState {
int state = 2;
ArrayList<ItemStack> items = new ArrayList<>();
}
public static class SubsetTag
{
protected class SubsetSlot extends GuiScrollSlot
{
public static class SubsetTag {
protected class SubsetSlot extends GuiScrollSlot {
public SubsetSlot() {
super(0, 0, 0, 0);
setSmoothScroll(false);
@@ -62,25 +63,21 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
@Override
protected int getNumSlots() {
return children.size()+state.items.size();
return children.size() + state.items.size();
}
@Override
protected void slotClicked(int slot, int button, int mx, int my, int count) {
if(slot < sorted.size()) {
if (slot < sorted.size()) {
SubsetTag tag = sorted.get(slot);
if (NEIClientUtils.shiftKey())
codechicken.nei.LayoutManager.searchField.setText("@" + tag.fullname);
else if (button == 0 && count >= 2)
SubsetWidget.showOnly(tag);
else
SubsetWidget.setHidden(tag, button == 1);
else if (button == 0 && count >= 2) SubsetWidget.showOnly(tag);
else SubsetWidget.setHidden(tag, button == 1);
} else {
ItemStack item = state.items.get(slot-sorted.size());
if(NEIClientUtils.controlKey())
NEIClientUtils.cheatItem(item, button, -1);
else
SubsetWidget.setHidden(state.items.get(slot-sorted.size()), button == 1);
ItemStack item = state.items.get(slot - sorted.size());
if (NEIClientUtils.controlKey()) NEIClientUtils.cheatItem(item, button, -1);
else SubsetWidget.setHidden(state.items.get(slot - sorted.size()), button == 1);
}
}
@@ -88,32 +85,31 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
protected void drawSlot(int slot, int x, int y, int mx, int my, float frame) {
int w = windowBounds().width;
Rectangle4i r = new Rectangle4i(x, y, w, getSlotHeight(slot));
if(slot < sorted.size()) {
if (slot < sorted.size()) {
SubsetTag tag = sorted.get(slot);
codechicken.nei.LayoutManager.getLayoutStyle().drawSubsetTag(tag.displayName(), x, y, r.w, r.h, tag.state.state, r.contains(mx, my));
}
else {
ItemStack stack = state.items.get(slot-sorted.size());
codechicken.nei.LayoutManager.getLayoutStyle()
.drawSubsetTag(tag.displayName(), x, y, r.w, r.h, tag.state.state, r.contains(mx, my));
} else {
ItemStack stack = state.items.get(slot - sorted.size());
boolean hidden = SubsetWidget.isHidden(stack);
int itemx = w/2-8;
int itemx = w / 2 - 8;
int itemy = 1;
codechicken.nei.LayoutManager.getLayoutStyle().drawSubsetTag(null, x, y, r.w, r.h, hidden ? 0 : 2, false);
codechicken.nei.LayoutManager.getLayoutStyle()
.drawSubsetTag(null, x, y, r.w, r.h, hidden ? 0 : 2, false);
GuiContainerManager.drawItem(x+itemx, y+itemy, stack);
if(new Rectangle4i(itemx, itemy, 16, 16).contains(mx, my))
SubsetWidget.hoverStack = stack;
GuiContainerManager.drawItem(x + itemx, y + itemy, stack);
if (new Rectangle4i(itemx, itemy, 16, 16).contains(mx, my)) SubsetWidget.hoverStack = stack;
}
}
@Override
public void drawOverlay(float frame) {
}
public void drawOverlay(float frame) {}
@Override
public void drawBackground(float frame) {
drawRect(x, y, x+width, y+height, 0xFF202020);
drawRect(x, y, x + width, y + height, 0xFF202020);
}
@Override
@@ -123,8 +119,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
@Override
public void drawScrollbar(float frame) {
if(hasScrollbar())
super.drawScrollbar(frame);
if (hasScrollbar()) super.drawScrollbar(frame);
}
@Override
@@ -155,9 +150,8 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
}
public String displayName() {
String translated = translate("subsets."+fullname);
if(!translated.startsWith("nei."))
return translated;
String translated = translate("subsets." + fullname);
if (!translated.startsWith("nei.")) return translated;
int idx = fullname.lastIndexOf('.');
return idx < 0 ? fullname : fullname.substring(idx + 1);
@@ -165,7 +159,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public String name() {
int idx = fullname.indexOf('.');
return idx < 0 ? fullname : fullname.substring(idx+1);
return idx < 0 ? fullname : fullname.substring(idx + 1);
}
public String parent() {
@@ -177,36 +171,34 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
int idx = name.indexOf('.');
String childname = idx > 0 ? name.substring(0, idx) : name;
SubsetTag child = children.get(childname.toLowerCase());
if(child == null)
return null;
if (child == null) return null;
return idx > 0 ? child.getTag(name.substring(idx+1)) : child;
return idx > 0 ? child.getTag(name.substring(idx + 1)) : child;
}
private void recacheChildren() {
sorted = new ArrayList<>(children.values());
childwidth = 0;
for(SubsetTag tag : sorted)
childwidth = Math.max(childwidth, tag.nameWidth()+2);
for (SubsetTag tag : sorted) childwidth = Math.max(childwidth, tag.nameWidth() + 2);
}
private void addTag(SubsetTag tag) {
String name = fullname == null ? tag.fullname : tag.fullname.substring(fullname.length()+1);
String name = fullname == null ? tag.fullname : tag.fullname.substring(fullname.length() + 1);
int idx = name.indexOf('.');
if(idx < 0) {//add or replace tag
if (idx < 0) { // add or replace tag
SubsetTag prev = children.put(name.toLowerCase(), tag);
if(prev != null) {//replaced, load children
if (prev != null) { // replaced, load children
tag.children = prev.children;
tag.sorted = prev.sorted;
}
recacheChildren();
}
else {
} else {
String childname = name.substring(0, idx);
SubsetTag child = children.get(childname.toLowerCase());
if(child == null)
children.put(childname.toLowerCase(), child = new SubsetTag(fullname == null ? childname : fullname+'.'+childname));
if (child == null) children.put(
childname.toLowerCase(),
child = new SubsetTag(fullname == null ? childname : fullname + '.' + childname));
recacheChildren();
child.addTag(tag);
}
@@ -214,51 +206,42 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
protected void cacheState() {
state = SubsetWidget.getState(this);
for(SubsetTag tag : sorted)
tag.cacheState();
for (SubsetTag tag : sorted) tag.cacheState();
}
public void addFiltersWithItem(List<ItemFilter> filters, String itemSearch) {
if(itemSearch == null) {
if (itemSearch == null) {
addFilters(filters);
} else {
if(filter != null)
filters.add(new DoubleFilteredFilter(filter, itemSearch));
if (filter != null) filters.add(new DoubleFilteredFilter(filter, itemSearch));
for(SubsetTag child : sorted)
child.addFiltersWithItem(filters, itemSearch);
for (SubsetTag child : sorted) child.addFiltersWithItem(filters, itemSearch);
}
}
public void addFilters(List<ItemFilter> filters) {
if(filter != null)
filters.add(filter);
for(SubsetTag child : sorted)
child.addFilters(filters);
public void addFilters(List<ItemFilter> filters) {
if (filter != null) filters.add(filter);
for (SubsetTag child : sorted) child.addFilters(filters);
}
public void search(List<SubsetTag> tags, Pattern p) {
if(fullname != null && p.matcher(fullname.toLowerCase()).find())
tags.add(this);
else
for(SubsetTag child : sorted)
child.search(tags, p);
if (fullname != null && p.matcher(fullname.toLowerCase()).find()) tags.add(this);
else for (SubsetTag child : sorted) child.search(tags, p);
}
public void updateVisiblity(int mx, int my) {
if(selectedChild != null) {
if (selectedChild != null) {
selectedChild.updateVisiblity(mx, my);
if(!selectedChild.isVisible())
selectedChild = null;
if (!selectedChild.isVisible()) selectedChild = null;
}
if(slot.contains(mx, my) && (selectedChild == null || !selectedChild.contains(mx, my))) {
if (slot.contains(mx, my) && (selectedChild == null || !selectedChild.contains(mx, my))) {
int mslot = slot.getClickedSlot(my);
if(mslot >= 0 && mslot < sorted.size()) {
if (mslot >= 0 && mslot < sorted.size()) {
SubsetTag mtag = sorted.get(mslot);
if(mtag != null) {
if(mtag != selectedChild && selectedChild != null)
selectedChild.setHidden();
if (mtag != null) {
if (mtag != selectedChild && selectedChild != null) selectedChild.setHidden();
selectedChild = mtag;
selectedChild.setVisible();
}
@@ -267,14 +250,13 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
setVisible();
}
if(selectedChild == null)
countdownVisible();
if (selectedChild == null) countdownVisible();
}
public void setHidden() {
visible = 0;
slot.mouseMovedOrUp(0, 0, 0);//cancel any scrolling
if(selectedChild != null) {
slot.mouseMovedOrUp(0, 0, 0); // cancel any scrolling
if (selectedChild != null) {
selectedChild.setHidden();
selectedChild = null;
}
@@ -286,41 +268,37 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
}
private void countdownVisible() {
if(visible > 0 && --visible == 0)
setHidden();
if (visible > 0 && --visible == 0) setHidden();
}
public void resize(int x, int pwidth, int y) {
int mheight = area.h;
int dheight = area.y2()-y;
int dheight = area.y2() - y;
int cheight = slot.contentHeight();
int height = cheight;
if(cheight > mheight) {
if (cheight > mheight) {
y = area.y;
height = mheight;
} else if(cheight > dheight) {
} else if (cheight > dheight) {
y = area.y2() - cheight;
}
height = height/slot.getSlotHeight(0)*slot.getSlotHeight(0);//floor to a multiple of slot height
height = height / slot.getSlotHeight(0) * slot.getSlotHeight(0); // floor to a multiple of slot height
int width = childwidth;
if(!state.items.isEmpty())
width = Math.max(childwidth, 18);
if(slot.contentHeight() > height)
width+=slot.scrollbarDim().width;
if (!state.items.isEmpty()) width = Math.max(childwidth, 18);
if (slot.contentHeight() > height) width += slot.scrollbarDim().width;
boolean fitLeft = x-width >= area.x1();
boolean fitRight = x+width+pwidth <= area.x2();
if(pwidth >= 0 ? !fitRight && fitLeft : !fitLeft)
pwidth*=-1;//swap
boolean fitLeft = x - width >= area.x1();
boolean fitRight = x + width + pwidth <= area.x2();
if (pwidth >= 0 ? !fitRight && fitLeft : !fitLeft) pwidth *= -1; // swap
x += pwidth >= 0 ? pwidth : -width;
slot.setSize(x, y, width, height);
slot.setMargins(slot.hasScrollbar() ? slot.scrollbarDim().width : 0, 0, 0, 0);
if(selectedChild != null) {
y = slot.getSlotY(sorted.indexOf(selectedChild))-slot.scrolledPixels()+slot.y;
if (selectedChild != null) {
y = slot.getSlotY(sorted.indexOf(selectedChild)) - slot.scrolledPixels() + slot.y;
selectedChild.resize(x, pwidth >= 0 ? width : -width, y);
}
}
@@ -335,44 +313,37 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public void draw(int mx, int my) {
slot.draw(mx, my, 0);
if(selectedChild != null)
selectedChild.draw(mx, my);
if (selectedChild != null) selectedChild.draw(mx, my);
}
public boolean contains(int px, int py) {
return slot.contains(px, py) ||
selectedChild != null && selectedChild.contains(px, py);
return slot.contains(px, py) || selectedChild != null && selectedChild.contains(px, py);
}
public void mouseClicked(int mx, int my, int button) {
if(selectedChild != null && selectedChild.contains(mx, my))
selectedChild.mouseClicked(mx, my, button);
else if(slot.contains(mx, my))
slot.mouseClicked(mx, my, button);
if (selectedChild != null && selectedChild.contains(mx, my)) selectedChild.mouseClicked(mx, my, button);
else if (slot.contains(mx, my)) slot.mouseClicked(mx, my, button);
}
public void mouseDragged(int mx, int my, int button, long heldTime) {
slot.mouseDragged(mx, my, button, heldTime);
if(selectedChild != null)
selectedChild.mouseDragged(mx, my, button, heldTime);
if (selectedChild != null) selectedChild.mouseDragged(mx, my, button, heldTime);
}
public void mouseUp(int mx, int my, int button) {
slot.mouseMovedOrUp(mx, my, button);
if(selectedChild != null)
selectedChild.mouseUp(mx, my, button);
if (selectedChild != null) selectedChild.mouseUp(mx, my, button);
}
public boolean mouseScrolled(int mx, int my, int scroll) {
if(slot.hasScrollbar() && slot.contains(mx, my)) {
if (slot.hasScrollbar() && slot.contains(mx, my)) {
slot.scroll(scroll);
return true;
}
if(selectedChild != null && selectedChild.mouseScrolled(mx, my, scroll))
return true;
if (selectedChild != null && selectedChild.mouseScrolled(mx, my, scroll)) return true;
if(slot.hasScrollbar() && !contains(mx, my)) {
if (slot.hasScrollbar() && !contains(mx, my)) {
slot.scroll(scroll);
return true;
}
@@ -381,8 +352,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
}
public boolean isScrolling() {
return slot.isScrolling() ||
selectedChild != null && selectedChild.isScrolling();
return slot.isScrolling() || selectedChild != null && selectedChild.isScrolling();
}
}
@@ -395,6 +365,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
* All operations on this variable should be synchronised.
*/
private static final ItemStackSet hiddenItems = new ItemStackSet();
private static final AtomicReference<NBTTagList> dirtyHiddenItems = new AtomicReference<>();
public static SubsetState getState(SubsetTag tag) {
@@ -416,7 +387,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public static boolean isHidden(ItemStack item) {
try {
if(readLock.tryLock(5, TimeUnit.SECONDS)) {
if (readLock.tryLock(5, TimeUnit.SECONDS)) {
try {
return hiddenItems.contains(item);
} finally {
@@ -432,27 +403,22 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
}
private static void _setHidden(SubsetTag tag, boolean hidden) {
for(ItemStack item : getState(tag).items)
_setHidden(item, hidden);
for(SubsetTag child : tag.sorted)
_setHidden(child, hidden);
for (ItemStack item : getState(tag).items) _setHidden(item, hidden);
for (SubsetTag child : tag.sorted) _setHidden(child, hidden);
}
private static void _setHidden(ItemStack item, boolean hidden) {
if (hiddenItemLock.isWriteLockedByCurrentThread()) {
if (hidden)
hiddenItems.add(item);
else
hiddenItems.remove(item);
if (hidden) hiddenItems.add(item);
else hiddenItems.remove(item);
}
}
public static void showOnly(SubsetTag tag) {
try {
if(writeLock.tryLock(5, TimeUnit.SECONDS)) {
if (writeLock.tryLock(5, TimeUnit.SECONDS)) {
try {
for (ItemStack item : ItemList.items)
_setHidden(item, true);
for (ItemStack item : ItemList.items) _setHidden(item, true);
setHidden(tag, false);
} finally {
writeLock.unlock();
@@ -467,7 +433,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public static void setHidden(SubsetTag tag, boolean hidden) {
try {
if(writeLock.tryLock(5, TimeUnit.SECONDS)) {
if (writeLock.tryLock(5, TimeUnit.SECONDS)) {
try {
_setHidden(tag, hidden);
updateHiddenItems();
@@ -484,7 +450,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public static void setHidden(ItemStack item, boolean hidden) {
try {
if(writeLock.tryLock(5, TimeUnit.SECONDS)) {
if (writeLock.tryLock(5, TimeUnit.SECONDS)) {
try {
_setHidden(item, hidden);
updateHiddenItems();
@@ -501,7 +467,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public static void unhideAll() {
try {
if(writeLock.tryLock(5, TimeUnit.SECONDS)) {
if (writeLock.tryLock(5, TimeUnit.SECONDS)) {
try {
hiddenItems.clear();
updateHiddenItems();
@@ -523,7 +489,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public static void loadHidden() {
try {
if(writeLock.tryLock(5, TimeUnit.SECONDS)) {
if (writeLock.tryLock(5, TimeUnit.SECONDS)) {
try {
hiddenItems.clear();
} finally {
@@ -540,19 +506,17 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
List<ItemStack> itemList = new LinkedList<>();
try {
NBTTagList list = NEIClientConfig.world.nbt.getTagList("hiddenItems", 10);
for(int i = 0; i < list.tagCount(); i++)
for (int i = 0; i < list.tagCount(); i++)
itemList.add(ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(i)));
}
catch (Exception e) {
} catch (Exception e) {
NEIClientConfig.logger.error("Error loading hiddenItems", e);
return;
}
try {
if(writeLock.tryLock(5, TimeUnit.SECONDS)) {
if (writeLock.tryLock(5, TimeUnit.SECONDS)) {
try {
for (ItemStack item : itemList)
hiddenItems.add(item);
for (ItemStack item : itemList) hiddenItems.add(item);
} finally {
writeLock.unlock();
}
@@ -567,17 +531,17 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
private static void saveHidden() {
NBTTagList list = dirtyHiddenItems.getAndSet(null);
if(list != null) {
if (list != null) {
NEIClientConfig.world.nbt.setTag("hiddenItems", list);
NEIClientConfig.world.saveNBT();
}
}
private static final RestartableTask prepareDirtyHiddenItems = new RestartableTask("NEI Subset Save Thread")
{
private static final RestartableTask prepareDirtyHiddenItems = new RestartableTask("NEI Subset Save Thread") {
private List<ItemStack> getList() {
try {
if(readLock.tryLock(5, TimeUnit.SECONDS)) {
if (readLock.tryLock(5, TimeUnit.SECONDS)) {
try {
return hiddenItems.values();
} finally {
@@ -595,8 +559,8 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
@Override
public void execute() {
NBTTagList list = new NBTTagList();
for(ItemStack item : getList()) {
if(interrupted()) return;
for (ItemStack item : getList()) {
if (interrupted()) return;
NBTTagCompound tag = new NBTTagCompound();
item.writeToNBT(tag);
list.appendTag(tag);
@@ -606,8 +570,9 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
};
private static final UpdateStateTask updateState = new UpdateStateTask();
private static class UpdateStateTask extends RestartableTask
{
private static class UpdateStateTask extends RestartableTask {
private volatile boolean reallocate;
public UpdateStateTask() {
@@ -634,22 +599,20 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
List<SubsetTag> tags = new LinkedList<>();
synchronized (root) {
cloneStates(root, tags, state);
if(interrupted()) return;
if (interrupted()) return;
}
if(reallocate) {
if (reallocate) {
for (ItemStack item : ItemList.items) {
if(interrupted()) return;
if(ItemInfo.isHidden(item)) continue;
for (SubsetTag tag : tags)
if (tag.filter.matches(item))
state.get(tag.fullname).items.add(item);
if (interrupted()) return;
if (ItemInfo.isHidden(item)) continue;
for (SubsetTag tag : tags) if (tag.filter.matches(item)) state.get(tag.fullname).items.add(item);
}
}
synchronized (root) {
calculateVisibility(root, state);
if(interrupted()) return;
if (interrupted()) return;
}
subsetState = state;
@@ -657,44 +620,38 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
}
private void cloneStates(SubsetTag tag, List<SubsetTag> tags, HashMap<String, SubsetState> state) {
for(SubsetTag child : tag.sorted) {
if(interrupted()) return;
for (SubsetTag child : tag.sorted) {
if (interrupted()) return;
cloneStates(child, tags, state);
}
tags.add(tag);
SubsetState sstate = new SubsetState();
if(!reallocate)
sstate.items = SubsetWidget.getState(tag).items;
if (!reallocate) sstate.items = SubsetWidget.getState(tag).items;
state.put(tag.fullname, sstate);
}
private void calculateVisibility(SubsetTag tag, Map<String, SubsetState> state) {
SubsetState sstate = state.get(tag.fullname);
int hidden = 0;
for(SubsetTag child : tag.sorted) {
if(interrupted()) return;
for (SubsetTag child : tag.sorted) {
if (interrupted()) return;
calculateVisibility(child, state);
int cstate = state.get(child.fullname).state;
if(cstate == 1)
sstate.state = 1;
else if(cstate == 0)
hidden++;
if (cstate == 1) sstate.state = 1;
else if (cstate == 0) hidden++;
}
if(sstate.state == 1) return;
if (sstate.state == 1) return;
List<ItemStack> items = sstate.items;
for(ItemStack item : items) {
if(interrupted()) return;
if (isHidden(item))
hidden++;
for (ItemStack item : items) {
if (interrupted()) return;
if (isHidden(item)) hidden++;
}
if(hidden == tag.sorted.size()+items.size())
sstate.state = 0;
else if(hidden > 0)
sstate.state = 1;
if (hidden == tag.sorted.size() + items.size()) sstate.state = 0;
else if (hidden > 0) sstate.state = 1;
}
}
@@ -716,7 +673,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
public void draw(int mx, int my) {
super.draw(mx, my);
area.set(x, y + h, w, LayoutManager.searchField.y - h - y); //23 for the search box
area.set(x, y + h, w, LayoutManager.searchField.y - h - y); // 23 for the search box
hoverStack = null;
if (root.isVisible()) {
@@ -734,33 +691,28 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
}
private void updateVisiblity(int mx, int my) {
if(!root.isVisible() || root.isScrolling())
return;
if (!root.isVisible() || root.isScrolling()) return;
root.updateVisiblity(mx, my);
if(!root.isVisible() && bounds().contains(mx, my))
root.setVisible();
if (!root.isVisible() && bounds().contains(mx, my)) root.setVisible();
}
@Override
public boolean contains(int px, int py) {
return super.contains(px, py) ||
root.isVisible() && root.contains(px, py);
return super.contains(px, py) || root.isVisible() && root.contains(px, py);
}
@Override
public boolean handleClick(int mx, int my, int button) {
if(root.isVisible() && root.contains(mx, my)) {
if (root.isVisible() && root.contains(mx, my)) {
root.mouseClicked(mx, my, button);
return true;
}
if(button == 0) {
if(System.currentTimeMillis() - lastclicktime < 500)
unhideAll();
else
root.setVisible();
if (button == 0) {
if (System.currentTimeMillis() - lastclicktime < 500) unhideAll();
else root.setVisible();
NEIClientUtils.playClickSound();
lastclicktime = System.currentTimeMillis();
@@ -779,14 +731,12 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
@Override
public void mouseDragged(int mx, int my, int button, long heldTime) {
if(root.isVisible())
root.mouseDragged(mx, my, button, heldTime);
if (root.isVisible()) root.mouseDragged(mx, my, button, heldTime);
}
@Override
public void mouseUp(int mx, int my, int button) {
if(root.isVisible())
root.mouseUp(mx, my, button);
if (root.isVisible()) root.mouseUp(mx, my, button);
}
@Override
@@ -796,8 +746,7 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
@Override
public void onGuiClick(int mx, int my) {
if(!contains(mx, my))
root.setHidden();
if (!contains(mx, my)) root.setHidden();
}
@Override
@@ -807,10 +756,10 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
@Override
public ItemFilter getFilter() {
//synchronise access on hiddenItems
// synchronise access on hiddenItems
return item -> {
try {
if(readLock.tryLock(5, TimeUnit.SECONDS)) {
if (readLock.tryLock(5, TimeUnit.SECONDS)) {
try {
return !hiddenItems.matches(item);
} finally {
@@ -833,36 +782,34 @@ public class SubsetWidget extends Button implements ItemFilterProvider, ItemsLoa
@Override
public ItemFilter getFilter(String searchText) {
if(!searchText.startsWith("@"))
return null;
if (!searchText.startsWith("@")) return null;
searchText = searchText.substring(1);
String itemSearch = null;
if(searchText.contains("->")) {
if (searchText.contains("->")) {
String[] split = searchText.split("->");
searchText = split[0];
if(split.length > 1) itemSearch = split[1];
if (split.length > 1) itemSearch = split[1];
}
AnyMultiItemFilter filter = new AnyMultiItemFilter();
SubsetTag tag = getTag(searchText);
if(tag != null) {
if (tag != null) {
// We've got an exact match
tag.addFiltersWithItem(filter.filters, itemSearch);
}
else {
} else {
// Try searching for a substring
Pattern p = SearchField.getPattern(searchText);
if(p == null) return null;
if (p == null) return null;
List<SubsetTag> matching = new LinkedList<>();
root.search(matching, p);
if(matching.isEmpty()) return null;
for(SubsetTag tag2 : matching) {
if (matching.isEmpty()) return null;
for (SubsetTag tag2 : matching) {
tag2.addFiltersWithItem(filter.filters, itemSearch);
}
}
return filter;
}
+12 -19
View File
@@ -2,10 +2,11 @@ package codechicken.nei;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiTextField;
import org.lwjgl.input.Keyboard;
public abstract class TextField extends Widget
{
public abstract class TextField extends Widget {
protected GuiTextField field;
private static final int maxSearchLength = 256;
@@ -24,7 +25,7 @@ public abstract class TextField extends Widget
public TextField(String ident) {
identifier = ident;
initInternalTextField();
// Keyboard.enableRepeatEvents(true);
// Keyboard.enableRepeatEvents(true);
}
public int getTextColour() {
@@ -44,7 +45,7 @@ public abstract class TextField extends Widget
try {
setDimensionsAndColor();
field.drawTextBox();
} catch(NullPointerException npe) {
} catch (NullPointerException npe) {
// Hack to deal with a null font renderer... recreate the field and it should work
GuiTextField oldField = field;
@@ -58,49 +59,43 @@ public abstract class TextField extends Widget
@Override
public void onGuiClick(int mousex, int mousey) {
if (!contains(mousex, mousey))
setFocus(false);
if (!contains(mousex, mousey)) setFocus(false);
}
@Override
public boolean handleClick(int mousex, int mousey, int button) {
setFocus(true);
if (button == 1)
setText("");
else
field.mouseClicked(mousex, mousey, button);
if (button == 1) setText("");
else field.mouseClicked(mousex, mousey, button);
return true;
}
@Override
public boolean handleKeyPress(int keyID, char keyChar) {
if (!focused())
return false;
if (!focused()) return false;
String oldText = text();
boolean handled = field.textboxKeyTyped(keyChar, keyID);
if(!handled) {
if (!handled) {
if (keyID == Keyboard.KEY_RETURN || keyID == Keyboard.KEY_NUMPADENTER || keyID == Keyboard.KEY_ESCAPE) {
setFocus(false);
handled = true;
}
}
if(handled) {
if (handled) {
onTextChange(oldText);
}
return handled;
}
public abstract void onTextChange(String oldText);
@Override
public void update() {
}
public void update() {}
public void setText(String s) {
String oldText = text();
@@ -126,7 +121,6 @@ public abstract class TextField extends Widget
Keyboard.enableRepeatEvents(previousKeyboardRepeatEnabled);
loseFocus();
}
}
}
@@ -137,5 +131,4 @@ public abstract class TextField extends Widget
public String text() {
return field.getText();
}
}
@@ -1,13 +1,14 @@
package codechicken.nei;
import com.google.common.base.Objects;
import cpw.mods.fml.common.FMLCommonHandler;
public class ThreadOperationTimer extends Thread
{
public class ThreadOperationTimer extends Thread {
@SuppressWarnings("serial")
public static class TimeoutException extends RuntimeException
{
public static class TimeoutException extends RuntimeException {
public final Object operation;
public TimeoutException(String msg, Object op) {
@@ -22,7 +23,7 @@ public class ThreadOperationTimer extends Thread
private long limit;
private ThreadOperationTimer(Thread thread, int limit) {
super(thread.getName()+" Operation Timer");
super(thread.getName() + " Operation Timer");
this.thread = thread;
this.limit = limit;
}
@@ -41,7 +42,7 @@ public class ThreadOperationTimer extends Thread
}
public synchronized void update(Object op) {
if(!Objects.equal(operation, op)) {
if (!Objects.equal(operation, op)) {
operation = op;
opTime = System.currentTimeMillis();
}
@@ -50,14 +51,19 @@ public class ThreadOperationTimer extends Thread
@SuppressWarnings("deprecation")
@Override
public void run() {
if(FMLCommonHandler.instance().findContainerFor("NotEnoughItems").getVersion().contains("$"))
return;//don't run this thread in a source environment
if (FMLCommonHandler.instance().findContainerFor("NotEnoughItems").getVersion().contains("$")) return; // don't
// run
// this
// thread
// in a
// source
// environment
while (thread.isAlive()) {
synchronized (this) {
if (operation != null && System.currentTimeMillis() - opTime > limit) {
// Thread.stop(Throwable) is hard-deprecated and IntelliJ complains about it.
//thread.stop(new TimeoutException("Operation took too long", operation));
// thread.stop(new TimeoutException("Operation took too long", operation));
thread.stop();
}
}
@@ -72,4 +78,4 @@ public class ThreadOperationTimer extends Thread
t.start();
return t;
}
}
}
@@ -1,7 +1,7 @@
package codechicken.nei;
public class VisiblityData
{
public class VisiblityData {
public boolean showUtilityButtons = true;
/**
* Item panel and associated buttons
@@ -35,19 +35,16 @@ public class VisiblityData
* The entire NEI interface, aka hidden
*/
public boolean showNEI = true;
public boolean enableDeleteMode = true;
// Deprecated -- left in for campatability with other mods that mess with this
public boolean showStateButtons = false;
public void translateDependancies()
{
if(!showNEI)
showWidgets = false;
if(!showWidgets)
showItemSection = showUtilityButtons = false;
if(!showItemSection)
public void translateDependancies() {
if (!showNEI) showWidgets = false;
if (!showWidgets) showItemSection = showUtilityButtons = false;
if (!showItemSection)
showBookmarkPanel = showSubsetDropdown = showPresetsDropdown = showSearchSection = showItemPanel = false;
}
}
+17 -24
View File
@@ -1,37 +1,34 @@
package codechicken.nei;
import codechicken.lib.vec.Rectangle4i;
import net.minecraft.item.ItemStack;
import java.util.List;
public abstract class Widget
{
public Widget() {
}
import net.minecraft.item.ItemStack;
import codechicken.lib.vec.Rectangle4i;
public abstract class Widget {
public Widget() {}
public abstract void draw(int mx, int my);
public void postDraw(int mx, int my) {
}
public void postDraw(int mx, int my) {}
public void postDrawTooltips(int mx, int my, List<String> tooltip) {}
public boolean handleClick(int mx, int my, int button) {
return true;
}
public void onGuiClick(int mx, int my) {
}
public void onGuiClick(int mx, int my) {}
public void mouseUp(int mx, int my, int button) {
}
public void mouseUp(int mx, int my, int button) {}
public boolean handleKeyPress(int keyID, char keyChar) {
return false;
}
public void lastKeyTyped(int keyID, char keyChar) {
}
public void lastKeyTyped(int keyID, char keyChar) {}
public boolean handleClickExt(int mx, int my, int button) {
return false;
@@ -41,8 +38,7 @@ public abstract class Widget
return false;
}
public void update() {
}
public void update() {}
public Rectangle4i bounds() {
return new Rectangle4i(x, y, w, h);
@@ -56,18 +52,15 @@ public abstract class Widget
return null;
}
public void mouseDragged(int mx, int my, int button, long heldTime) {
}
public void mouseDragged(int mx, int my, int button, long heldTime) {}
public List<String> handleTooltip(int mx, int my, List<String> tooltip) {
return tooltip;
}
public void loseFocus() {
}
public void loseFocus() {}
public void gainFocus() {
}
public void gainFocus() {}
public int x;
public int y;
@@ -2,17 +2,15 @@ package codechicken.nei;
import java.util.Comparator;
public class WidgetZOrder
implements Comparator<Widget>
{
public class WidgetZOrder implements Comparator<Widget> {
final boolean topfirst;
public WidgetZOrder(boolean topfirst)
{
public WidgetZOrder(boolean topfirst) {
this.topfirst = topfirst;
}
public int compare(Widget w1, Widget w2)
{
public int compare(Widget w1, Widget w2) {
return w1.z != w2.z ? ((topfirst ? w1.z > w2.z : w1.z < w2.z) ? 1 : -1) : 1;
}
}
@@ -1,9 +1,7 @@
package codechicken.nei;
import codechicken.lib.math.MathHelper;
import codechicken.lib.render.RenderUtils;
import codechicken.nei.KeyManager.IKeyStateTracker;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.passive.EntityPig;
@@ -13,8 +11,12 @@ import net.minecraft.world.SpawnerAnimals;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import org.lwjgl.opengl.GL11;
import codechicken.lib.math.MathHelper;
import codechicken.nei.KeyManager.IKeyStateTracker;
public class WorldOverlayRenderer implements IKeyStateTracker {
public static int chunkOverlay = 0;
@@ -22,19 +24,20 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
public static int mobOverlay = 0;
private static byte[] mobSpawnCache;
private static long mobOverlayUpdateTime;
private static String oregenPatternName;
private static boolean hasOregenPatternBeenSet = false;
public static void reset() {
mobOverlay = 0;
chunkOverlay = 0;
hasOregenPatternBeenSet = false;
}
@Override
public void tickKeyStates() {
if (Minecraft.getMinecraft().currentScreen != null)
return;
if (Minecraft.getMinecraft().currentScreen != null) return;
if (KeyManager.keyStates.get("world.moboverlay").down)
mobOverlay = (mobOverlay + 1) % 2;
if (KeyManager.keyStates.get("world.moboverlay").down) mobOverlay = (mobOverlay + 1) % 2;
if (KeyManager.keyStates.get("world.chunkoverlay").down)
chunkOverlay = (chunkOverlay + 1) % (NEIModContainer.isGT5Loaded() ? 4 : 3);
}
@@ -42,10 +45,19 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
public static void render(float frame) {
GL11.glPushMatrix();
Entity entity = Minecraft.getMinecraft().renderViewEntity;
RenderUtils.translateToWorldCoords(entity, frame);
renderChunkBounds(entity);
renderMobSpawnOverlay(entity);
double interpPosX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * frame;
double interpPosY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * frame;
double interpPosZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * frame;
int intOffsetX = (int) interpPosX;
int intOffsetY = (int) interpPosY;
int intOffsetZ = (int) interpPosZ;
GL11.glTranslated(-interpPosX + intOffsetX, -interpPosY + intOffsetY, -interpPosZ + intOffsetZ);
renderChunkBounds(entity, intOffsetX, intOffsetY, intOffsetZ);
renderMobSpawnOverlay(entity, intOffsetX, intOffsetY, intOffsetZ);
GL11.glPopMatrix();
}
@@ -86,7 +98,7 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
}
}
private static void renderMobSpawnOverlay(Entity entity) {
private static void renderMobSpawnOverlay(Entity entity, int intOffsetX, int intOffsetY, int intOffsetZ) {
if (mobOverlay == 0) {
if (mobSpawnCache != null) {
mobSpawnCache = null;
@@ -105,15 +117,17 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glLineWidth(1.5F);
GL11.glBegin(GL11.GL_LINES);
GL11.glColor4f(1, 0, 0, 1);
int curSpawnMode = 2;
World world = entity.worldObj;
int x1 = (int) entity.posX;
int z1 = (int) entity.posZ;
int y1 = (int) MathHelper.clip(entity.posY, 16, world.getHeight() - 16);
int x1 = (int) entity.posX - intOffsetX;
int z1 = (int) entity.posZ - intOffsetZ;
int y1 = (int) MathHelper.clip(entity.posY, 16, world.getHeight() - 16) - intOffsetY;
final Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_LINES);
tess.setColorOpaque(255, 0, 0);
for (int i = 0; i <= 32; i++) {
int x = x1 - 16 + i;
@@ -132,22 +146,22 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
if (spawnMode != curSpawnMode) {
if (spawnMode == 1) {
GL11.glColor4f(1, 1, 0, 1);
tess.setColorOpaque(255, 255, 0);
} else {
GL11.glColor4f(1, 0, 0, 1);
tess.setColorOpaque(255, 0, 0);
}
curSpawnMode = spawnMode;
}
GL11.glVertex3d(x, y + 0.02, z);
GL11.glVertex3d(x + 1, y + 0.02, z + 1);
GL11.glVertex3d(x + 1, y + 0.02, z);
GL11.glVertex3d(x, y + 0.02, z + 1);
tess.addVertex(x, y + 0.02, z);
tess.addVertex(x + 1, y + 0.02, z + 1);
tess.addVertex(x + 1, y + 0.02, z);
tess.addVertex(x, y + 0.02, z + 1);
}
}
}
GL11.glEnd();
tess.draw();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
@@ -157,8 +171,8 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
private static final AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(0, 0, 0, 0, 0, 0);
private static byte getSpawnMode(Chunk chunk, int x, int y, int z) {
if (!SpawnerAnimals.canCreatureTypeSpawnAtLocation(EnumCreatureType.monster, chunk.worldObj, x, y, z) ||
chunk.getSavedLightValue(EnumSkyBlock.Block, x & 15, y, z & 15) >= 8) {
if (chunk.getSavedLightValue(EnumSkyBlock.Block, x & 15, y, z & 15) >= 8
|| !SpawnerAnimals.canCreatureTypeSpawnAtLocation(EnumCreatureType.monster, chunk.worldObj, x, y, z)) {
return 0;
}
@@ -168,16 +182,16 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
aabb.maxY = y + 1.8;
aabb.minZ = z + 0.2;
aabb.maxZ = z + 0.8;
if (!chunk.worldObj.getCollidingBoundingBoxes(dummyEntity, aabb).isEmpty() || chunk.worldObj.isAnyLiquid(aabb)) {
if (!chunk.worldObj.getCollidingBoundingBoxes(dummyEntity, aabb).isEmpty()
|| chunk.worldObj.isAnyLiquid(aabb)) {
return 0;
}
return (byte) (chunk.getSavedLightValue(EnumSkyBlock.Sky, x & 15, y, z & 15) >= 8 ? 1 : 2);
}
private static void renderChunkBounds(Entity entity) {
if (chunkOverlay == 0)
return;
private static void renderChunkBounds(Entity entity, int intOffsetX, int intOffsetY, int intOffsetZ) {
if (chunkOverlay == 0) return;
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
@@ -186,136 +200,161 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glLineWidth(1.5F);
GL11.glBegin(GL11.GL_LINES);
for (int cx = -4; cx <= 4; cx++)
for (int cz = -4; cz <= 4; cz++) {
double x1 = (entity.chunkCoordX + cx) << 4;
double z1 = (entity.chunkCoordZ + cz) << 4;
double x2 = x1 + 16;
double z2 = z1 + 16;
for (int cx = -4; cx <= 4; cx++) for (int cz = -4; cz <= 4; cz++) {
double x1 = ((entity.chunkCoordX + cx) << 4) - intOffsetX;
double z1 = ((entity.chunkCoordZ + cz) << 4) - intOffsetZ;
double x2 = x1 + 16;
double z2 = z1 + 16;
double dy = 128;
double y1 = Math.floor(entity.posY - dy / 2);
double y2 = y1 + dy;
if (y1 < 0) {
y1 = 0;
y2 = dy;
}
double dy = 128;
double y1 = Math.floor(entity.posY - dy / 2);
double y2 = y1 + dy;
if (y1 < 0) {
y1 = 0;
y2 = dy;
}
if (y1 > entity.worldObj.getHeight()) {
y2 = entity.worldObj.getHeight();
y1 = y2 - dy;
}
if (y1 > entity.worldObj.getHeight()) {
y2 = entity.worldObj.getHeight();
y1 = y2 - dy;
}
double dist = Math.pow(1.5, -(cx * cx + cz * cz));
y1 -= intOffsetY;
y2 -= intOffsetY;
GL11.glColor4d(0.9, 0, 0, dist);
if (cx >= 0 && cz >= 0) {
GL11.glVertex3d(x2, y1, z2);
GL11.glVertex3d(x2, y2, z2);
}
if (cx >= 0 && cz <= 0) {
GL11.glVertex3d(x2, y1, z1);
GL11.glVertex3d(x2, y2, z1);
}
if (cx <= 0 && cz >= 0) {
GL11.glVertex3d(x1, y1, z2);
GL11.glVertex3d(x1, y2, z2);
}
if (cx <= 0 && cz <= 0) {
GL11.glVertex3d(x1, y1, z1);
GL11.glVertex3d(x1, y2, z1);
}
double dist = Math.pow(1.5, -(cx * cx + cz * cz));
if (cx == 0 && cz == 0) {
if (chunkOverlay == 2) {
dy = 32;
y1 = Math.floor(entity.posY - dy / 2);
y2 = y1 + dy;
if (y1 < 0) {
y1 = 0;
y2 = dy;
GL11.glColor4d(0.9, 0, 0, dist);
if (cx >= 0 && cz >= 0) {
GL11.glVertex3d(x2, y1, z2);
GL11.glVertex3d(x2, y2, z2);
}
if (cx >= 0 && cz <= 0) {
GL11.glVertex3d(x2, y1, z1);
GL11.glVertex3d(x2, y2, z1);
}
if (cx <= 0 && cz >= 0) {
GL11.glVertex3d(x1, y1, z2);
GL11.glVertex3d(x1, y2, z2);
}
if (cx <= 0 && cz <= 0) {
GL11.glVertex3d(x1, y1, z1);
GL11.glVertex3d(x1, y2, z1);
}
if (cx == 0 && cz == 0) {
if (chunkOverlay == 2) {
dy = 32;
y1 = Math.floor(entity.posY - dy / 2);
y2 = y1 + dy;
if (y1 < 0) {
y1 = 0;
y2 = dy;
}
if (y1 > entity.worldObj.getHeight()) {
y2 = entity.worldObj.getHeight();
y1 = y2 - dy;
}
y1 -= intOffsetY;
y2 -= intOffsetY;
GL11.glColor4d(0, 0.9, 0, 0.4);
for (double y = (int) y1; y <= y2; y++) {
GL11.glVertex3d(x2, y, z1);
GL11.glVertex3d(x2, y, z2);
GL11.glVertex3d(x1, y, z1);
GL11.glVertex3d(x1, y, z2);
GL11.glVertex3d(x1, y, z2);
GL11.glVertex3d(x2, y, z2);
GL11.glVertex3d(x1, y, z1);
GL11.glVertex3d(x2, y, z1);
}
for (double h = 1; h <= 15; h++) {
GL11.glVertex3d(x1 + h, y1, z1);
GL11.glVertex3d(x1 + h, y2, z1);
GL11.glVertex3d(x1 + h, y1, z2);
GL11.glVertex3d(x1 + h, y2, z2);
GL11.glVertex3d(x1, y1, z1 + h);
GL11.glVertex3d(x1, y2, z1 + h);
GL11.glVertex3d(x2, y1, z1 + h);
GL11.glVertex3d(x2, y2, z1 + h);
}
} else if (chunkOverlay == 3) {
if (!hasOregenPatternBeenSet) {
try {
oregenPatternName = ((Enum<?>) Class.forName("gregtech.common.GT_Worldgenerator")
.getDeclaredField("oregenPattern").get(null)).name();
} catch (Exception ignored) {
oregenPatternName = "AXISSYMMETRICAL";
}
if (y1 > entity.worldObj.getHeight()) {
y2 = entity.worldObj.getHeight();
y1 = y2 - dy;
}
GL11.glColor4d(0, 0.9, 0, 0.4);
for (double y = (int) y1; y <= y2; y++) {
GL11.glVertex3d(x2, y, z1);
GL11.glVertex3d(x2, y, z2);
GL11.glVertex3d(x1, y, z1);
GL11.glVertex3d(x1, y, z2);
GL11.glVertex3d(x1, y, z2);
GL11.glVertex3d(x2, y, z2);
GL11.glVertex3d(x1, y, z1);
GL11.glVertex3d(x2, y, z1);
}
for (double h = 1; h <= 15; h++) {
GL11.glVertex3d(x1 + h, y1, z1);
GL11.glVertex3d(x1 + h, y2, z1);
GL11.glVertex3d(x1 + h, y1, z2);
GL11.glVertex3d(x1 + h, y2, z2);
GL11.glVertex3d(x1, y1, z1 + h);
GL11.glVertex3d(x1, y2, z1 + h);
GL11.glVertex3d(x2, y1, z1 + h);
GL11.glVertex3d(x2, y2, z1 + h);
}
} else if (chunkOverlay == 3) {
int gx1 = ((entity.chunkCoordX < 0 ? entity.chunkCoordX - 3 : entity.chunkCoordX) / 3 * 3) << 4;
int gz1 = ((entity.chunkCoordZ < 0 ? entity.chunkCoordZ - 3 : entity.chunkCoordZ) / 3 * 3) << 4;
hasOregenPatternBeenSet = true;
}
int gx1;
int gz1;
if (oregenPatternName.equals("EQUAL_SPACING")) {
// gt oregen uses new regular pattern
gx1 = ((Math.floorDiv(entity.chunkCoordX, 3) * 3) << 4) - intOffsetX;
gz1 = ((Math.floorDiv(entity.chunkCoordZ, 3) * 3) << 4) - intOffsetZ;
} else {
// gt oregen uses old bugged pattern
gx1 = (((entity.chunkCoordX < 0 ? entity.chunkCoordX - 3 : entity.chunkCoordX) / 3 * 3) << 4)
- intOffsetX;
gz1 = (((entity.chunkCoordZ < 0 ? entity.chunkCoordZ - 3 : entity.chunkCoordZ) / 3 * 3) << 4)
- intOffsetZ;
if (entity.chunkCoordX < 0) {
gx1 += 16;
}
if (entity.chunkCoordZ < 0) {
gz1 += 16;
}
int gx2 = gx1 + 48;
int gz2 = gz1 + 48;
GL11.glColor4d(0, 0.9, 0, 0.4);
for (double y = (int) y1; y <= y2; y++) {
GL11.glVertex3d(gx2, y, gz1);
GL11.glVertex3d(gx2, y, gz2);
GL11.glVertex3d(gx1, y, gz1);
GL11.glVertex3d(gx1, y, gz2);
GL11.glVertex3d(gx1, y, gz2);
GL11.glVertex3d(gx2, y, gz2);
GL11.glVertex3d(gx1, y, gz1);
GL11.glVertex3d(gx2, y, gz1);
}
for (double h = 4; h <= 44; h += 4) {
if (h % 16 == 0) {
continue;
}
GL11.glVertex3d(gx1 + h, y1, gz1);
GL11.glVertex3d(gx1 + h, y2, gz1);
GL11.glVertex3d(gx1 + h, y1, gz2);
GL11.glVertex3d(gx1 + h, y2, gz2);
GL11.glVertex3d(gx1, y1, gz1 + h);
GL11.glVertex3d(gx1, y2, gz1 + h);
GL11.glVertex3d(gx2, y1, gz1 + h);
GL11.glVertex3d(gx2, y2, gz1 + h);
}
GL11.glColor4d(0, 0, 0.9, 0.4);
gx1 += 23;
gz1 += 23;
gx2 = gx1 + 1;
gz2 = gz1 + 1;
GL11.glVertex3d(gx1, y1, gz1);
GL11.glVertex3d(gx1, y2, gz1);
GL11.glVertex3d(gx2, y1, gz1);
GL11.glVertex3d(gx2, y2, gz1);
GL11.glVertex3d(gx1, y1, gz2);
GL11.glVertex3d(gx1, y2, gz2);
GL11.glVertex3d(gx2, y1, gz2);
GL11.glVertex3d(gx2, y2, gz2);
}
int gx2 = gx1 + 48;
int gz2 = gz1 + 48;
GL11.glColor4d(0, 0.9, 0, 0.4);
for (double y = (int) y1; y <= y2; y++) {
GL11.glVertex3d(gx2, y, gz1);
GL11.glVertex3d(gx2, y, gz2);
GL11.glVertex3d(gx1, y, gz1);
GL11.glVertex3d(gx1, y, gz2);
GL11.glVertex3d(gx1, y, gz2);
GL11.glVertex3d(gx2, y, gz2);
GL11.glVertex3d(gx1, y, gz1);
GL11.glVertex3d(gx2, y, gz1);
}
for (double h = 4; h <= 44; h += 4) {
if (h % 16 == 0) {
continue;
}
GL11.glVertex3d(gx1 + h, y1, gz1);
GL11.glVertex3d(gx1 + h, y2, gz1);
GL11.glVertex3d(gx1 + h, y1, gz2);
GL11.glVertex3d(gx1 + h, y2, gz2);
GL11.glVertex3d(gx1, y1, gz1 + h);
GL11.glVertex3d(gx1, y2, gz1 + h);
GL11.glVertex3d(gx2, y1, gz1 + h);
GL11.glVertex3d(gx2, y2, gz1 + h);
}
GL11.glColor4d(0, 0, 0.9, 0.4);
gx1 += 23;
gz1 += 23;
gx2 = gx1 + 1;
gz2 = gz1 + 1;
GL11.glVertex3d(gx1, y1, gz1);
GL11.glVertex3d(gx1, y2, gz1);
GL11.glVertex3d(gx2, y1, gz1);
GL11.glVertex3d(gx2, y2, gz1);
GL11.glVertex3d(gx1, y1, gz2);
GL11.glVertex3d(gx1, y2, gz2);
GL11.glVertex3d(gx2, y1, gz2);
GL11.glVertex3d(gx2, y2, gz2);
}
}
}
GL11.glEnd();
GL11.glEnable(GL11.GL_LIGHTING);
+113 -61
View File
@@ -1,5 +1,20 @@
package codechicken.nei.api;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import org.lwjgl.input.Keyboard;
import com.google.common.collect.Sets;
import codechicken.nei.BookmarkContainerInfo;
import codechicken.nei.ItemList;
import codechicken.nei.ItemSorter;
import codechicken.nei.ItemStackSet;
@@ -24,24 +39,13 @@ import codechicken.nei.recipe.IUsageHandler;
import codechicken.nei.recipe.RecipeCatalysts;
import codechicken.nei.recipe.RecipeInfo;
import codechicken.nei.recipe.StackInfo;
import net.minecraft.block.Block;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import org.lwjgl.input.Keyboard;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* This is the main class that handles item property configuration.
* WARNING: DO NOT access this class until the world has been loaded
* These methods should be called from INEIConfig implementors
* This is the main class that handles item property configuration. WARNING: DO NOT access this class until the world
* has been loaded These methods should be called from INEIConfig implementors
*/
public class API
{
public class API {
/**
* Register a new Crafting Recipe handler;
*
@@ -64,8 +68,7 @@ public class API
* Add a gui to the default overlay renderer with the default position
*
* @param classz The class of your gui
* @param ident The identification string, currently
* {crafting, crafting2x2, smelting, fuel, brewing}
* @param ident The identification string, currently {crafting, crafting2x2, smelting, fuel, brewing}
*/
public static void registerGuiOverlay(Class<? extends GuiContainer> classz, String ident) {
registerGuiOverlay(classz, ident, 5, 11);
@@ -75,8 +78,7 @@ public class API
* Add a gui to the default overlay renderer with an offset
*
* @param classz The class of your gui
* @param ident The identification string, currently
* {crafting, crafting2x2, smelting, fuel, brewing}
* @param ident The identification string, currently {crafting, crafting2x2, smelting, fuel, brewing}
* @param x x-offset
* @param y y-offset
*/
@@ -88,11 +90,11 @@ public class API
* Add a gui to the default overlay renderer
*
* @param classz The class of your gui
* @param ident The identification string, currently
* {crafting, crafting2x2, smelting, fuel, brewing}
* @param ident The identification string, currently {crafting, crafting2x2, smelting, fuel, brewing}
* @param positioner A Stack Repositioner for moving the items to the right place
*/
public static void registerGuiOverlay(Class<? extends GuiContainer> classz, String ident, IStackPositioner positioner) {
public static void registerGuiOverlay(Class<? extends GuiContainer> classz, String ident,
IStackPositioner positioner) {
RecipeInfo.registerGuiOverlay(classz, ident, positioner);
}
@@ -101,12 +103,22 @@ public class API
* @param handler The handler to register
* @param ident The recipe identification string
*/
public static void registerGuiOverlayHandler(Class<? extends GuiContainer> classz, IOverlayHandler handler, String ident) {
public static void registerGuiOverlayHandler(Class<? extends GuiContainer> classz, IOverlayHandler handler,
String ident) {
RecipeInfo.registerOverlayHandler(classz, handler, ident);
}
/**
* Set the offset to be added to items to translate them into recipe coords on the actual gui, default is 5, 11. Primarily RecipeTransferRects
* @param classz The class of your gui
* @param ident The recipe identification string
*/
public static boolean hasGuiOverlayHandler(Class<? extends GuiContainer> classz, String ident) {
return RecipeInfo.hasOverlayHandler(classz, ident);
}
/**
* Set the offset to be added to items to translate them into recipe coords on the actual gui, default is 5, 11.
* Primarily RecipeTransferRects
*
* @param classz The class of your gui
* @param x
@@ -126,43 +138,52 @@ public class API
}
/**
* Hide an item from the item panel
* Damage values of OreDictionary.WILDCARD_VALUE and ItemStackMap.WILDCARD_TAG tags function as wildcards for their respective variables
* Hide an item from the item panel Damage values of OreDictionary.WILDCARD_VALUE and ItemStackMap.WILDCARD_TAG tags
* function as wildcards for their respective variables
*/
public static void hideItem(ItemStack item) {
ItemInfo.hiddenItems.add(item);
LayoutManager.markItemsDirty();
if (!ItemInfo.hiddenItems.contains(item)) {
ItemInfo.hiddenItems.add(item);
LayoutManager.markItemsDirty();
}
}
/**
* Add or replace the name normally shown on the item tooltip
*/
public static void setOverrideName(ItemStack item, String name) {
ItemInfo.nameOverrides.put(item, name);
LayoutManager.markItemsDirty();
if (!name.equals(ItemInfo.nameOverrides.get(item))) {
ItemInfo.nameOverrides.put(item, name);
LayoutManager.markItemsDirty();
}
}
/**
* Adds an item to the item panel. Any items added using this function will override the default search pattern.
*
* @param item an item with data
*/
public static void addItemListEntry(ItemStack item) {
ItemInfo.itemOverrides.put(item.getItem(), item);
LayoutManager.markItemsDirty();
if (!ItemInfo.itemOverrides.containsEntry(item.getItem(), item)) {
ItemInfo.itemOverrides.put(item.getItem(), item);
LayoutManager.markItemsDirty();
}
}
/**
* Sets the item variants to appear in the item panel, overriding the default search pattern for a given item
*/
public static void setItemListEntries(Item item, Iterable<ItemStack> items) {
if(items == null)
items = Collections.emptyList();
ItemInfo.itemOverrides.replaceValues(item, items);
LayoutManager.markItemsDirty();
if (items == null) items = Collections.emptyList();
if (!Sets.newHashSet(items).equals(Sets.newHashSet(ItemInfo.itemOverrides.get(item)))) {
ItemInfo.itemOverrides.replaceValues(item, items);
LayoutManager.markItemsDirty();
}
}
/**
* Add a custom KeyBinding to be configured in the Controls menu.
*
* @param ident An identifier for your key, eg "shoot"
* @param defaultKey The default value, commonly obtained from {@link Keyboard}
*/
@@ -172,12 +193,24 @@ public class API
addOption(new OptionKeyBind(ident));
}
/**
* Add a custom KeyBinding to be configured in the Controls menu.
*
* @param ident An identifier for your key, eg "shoot"
* @param defaultKey The default value, commonly obtained from {@link Keyboard}
*/
public static void addHashBind(String ident, int defaultKey) {
NEIClientConfig.setDefaultKeyBinding(ident, defaultKey);
addOption(new OptionKeyBind(ident, true));
}
public static void addOption(Option option) {
NEIClientConfig.getOptionList().addOption(option);
}
/**
* Add a new Layout Style for the NEI interface
*
* @param styleID The Unique ID to be used for storing your style in the config and cycling through avaliable styles
* @param style The style to add.
*/
@@ -187,6 +220,7 @@ public class API
/**
* Registers a new Infinite Item Handler.
*
* @param handler The handler to be registered.
*/
public static void addInfiniteItemHandler(IInfiniteItemHandler handler) {
@@ -195,6 +229,7 @@ public class API
/**
* Registers a new Infinite Item Handler.
*
* @param block The block to handle, null for all.
* @param handler The handler to be registered.
*/
@@ -204,6 +239,7 @@ public class API
/**
* Tells NEI not to perform any Fast Transfer operations on slots of a particular class
*
* @param slotClass The class of slot to be exempted
*/
public static void addFastTransferExemptSlot(Class<? extends Slot> slotClass) {
@@ -212,8 +248,10 @@ public class API
/**
* Register a new text handler for the block highlight tooltip with a layout specification (HEADER, BODY or FOOTER).
*
* @param handler The handler to be registered.
* @param layout A HUDAugmenterRegistry.Layout entry. HEADER is displayed before BODY which is displayed before FOOTER.
* @param layout A HUDAugmenterRegistry.Layout entry. HEADER is displayed before BODY which is displayed before
* FOOTER.
*/
public static void registerHighlightHandler(IHighlightHandler handler, ItemInfo.Layout... layout) {
ItemInfo.registerHighlightHandler(handler, layout);
@@ -221,6 +259,7 @@ public class API
/**
* Register a mode handler for overriding NEI recipe/utility/cheat mode settings.
*
* @param handler The handler to be registered.
*/
public static void registerModeHandler(INEIModeHandler handler) {
@@ -229,6 +268,7 @@ public class API
/**
* Register a filter provider for the item panel.
*
* @param filterProvider The filter provider to be registered.
*/
public static void addItemFilter(ItemFilterProvider filterProvider) {
@@ -239,7 +279,8 @@ public class API
/**
* Adds a new tag to the item subset dropdown.
* @param name The fully qualified name, Eg Blocks.MobSpawners. NOT case sensitive
*
* @param name The fully qualified name, Eg Blocks.MobSpawners. NOT case sensitive
* @param filter A filter for matching items that fit in this subset
*/
public static void addSubset(String name, ItemFilter filter) {
@@ -248,13 +289,13 @@ public class API
/**
* Adds a new tag to the item subset dropdown.
* @param name The fully qualified name, Eg Blocks.MobSpawners. NOT case sensitive
*
* @param name The fully qualified name, Eg Blocks.MobSpawners. NOT case sensitive
* @param items An iterable of itemstacks to be added as a subset
*/
public static void addSubset(String name, Iterable<ItemStack> items) {
ItemStackSet filter = new ItemStackSet();
for(ItemStack item : items)
filter.add(item);
for (ItemStack item : items) filter.add(item);
addSubset(new SubsetTag(name, filter));
}
@@ -274,32 +315,39 @@ public class API
/**
* Adds a new sorting option to the item panel sort menu
* @param name A unique id for this sort option. Will be used in the config for saving and translated in the options gui. Note that if the translation key name.tip exists, it will be used for a tooltip
*
* @param name A unique id for this sort option. Will be used in the config for saving and translated in the options
* gui. Note that if the translation key name.tip exists, it will be used for a tooltip
*/
public static void addSortOption(String name, Comparator<ItemStack> comparator) {
ItemSorter.add(name, comparator);
}
/**
* Adds an additional item list entry for an item, sorted after the rest of the items are found through the normal process
* @param item The item to add the variant for
* Adds an additional item list entry for an item, sorted after the rest of the items are found through the normal
* process
*
* @param item The item to add the variant for
* @param variant The stack to appear in the item panel
*/
public static void addItemVariant(Item item, ItemStack variant) {
ItemInfo.itemVariants.put(item, variant);
LayoutManager.markItemsDirty();
if (!ItemInfo.itemVariants.containsEntry(item, variant)) {
ItemInfo.itemVariants.put(item, variant);
LayoutManager.markItemsDirty();
}
}
public static void registerStackStringifyHandler(IStackStringifyHandler handler)
{
public static void registerStackStringifyHandler(IStackStringifyHandler handler) {
StackInfo.stackStringifyHandlers.add(handler);
}
/**
* Adds an association between an ingredient and what it can craft. (i.e. Furnace ItemStack -> Smelting and Fuel Recipes)
* Allows players to see what ingredient they need to craft in order to make recipes from a recipe category.
* @param stack the ingredient that can craft recipes (like a furnace or crafting table)
* @param handler the recipe category handled by the ingredient
* Adds an association between an ingredient and what it can craft. (i.e. Furnace ItemStack -> Smelting and Fuel
* Recipes) Allows players to see what ingredient they need to craft in order to make recipes from a recipe
* category.
*
* @param stack the ingredient that can craft recipes (like a furnace or crafting table)
* @param handler the recipe category handled by the ingredient
* @param priority higher priority comes first, default to 0
*/
public static void addRecipeCatalyst(ItemStack stack, IRecipeHandler handler, int priority) {
@@ -315,11 +363,13 @@ public class API
}
/**
* Adds an association between an ingredient and what it can craft. (i.e. Furnace ItemStack -> Smelting and Fuel Recipes)
* Allows players to see what ingredient they need to craft in order to make recipes from a recipe category.
* @param stack the ingredient that can craft recipes (like a furnace or crafting table)
* Adds an association between an ingredient and what it can craft. (i.e. Furnace ItemStack -> Smelting and Fuel
* Recipes) Allows players to see what ingredient they need to craft in order to make recipes from a recipe
* category.
*
* @param stack the ingredient that can craft recipes (like a furnace or crafting table)
* @param handlerID recipe category identifier (see also {@link RecipeCatalysts#getRecipeID(IRecipeHandler)})
* @param priority higher priority comes first, default to 0
* @param priority higher priority comes first, default to 0
*/
public static void addRecipeCatalyst(ItemStack stack, String handlerID, int priority) {
RecipeCatalysts.addRecipeCatalyst(handlerID, new CatalystInfo(stack, priority));
@@ -341,6 +391,11 @@ public class API
RecipeCatalysts.removeRecipeCatalyst(handlerID, stack);
}
public static void registerBookmarkContainerHandler(Class<? extends GuiContainer> gui,
IBookmarkContainerHandler handler) {
BookmarkContainerInfo.registerBookmarkContainerHandler(gui, handler);
}
@Deprecated
public static void addRecipeCatalyst(List<ItemStack> stacks, IRecipeHandler handler) {
for (ItemStack stack : stacks) {
@@ -356,11 +411,8 @@ public class API
}
@Deprecated
public static void addRecipeCatalyst(ItemStack stack, Class<? extends IRecipeHandler> handler) {
}
public static void addRecipeCatalyst(ItemStack stack, Class<? extends IRecipeHandler> handler) {}
@Deprecated
public static void addRecipeCatalyst(List<ItemStack> stacks, Class<? extends IRecipeHandler> handler) {
}
public static void addRecipeCatalyst(List<ItemStack> stacks, Class<? extends IRecipeHandler> handler) {}
}
@@ -1,44 +1,42 @@
package codechicken.nei.api;
import codechicken.nei.PositionedStack;
import codechicken.nei.guihook.GuiContainerManager;
import net.minecraft.inventory.Slot;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
public class DefaultOverlayRenderer implements IRecipeOverlayRenderer
{
public DefaultOverlayRenderer(List<PositionedStack> ai, IStackPositioner positioner)
{
import net.minecraft.inventory.Slot;
import org.lwjgl.opengl.GL11;
import codechicken.nei.PositionedStack;
import codechicken.nei.guihook.GuiContainerManager;
public class DefaultOverlayRenderer implements IRecipeOverlayRenderer {
public DefaultOverlayRenderer(List<PositionedStack> ai, IStackPositioner positioner) {
positioner = this.positioner = positioner;
ingreds = new ArrayList<>();
for(PositionedStack stack : ai)
ingreds.add(stack.copy());
for (PositionedStack stack : ai) ingreds.add(stack.copy());
ingreds = positioner.positionStacks(ingreds);
}
@Override
public void renderOverlay(GuiContainerManager gui, Slot slot)
{
public void renderOverlay(GuiContainerManager gui, Slot slot) {
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(770, 1);
GL11.glColor4d(0.6, 0.6, 0.6, 0.7);
GuiContainerManager.setColouredItemRender(true);
for(PositionedStack stack : ingreds)
{
if(stack.relx == slot.xDisplayPosition && stack.rely == slot.yDisplayPosition)
for (PositionedStack stack : ingreds) {
if (stack.relx == slot.xDisplayPosition && stack.rely == slot.yDisplayPosition)
GuiContainerManager.drawItem(stack.relx, stack.rely, stack.item);
}
GuiContainerManager.setColouredItemRender(false);
GL11.glColor4f(1, 1, 1, 1);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_LIGHTING);
}
final IStackPositioner positioner;
ArrayList<PositionedStack> ingreds;
}
+41 -8
View File
@@ -1,30 +1,41 @@
package codechicken.nei.api;
import codechicken.nei.NEIChestGuiHandler;
import codechicken.nei.NEICreativeGuiHandler;
import codechicken.nei.NEIDummySlotHandler;
import codechicken.nei.recipe.GuiRecipeCatalyst;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import codechicken.lib.vec.Rectangle4i;
import codechicken.nei.NEIChestGuiHandler;
import codechicken.nei.NEICreativeGuiHandler;
import codechicken.nei.NEIDummySlotHandler;
import codechicken.nei.NEIPotionGuiHandler;
import codechicken.nei.recipe.CheatItemHandler;
import codechicken.nei.recipe.FillFluidContainerHandler;
import codechicken.nei.recipe.GuiRecipeCatalyst;
import codechicken.nei.recipe.SearchInputDropHandler;
public class GuiInfo {
public static final LinkedList<INEIGuiHandler> guiHandlers = new LinkedList<>();
public static final HashSet<Class<? extends GuiContainer>> customSlotGuis = new HashSet<>();
public static ReentrantReadWriteLock guiHandlersLock = new ReentrantReadWriteLock();
public static Lock writeLock = guiHandlersLock.writeLock();
public static Lock readLock = guiHandlersLock.readLock();
public static void load() {
API.registerNEIGuiHandler(new NEICreativeGuiHandler());
API.registerNEIGuiHandler(new NEIChestGuiHandler());
API.registerNEIGuiHandler(new NEIDummySlotHandler());
API.registerNEIGuiHandler(new GuiRecipeCatalyst(null));
API.registerNEIGuiHandler(new SearchInputDropHandler());
API.registerNEIGuiHandler(new FillFluidContainerHandler());
API.registerNEIGuiHandler(new CheatItemHandler());
API.registerNEIGuiHandler(new NEIPotionGuiHandler());
customSlotGuis.add(GuiContainerCreative.class);
}
@@ -40,4 +51,26 @@ public class GuiInfo {
public static boolean hasCustomSlots(GuiContainer gui) {
return customSlotGuis.contains(gui.getClass());
}
public static boolean hideItemPanelSlot(GuiContainer gui, Rectangle4i rect) {
try {
readLock.lock();
if (guiHandlers.stream()
.anyMatch(handler -> handler.hideItemPanelSlot(gui, rect.x, rect.y, rect.w, rect.h))) {
return true;
}
} finally {
readLock.unlock();
}
for (Object item : gui.buttonList) {
GuiButton button = (GuiButton) item;
if ((new Rectangle4i(button.xPosition, button.yPosition, button.width, button.height)).intersects(rect)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,11 @@
package codechicken.nei.api;
import java.util.ArrayList;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
public interface IBookmarkContainerHandler {
void pullBookmarkItemsFromContainer(GuiContainer guiContainer, ArrayList<ItemStack> realItems);
}
@@ -1,13 +1,14 @@
package codechicken.nei.api;
/**
* An nei configuration entry point should implement this class and have name "NEI<someting>Config"
* loadConfig will only be called when NEI is installed.
* An nei configuration entry point should implement this class and have name "NEI<someting>Config" loadConfig will only
* be called when NEI is installed.
*/
public interface IConfigureNEI
{
public interface IConfigureNEI {
public void loadConfig();
public String getName();
public String getVersion();
}
@@ -1,8 +1,13 @@
package codechicken.nei.api;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
public interface IGuiContainerOverlay
{
public GuiContainer getFirstScreen();
public interface IGuiContainerOverlay {
GuiContainer getFirstScreen();
default GuiScreen getFirstScreenGeneral() {
return getFirstScreen();
}
}
@@ -1,15 +1,16 @@
package codechicken.nei.api;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import java.util.List;
public interface IHighlightHandler {
public interface IHighlightHandler
{
public ItemStack identifyHighlight(World world, EntityPlayer player, MovingObjectPosition mop);
public List<String> handleTextData(ItemStack itemStack, World world, EntityPlayer player, MovingObjectPosition mop, List<String> currenttip, ItemInfo.Layout layout);
public List<String> handleTextData(ItemStack itemStack, World world, EntityPlayer player, MovingObjectPosition mop,
List<String> currenttip, ItemInfo.Layout layout);
}
@@ -3,14 +3,17 @@ package codechicken.nei.api;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
public interface IInfiniteItemHandler
{
public interface IInfiniteItemHandler {
void onPickup(ItemStack heldItem);
void onPlaceInfinite(ItemStack heldItem);
boolean canHandleItem(ItemStack stack);
boolean isItemInfinite(ItemStack stack);
public void replenishInfiniteStack(InventoryPlayer inventory, int slotNo);
public ItemStack getInfiniteItem(ItemStack typeStack);
}
@@ -1,20 +1,24 @@
package codechicken.nei.api;
import codechicken.nei.VisiblityData;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import codechicken.nei.VisiblityData;
/**
* Lets you just override those things you want to
*/
public class INEIGuiAdapter implements INEIGuiHandler
{
public class INEIGuiAdapter implements INEIGuiHandler {
static final Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
@Override
public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility)
{
public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) {
return currentVisibility;
}
@@ -24,20 +28,22 @@ public class INEIGuiAdapter implements INEIGuiHandler
}
@Override
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer gui)
{
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer gui) {
return null;
}
@Override
public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button)
{
public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) {
return false;
}
@Override
public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h)
{
return false;
public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) {
return false;
}
protected String formattingText(String displayName) {
return SPECIAL_REGEX_CHARS.matcher(EnumChatFormatting.getTextWithoutFormattingCodes(displayName))
.replaceAll("\\\\$0");
}
}
@@ -1,44 +1,49 @@
package codechicken.nei.api;
import codechicken.nei.VisiblityData;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.item.ItemStack;
import java.util.List;
import codechicken.nei.VisiblityData;
/**
* If this is implemented on a gui, it will be automatically registered
*/
public interface INEIGuiHandler
{
public interface INEIGuiHandler {
public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility);
/**
* NEI will give the specified item to the InventoryRange returned if the player's inventory is full.
* Should not return null, just an empty list
* NEI will give the specified item to the InventoryRange returned if the player's inventory is full. Should not
* return null, just an empty list
*/
public Iterable<Integer> getItemSpawnSlots(GuiContainer gui, ItemStack item);
/**
* @return A list of TaggedInventoryAreas that will be used with the savestates.
*/
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer gui);
/**
* Handles clicks while an itemstack has been dragged from the item panel. Use this to set configurable slots and the like.
* Changes made to the stackSize of the dragged stack will be kept
* @param gui The current gui instance
* @param mousex The x position of the mouse
* @param mousey The y position of the mouse
* Handles clicks while an itemstack has been dragged from the item panel. Use this to set configurable slots and
* the like. Changes made to the stackSize of the dragged stack will be kept
*
* @param gui The current gui instance
* @param mousex The x position of the mouse
* @param mousey The y position of the mouse
* @param draggedStack The stack being dragged from the item panel
* @param button The button presed
* @return True if the drag n drop was handled. False to resume processing through other routes. The held stack will be deleted if draggedStack.stackSize == 0
* @param button The button presed
* @return True if the drag n drop was handled. False to resume processing through other routes. The held stack will
* be deleted if draggedStack.stackSize == 0
*/
public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button);
/**
* Used to prevent the item panel from drawing on top of other gui elements.
* This function will also be called with a 1x1 size rectangle on the mouse position for determining if the given coordinate should override item panel functions such as scrolling
* Used to prevent the item panel from drawing on top of other gui elements. This function will also be called with
* a 1x1 size rectangle on the mouse position for determining if the given coordinate should override item panel
* functions such as scrolling
*
* @param x The x coordinate of the rectangle bounding the slot
* @param y The y coordinate of the rectangle bounding the slot
* @param w The w coordinate of the rectangle bounding the slot
@@ -1,6 +1,6 @@
package codechicken.nei.api;
public interface INEIModeHandler
{
public interface INEIModeHandler {
public boolean isModeValid(int mode);
}
@@ -1,9 +1,10 @@
package codechicken.nei.api;
import codechicken.nei.recipe.IRecipeHandler;
import net.minecraft.client.gui.inventory.GuiContainer;
public interface IOverlayHandler
{
public void overlayRecipe(GuiContainer firstGui, IRecipeHandler recipe, int recipeIndex, boolean shift);
import codechicken.nei.recipe.IRecipeHandler;
public interface IOverlayHandler {
void overlayRecipe(GuiContainer firstGui, IRecipeHandler recipe, int recipeIndex, boolean shift);
}
@@ -1,9 +1,10 @@
package codechicken.nei.api;
import codechicken.nei.guihook.GuiContainerManager;
import net.minecraft.inventory.Slot;
public interface IRecipeOverlayRenderer
{
import codechicken.nei.guihook.GuiContainerManager;
public interface IRecipeOverlayRenderer {
public void renderOverlay(GuiContainerManager gui, Slot slot);
}
@@ -1,14 +1,14 @@
package codechicken.nei.api;
import codechicken.nei.PositionedStack;
import java.util.ArrayList;
import codechicken.nei.PositionedStack;
/**
* For repositioning recipes in overlay renderers.
*
*
*/
public interface IStackPositioner
{
public interface IStackPositioner {
public ArrayList<PositionedStack> positionStacks(ArrayList<PositionedStack> ai);
}
@@ -1,16 +1,14 @@
package codechicken.nei.api;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import net.minecraft.item.ItemStack;
public interface IStackStringifyHandler
{
public interface IStackStringifyHandler {
public NBTTagCompound convertItemStackToNBT(ItemStack stack, boolean saveStackSize);
public ItemStack convertNBTToItemStack(NBTTagCompound nbtTag);
public FluidStack getFluid(ItemStack stack);
}
}
@@ -2,15 +2,16 @@ package codechicken.nei.api;
import net.minecraft.item.ItemStack;
public interface ItemFilter
{
public interface ItemFilter {
/**
* Provides an item filter. May be called from any thread. Returned filter should only reference objects with immutable state.
* Provides an item filter. May be called from any thread. Returned filter should only reference objects with
* immutable state.
*/
public static interface ItemFilterProvider
{
public static interface ItemFilterProvider {
public ItemFilter getFilter();
}
public boolean matches(ItemStack item);
}
}
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more