Compare commits

...
Author SHA1 Message Date
ABKQPO 65bca01f52 Leave a fluid alone when an air position is emptied 2026-09-11 10:17:00 +08:00
ABKQPO 6bc8cea2bf Roll a placement back to what was there rather than to air 2026-09-11 10:13:09 +08:00
ABKQPO 6209d67ba7 Default the fluid cost of a registration to one bucket 2026-09-11 10:01:36 +08:00
ABKQPO 7adaa4841d Place the fluid of a round that finished its structure in the same round 2026-09-11 09:55:22 +08:00
ABKQPO d7df0c0b5b Keep the priority of a registry entry in its name 2026-09-11 09:47:10 +08:00
ABKQPO 1632ad762a Name the fluid extractors after the item ones 2026-09-11 09:40:20 +08:00
ABKQPO 0edeef4f09 Drop the lang entry of the AE2FC fluid source that no longer exists 2026-09-11 09:17:34 +08:00
ABKQPO 51a85dfa1b Extract fluid containers from the same inventories as items 2026-09-11 08:51:36 +08:00
ABKQPO 98101c00aa Add fluid block autoplace with a pluggable fluid cost and source API
Water, lava and every Forge fluid block can now be placed by survival autoplace, paid for with fluid instead of with an item.

* Fluid costs are registered per block state, water and lava are registered by default, and a registration can ask for fluid even when the block also has an item form.
* A fluid is only placed once the rest of the structure is in place, so it cannot flow out of a half built multiblock, and only the fluid missing from a position is charged, so topping up a leak costs the difference instead of a whole bucket.
* The fluid comes from the player: their fluid containers, plus whatever mods contribute through the new fluid container extractor and fluid source provider registries.
* Existing structure definitions need no change, as ofBlock and the other block elements become fluid elements when the block has no item form.
2026-09-10 18:35:16 +08:00
Eldrinn Elantey d829ae466b Localize and unify missing block messages in autoplace (#70)
StructureLib built the missing block name on the server, where only
en_US is loaded, so players on dedicated servers saw English names in
chat. Send the item's lang key and let the client translate it. Stacks
whose name is not a plain key, GT meta items among them, keep the old
server side name.

Players also saw two shapes of the same message: a bracketed name with
rarity color and an item tooltip from two of the survivalPlaceBlocks
branches, a bare yellow name from the stack list branch. All three now
build the name the same way.
2026-09-09 09:21:27 +08:00
Martin Robertz 137f651486 update deps 2026-07-03 19:22:22 +02:00
attempt0andgithub-actions[bot] ff88cbf2d7 Read channel in getBlocksToPlace (#68)
## Summary
This causes inconsistency in the API and should be addressed. The
primary consumer of the API is NEI preview and the preview does show
wrong block with glass tier set, not sure if this is the cause
<img width="1088" height="491" alt="image"
src="https://github.com/user-attachments/assets/fff146d8-6d8e-44d9-842e-1677691271d2"
/>

## Checklist
- [ ] I have tested this PR in DevEnv
- [ ] I have tested this PR in Fullpack
- [x] This PR is in compliance with the [GTNH AI
Policy](https://github.com/GTNewHorizons/GTNH-Dev-Doc/blob/master/AI_POLICY.md)
- [ ] This PR requires another PR in order to merge

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-03 23:33:08 +08:00
DylanTaylor1 4922760b46 Change subchannel color to match tooltips (#67)
Changes subchannel color from orange to aqua to match tooltips from the
Construction Tooltips Overhaul
(https://github.com/GTNewHorizons/GT5-Unofficial/pull/7299)
2026-07-02 21:12:20 -04:00
Eldrinn-Elantey 45bd25401f Add confirmation step to Clear button in channel GUI (#66) 2026-06-21 16:57:58 +02:00
Dream Master 050f0b5a5c update+gradle+bs+deps 2026-06-19 15:34:27 +02:00
Nikolay S.andGlease 2c5fa02a9e Simple Cleanups (#61)
Cleans up the code a tiny bit, moving comments around, removing some
`@SuppressWarnings` and some unused code, and using modern Java
features.

These changes should require no modifications to any outside mods.

---------

Co-authored-by: Glease <4586901+Glease@users.noreply.github.com>
2026-06-19 15:31:17 +02:00
Yoshyandgithub-actions[bot] 287e8317c9 Add reject_continue to PlaceResult and make SKIP short-circuit in ofChain (#63)
ofChain survival placement had a bug where SKIP (returned when a block
already exists) would not stop the chain, causing fallback alternatives
to replace already valid blocks , for example:
<img width="436" height="477" alt="image"
src="https://github.com/user-attachments/assets/7ff3d6fa-de98-4716-823f-3ad2abab7394"
/>

SKIP now short-circuits the chain, remaining alternatives are skipped
because the position is already valid.
To keep correct behavior for elements without autobuild (which
previously returned SKIP as a "no implementation" signal), a new
REJECT_CONTINUE value is added, which: continues silently like SKIP (no
error, not counted) in the walker and in the chain tries the next
alternative like REJECT
Default survivalPlaceBlock and IStructureElementCheckOnly now return
REJECT_CONTINUE instead of SKIP for unhandled paths.

Tested this with the example above, and fixed the issue:
<img width="435" height="498" alt="image"
src="https://github.com/user-attachments/assets/d92bce4d-b5ad-4051-af79-ffd8c819f9f7"
/>
survival placement also still works:
<img width="1234" height="916" alt="image"
src="https://github.com/user-attachments/assets/632d5556-524d-4dc5-a7f5-75c859cb6b70"
/>

this should ideally merged before
https://github.com/GTNewHorizons/GT5-Unofficial/pull/6922 , to fix this
underlying bug, but if possible not be tagged without the other PR,
which would cause all NEI previews of multis with water to not show any
water anymore

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-06-06 18:10:11 +02:00
Luca 95d1533342 Add Context Parameter to get Description (#60)
Yes this is breaking, but only to the changes that where merged not even
24 hours ago.
2026-05-24 13:35:25 +08:00
Luca 19179ec894 improve description fallback (#59) 2026-05-23 19:42:15 +02:00
Luca d8b301457f Add getDescription() to IStructureElement (#57) 2026-05-23 09:42:20 +02:00
Martin Robertz 40edf05109 update+gradle+bs+deps 2026-04-03 22:32:39 +02:00
evgengoldwar 4e5a92aff7 Add more info (#56)
Fixing the issue where the ofBlock method does not show a hint about
which block cannot be placed.
<img width="942" height="261" alt="image"
src="https://github.com/user-attachments/assets/2162c68e-e7ef-4fa4-ab86-61321884bfe7"
/>
2026-03-26 15:23:20 +01:00
UltraProdigy a09e6058a9 Optimize Image & Workflow (#55) 2026-03-07 09:38:45 +01:00
danyadev e774dd5e10 optimize StructureDefinition.addShape (#54)
Before: 161ms of loading time
After: 60.7ms of loading time

An example with Forge of Gods
<img width="1917" height="513" alt="image"
src="https://github.com/user-attachments/assets/61e9b420-7cc2-4e76-89f3-864bd6d7a77f"
/>
<img width="1918" height="490" alt="image"
src="https://github.com/user-attachments/assets/5297956c-41c8-43f7-9451-e29e26609a7e"
/>
2026-03-01 13:03:05 +01:00
Martin Robertz 0866dbee98 fix 2026-01-05 22:05:18 +01:00
Martin Robertz 208f7ffc41 update deps+bs+gradle 2026-01-05 21:28:00 +01:00
Worive 88a6021546 Autocomplete channel name with tab (#53) 2026-01-05 10:21:14 +08:00
UltraProdigy a05267a566 Replace Dot Hints With Number Hints (#52)
As title says, makes the holograms much more readable.

Textures By: bapy_
Original PR By: kstvr32

Supercedes: https://github.com/GTNewHorizons/StructureLib/pull/32

Examples:
<img width="2534" height="1351" alt="image"
src="https://github.com/user-attachments/assets/c24f60b2-d654-4b15-b917-4003141a2b69"
/>
<img width="2538" height="1350" alt="image"
src="https://github.com/user-attachments/assets/a5ca3f42-ca96-4675-8e80-c89fba359fbf"
/>
2025-12-17 08:04:19 +01:00
Wilhelm Schuster dd3413dcaa Don't enable buttons in channel configuration when channel key is empty (#51)
The channel configuration GUI would allow pressing the "Add" button even
though the channel key field was empty, leading to a crash.

fixes
https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/22838
2025-12-15 09:33:15 +08:00
Martin Robertz 34394ef8a5 update 2025-10-28 21:07:20 +01:00
RecursivePineapple 7c0d3f4bd6 Expose ability to iterate over structures (#49) 2025-10-28 12:52:40 +08:00
Martin Robertz cd4f3617be update 2025-09-20 15:44:09 +02:00
Wilhelm Schuster 256bc60d35 Fix crash trying to open Hologram Projector GUI on java 8 (#48) 2025-09-19 00:16:47 +08:00
Martin Robertz 70426ab7b3 update 2025-09-17 13:53:22 +02:00
Wilhelm Schuster 0030c02e9a Small improvements to the channel config GUI (#47) 2025-09-15 22:06:29 +02:00
Wilhelm Schuster 7382db1bbd Fix Hologram Projector Shift-Use opening both GUIs (#46) 2025-09-14 19:00:59 +02:00
Wilhelm Schuster b669cbecf1 Fix Hologram Projector config GUI not releasing cursor (#45) 2025-09-14 10:21:21 +02:00
Dream Master 6283931667 update 2025-08-04 10:28:35 +07:00
Abdiel Kavash 3b3bc4b9ad Add preset IAlignmentLimits constants. (#43)
Many multiblocks can only be placed or rotated in certain orientations.
This has been always done ad-hoc, with individual checks for each
controller. This is inconsistent and sometimes it results in bugs where
certain orientations are not allowed for no discernible reason; for
example
https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/14206.

This PR introduces a short list of named constants to
`IAlignmentLimits`, which describe common multiplboc orientations. These
are currently:

* `UNLIMITED`: Any orientation is allowed. Most multiblocks.
* `UPRIGHT`: The multiblock must be in an upright position, with the top
side facing up. Example: Distillation Tower, Ore Washing Plant.
* `NOT_UPSIDE_DOWN`: The multiblock can be in any orientation, except
for the top side facing directly downwards. This is currently only the
Large Heat Exchanger and Integrated Ore Factory.
* `FACING_UP`: The front of the controller must face up. Example:
Flotation Cell, XL Turbines.

Currently, these constants describe the allowed facings of *all* GT5U
multiblocks.

A multiblock can then simply return one of these constants from
`getInitialAlignmentLimits()` to describe its valid orientations,
instead of implementing the logic itself. This concentrates the code to
one place, improves readability, and fixes any bugs connected with these
checks being done wrong.

Of course, even though the list is currently complete, if any future
multiblock wants to implement its own strange restrictions on
orientation, it can still implement its own check instead of returning
one of the constants.

A follow-up PR to GT5U implements this for all multiblocks which
restrict valid orientations:
https://github.com/GTNewHorizons/GT5-Unofficial/pull/4595
2025-08-01 10:54:59 +07:00
Alexdoru bef4fdd949 Delete overkill mixin registration system (#44) 2025-07-14 04:31:17 +08:00
Martin Robertz 4a06c8f95b update 2025-06-19 21:09:58 +02:00
koolkrafter5 241bed1989 Update dev username (#41) 2025-06-16 10:53:32 +08:00
Martin Robertz f5594c25db update 2025-04-30 16:05:28 +02:00
Glease 7cda901ae5 add channel desc and channel indicator item (#39)
Add channel desc and channel indicator item. Its meaning and development
examples has been added to overview page in javadoc.
Also removes gt_no_hatch and show_error special button from GUI as they
are now a candidate in the dropdown menu.

one day we will move this to MUI2, but for now let's stick to existing
infra that is known to work



https://github.com/user-attachments/assets/814edbb6-c4b4-4309-8798-787d9ed1aeef

Note: channels in demo video are from GT5. if you boot the pack without
the modified gt5 you won't see most of the channels.

---------

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-04-30 15:55:19 +02:00
538459eab5 channel configure ui tweaks (#35)
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
Co-authored-by: Martin Robertz <dream-master@gmx.net>
Co-authored-by: Maya <10861407+serenibyss@users.noreply.github.com>
2025-03-11 09:41:57 -05:00
Maya 3a9ec8b6ac update 2025-03-10 16:27:58 -05:00
Glease 330a13271b fix unbreakable warded glass (#37)
fix
https://github.com/GTNewHorizons/GT-New-Horizons-Modpack/issues/18849

@Ruling-0 since your glass refactor is slightly related to this

---------

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2025-03-10 16:26:36 -05:00
glowredmanandGlease bf5dd5566b Add Localization (#36)
This adds some missing localizations for unlocalized names returned by
the ItemStack-insensitive version of `Item.getUnlocalizedName()`.
Relevant for the Item/Block stats introduced in
https://github.com/GTNewHorizons/Hodgepodge/pull/398.

---------

Co-authored-by: Glease <4586901+Glease@users.noreply.github.com>
2025-01-02 11:40:59 +08:00
Martin Robertz b9d0143245 update 2024-12-14 20:12:25 +01:00
43fc39c99b Add error hint when block is invalid (#31)
Co-authored-by: kstvr32 <kstvr32@gmail.com>
Co-authored-by: Martin Robertz <dream-master@gmx.net>
2024-12-14 19:13:34 +01:00
Lyft 6337536dc3 Send correct identifier when instrumenting (#34) 2024-11-19 10:20:47 +08:00
Lyft 9b96560119 Fix IStructureElementChain returning an invalid Iterable (#33) 2024-11-09 15:46:49 +01:00
Dream Master 3ce1c877e3 update 2024-08-07 15:42:01 +07:00
GleaseandDream Master 3d150d95cb customizable registries (#25)
* add a bit javadoc

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* customizable registries

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* add gui for customizing registries

* add a bit javadoc

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* spotless

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* remove debug statements

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* add notes on localization

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* update

* fix

* fix

---------

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
Co-authored-by: Dream Master <dream-master@gmx.net>
2024-08-07 15:37:30 +07:00
Dream Master 03e84e3d37 update 2024-07-10 11:12:56 +07:00
Jason Mitchell 547833bedb Bump NEI dep
Bump GTNHLib dep for CoordinatePacker

Bump deps
2024-07-09 09:39:45 -07:00
Jason Mitchell 61e0d4b7e7 Add basic BlockChangeNotifier & BlockChangeListener 2024-07-09 09:39:45 -07:00
Jason Mitchell 6867ed50e6 Add mixins 2024-07-09 09:39:45 -07:00
Jason Mitchell e7a47c199b Enable checkstyle 2024-07-09 09:39:45 -07:00
Jason Mitchell b2bc474382 Update BS, enable Jabel & Generic injection 2024-07-09 09:39:45 -07:00
Martin Robertz eef6baea4b update 2024-04-16 22:13:22 +02:00
Glease efd49701e1 add a new api to stack extractors
Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2024-04-16 17:32:31 +08:00
Raven Szewczyk a7f0d6be72 [ci skip] upgraded build system 2024-02-04 20:01:59 +00:00
Glease 0ff38c2da9 revise javadoc publish (#27)
* fix deprecation

* add cleanup
2024-01-09 22:52:41 +01:00
chochem 307bb1714c Fix broken mod (#26)
* clear out repositories

* update bs

* update deps

* spotless
2024-01-09 11:42:10 +08:00
Raven Szewczyk 7d8e6a0ea5 [ci skip] upgraded build system 2024-01-08 21:29:25 +00:00
Glease b6d2af2170 add new api to check for rotation/flip changes (#24)
* add new api to check for rotation/flip changes

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* add a bit javadoc

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

---------

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2023-09-13 14:29:39 +02:00
Glease 8309567076 fix cube faces rendering order (#22)
* fix cube faces rendering order

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* spotless

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

* address review

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>

---------

Signed-off-by: Glease <4586901+Glease@users.noreply.github.com>
2023-07-13 22:05:35 +02:00
kstvr32 23312198a6 Allow autoplace channels to work in survival mode (#20)
* allow autoplace channels to work in survival mode

* bump NEI dependency version
2023-05-04 17:40:03 +02:00
Glease fa5e2ae4ca flush buffer to ensure vertexes in same trig being drawn in same batch (#19)
* flush buffer to ensure vertexes in same trig being drawn in same batch

* off by one
2023-03-08 12:23:32 +01:00
Glease a8a1547845 remove unnecessary shim code for IMultiblockInfoContainer
nobody implement these in practice, so we should be safe
2023-02-28 12:37:18 +08:00
Raven Szewczyk 113e05b7e6 Java11 javadoc generator (#18) 2023-02-28 01:30:57 +08:00
Glease 080785ad05 spotless 2023-02-27 20:36:44 +08:00
Glease 6c14ca0a1d fix hologram rendering at large coordinates
Inspired by https://github.com/GTNewHorizons/NotEnoughItems/pull/353. Thanks @eigenraven!
2023-02-27 19:57:51 +08:00
111 changed files with 7572 additions and 1878 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
name: Optimize images
on:
pull_request:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
push:
branches: [ master, main, release/** ]
paths:
- "**/*.png"
jobs:
optimize-images:
uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/optimize-images.yml@master
secrets: inherit
-47
View File
@@ -1,47 +0,0 @@
# Simple workflow for deploying static content to GitHub Pages
name: Deploy static content to Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["gh-pages"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow one concurrent deployment
concurrency:
group: "pages"
cancel-in-progress: true
jobs:
# Single deploy job since we're just deploying
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Pages
uses: actions/configure-pages@v2
- name: Generate Index
shell: bash
run: |
find . -name javadoc -type d -print > index.txt
echo feature/doc >> index.txt
- name: Upload artifact
uses: actions/upload-pages-artifact@v1
with:
# Upload entire repository
path: '.'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v1
+43 -9
View File
@@ -5,8 +5,10 @@ on:
branches:
- master
- feature/doc
- '**/*-javadoc'
tags:
- '*'
delete:
permissions:
contents: write
@@ -14,19 +16,53 @@ permissions:
id-token: write
jobs:
javadoc:
prune:
if: github.event_name == 'delete'
concurrency: javadoc-publish
runs-on: ubuntu-latest
outputs:
result_hash: ${{ steps.deploy.outputs.hash }}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
fetch-depth: 0
ref: gh-pages
- name: Deploy 🚀
id: deploy
shell: bash
run: |
if git rm -r $TARGET_FOLDER ; then
echo Nothing to clean up
fi
find . -name javadoc -type d -print | sed 's#^\./\(.*\)/javadoc$#\1#' | sort --version-sort --reverse > index.txt
git add index.txt
git config user.name "${GITHUB_ACTOR}"
git config user.email "${GITHUB_ACTOR_ID}-${GITHUB_ACTOR}@users.noreply.github.com"
git commit -m "Clean up javadoc after ref $TARGET_FOLDER is deleted"
git push
echo "hash=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
env:
TARGET_FOLDER: ${{ github.ref_name }}
javadoc:
if: github.event_name == 'push'
concurrency: javadoc-publish
runs-on: ubuntu-latest
outputs:
result_hash: ${{ steps.deploy.outputs.hash }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-java@v2
- uses: actions/setup-java@v3
with:
java-version: 8
java-version: |
8
11
17
distribution: 'temurin'
cache: gradle
@@ -51,14 +87,12 @@ jobs:
echo Nothing to deploy
exit 0
fi
find . -name javadoc -type d -print | sed 's#^\./\(.*\)/javadoc$#\1#' > index.txt
find . -name javadoc -type d -print | sed 's#^\./\(.*\)/javadoc$#\1#' | sort --version-sort --reverse > index.txt
git add index.txt
git config user.name "${GITHUB_ACTOR}"
git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
git config user.email "${GITHUB_ACTOR_ID}-${GITHUB_ACTOR}@users.noreply.github.com"
git commit -m "Deploy javadoc from ref $TARGET_FOLDER"
git push
echo "::set-output name=hash::$(git rev-parse HEAD)"
echo "hash=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT
env:
TARGET_FOLDER: ${{ github.ref_name }}
COMMIT_AUTHOR: ${{ github.pusher.name }}
COMMIT_EMAIL: ${{ github.pusher.email }}
+1
View File
@@ -27,3 +27,4 @@ whitelist.json
*.iws
src/main/resources/mixins.*.json
*.bat
layout.json
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+2
View File
@@ -32,3 +32,5 @@ The project is developed using IDEA. Please manually configure the build to not
Due to me adding in ItemStackMap, which was derived from code from CodeChicken's LGPL mod NEI. This mod is effectively considered
licensed under LGPL in its entirety since commit ebef584b8c518f8202cfe0984fb28a6d23e52b3d or any squash commit containing it, e.g.
609e50428ee4e293f65f67f554a70b9fcfae97c4.
Note while the LICENSE.txt is added by a much later commit, all code on previous commits are covered by this as well.
+7 -1
View File
@@ -1,4 +1,10 @@
javadoc {
javadocTool = javaToolchains.javadocToolFor {
// Last version with frames, but it also has search
languageVersion = JavaLanguageVersion.of(25)
vendor = JvmVendorSpec.ADOPTIUM
}
inputs.file "src/main/javadoc/overview.html"
include "com/gtnewhorizon/structurelib/alignment/**"
@@ -12,7 +18,7 @@ javadoc {
options {
overview "src/main/javadoc/overview.html"
links 'https://docs.oracle.com/javase/8/docs/api/'
links 'https://docs.oracle.com/en/java/javase/25/docs/api/'
links 'https://skmedix.github.io/ForgeJavaDocs/javadoc/forge/1.7.10-10.13.4.1614/'
}
}
+2 -1259
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -1,9 +1,10 @@
// Add your dependencies here
dependencies {
api("com.github.GTNewHorizons:GTNHLib:0.0.10:dev")
runtimeOnly("com.github.GTNewHorizons:NotEnoughItems:2.3.25-GTNH:dev")
api("com.github.GTNewHorizons:GTNHLib:0.11.21:dev")
implementation("com.github.GTNewHorizons:NotEnoughItems:2.8.110-GTNH:dev")
testImplementation(platform('org.junit:junit-bom:5.9.2'))
testImplementation('org.junit.jupiter:junit-jupiter')
testRuntimeOnly ('org.junit.platform:junit-platform-launcher')
}
+207 -29
View File
@@ -1,60 +1,238 @@
# ExampleMod tag to use as Blowdryer (Spotless, etc.) settings version, leave empty to disable.
# LOCAL to test local config updates.
gtnh.settings.blowdryerTag = 0.2.0
# Human-readable mod name, available for mcmod.info population.
modName = StructureLib
# This is a case-sensitive string to identify your mod. Convention is to use lower case.
# Case-sensitive identifier string, available for mcmod.info population and used for automatic mixin JSON generation.
# Conventionally lowercase.
modId = structurelib
# Root package of the mod, used to find various classes in other properties,
# mcmod.info substitution, enabling assertions in run tasks, etc.
modGroup = com.gtnewhorizon.structurelib
# WHY is there no version field?
# The build script relies on git to provide a version via tags. It is super easy and will enable you to always know the
# code base or your binary. Check out this tutorial: https://blog.mattclemente.com/2017/10/13/versioning-with-git-tags/
# Whether to use modGroup as the maven publishing group.
# When false, com.github.GTNewHorizons is used.
useModGroupForPublishing = false
# Will update your build.gradle automatically whenever an update is available
# Updates your build.gradle and settings.gradle automatically whenever an update is available.
autoUpdateBuildScript = false
# Version of Minecraft to target
minecraftVersion = 1.7.10
# Version of Minecraft Forge to target
forgeVersion = 10.13.4.1614
# Select a username for testing your mod with breakpoints. You may leave this empty for a random user name each time you
# restart Minecraft in development. Choose this dependent on your mod:
# Do you need consistent player progressing (for example Thaumcraft)? -> Select a name
# Do you need to test how your custom blocks interacts with a player that is not the owner? -> leave name empty
developmentEnvironmentUserName = "Developer"
# Specify an MCP channel for dependency deobfuscation and the deobfParams task.
channel = stable
# Define a source file of your project with:
# public static final String VERSION = "GRADLETOKEN_VERSION";
# The string's content will be replaced with your mods 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 = StructureLib.java
# Specify an MCP mappings version for dependency deobfuscation and the deobfParams task.
mappingsVersion = 12
# Defines other MCP mappings for dependency deobfuscation.
remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/
# Select a default username for testing your mod. You can always override this per-run by running
# `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE.
developmentEnvironmentUserName = Developer
# Enables modern Java syntax support. Valid values:
# - false: No modern syntax, Java 8 only
# - jabel: Jabel syntax-only support, compiles to J8 bytecode
# - jvmDowngrader: Full modern Java via JVM Downgrader (syntax + stdlib APIs)
# - modern: Native modern Java bytecode, no downgrading
enableModernJavaSyntax = jabel
# If set, ignores the above setting and compiles with the given toolchain. This may cause unexpected issues,
# and should *not* be used in most situations. -1 disables this.
# forceToolchainVersion = -1
# Target JVM version for JVM Downgrader bytecode downgrading.
# Only used when enableModernJavaSyntax = jvmDowngrader
# downgradeTargetVersion = 8
# Comma-separated list of Java versions for multi-release jar support (JVM Downgrader only).
# Classes will be available in META-INF/versions/N/ for each version N in this list.
# Default: "21,25" (J25+ gets native classes, J21-24 gets partial downgrade, J8-20 gets full downgrade).
# jvmDowngraderMultiReleaseVersions = 21,25
# Specifies how JVM Downgrader API stubs are provided. Options:
# - shade: Shade minimized stubs into the jar
# - gtnhlib: GTNHLib provides stubs at runtime (adds version constraint)
# - external: Another dependency provides stubs (no constraint, no warning)
# - (empty): Warning reminding you to configure stubs
# Note: 'shade' option requires you to verify license compliance, see: https://github.com/unimined/JvmDowngrader/blob/main/LICENSE.md
# jvmDowngraderStubsProvider =
# Enables injecting missing generics into the decompiled source code for a better coding experience.
# Turns most publicly visible List, Map, etc. into proper List<E>, Map<K, V> types.
enableGenericInjection = true
# Generate a class with a String field for the mod version named as defined below.
# If generateGradleTokenClass is empty or not missing, no such class will be generated.
# If gradleTokenVersion is empty or missing, the field will not be present in the class.
generateGradleTokenClass = com.gtnewhorizon.structurelib.Tags
# Name of the token containing the project's current version to generate/replace.
gradleTokenVersion = VERSION
# [DEPRECATED] Mod ID replacement token.
gradleTokenModId =
# [DEPRECATED] Mod name replacement token.
gradleTokenModName =
gradleTokenVersion = GRADLETOKEN_VERSION
# [DEPRECATED] Mod Group replacement token.
gradleTokenGroupName =
# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise you can
# [DEPRECATED]
# Multiple source files can be defined here by providing a comma-separated 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.
# Example value: apiPackage = api + modGroup = com.myname.mymodid -> com.myname.mymodid.api
# Example value: (apiPackage = api) + (modGroup = com.myname.mymodid) -> com.myname.mymodid.api
apiPackage =
# Specify the configuration file for Forge's access transformers here. I must be placed into /src/main/resources/META-INF/
# Example value: mymodid_at.cfg
# Specify the configuration file for Forge's access transformers here. It must be placed into /src/main/resources/META-INF/
# There can be multiple files in a space-separated list.
# Example value: mymodid_at.cfg nei_at.cfg
accessTransformersFile =
# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled!
usesMixins = false
usesMixins = true
# Set to a non-empty string to configure mixins in a separate source set under src/VALUE, instead of src/main.
# This can speed up compile times thanks to not running the mixin annotation processor on all input sources.
# Mixin classes will have access to "main" classes, but not the other way around.
separateMixinSourceSet =
# Adds some debug arguments like verbose output and class export.
usesMixinDebug = false
# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise.
mixinPlugin =
# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail!
mixinsPackage =
# Specify the package that contains all of your Mixins. The package must exist or
# the build will fail. If you have a package property defined in your mixins.<modid>.json,
# it must match with this or the build will fail.
mixinsPackage = mixins
# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin!
# This parameter is for legacy compatability only
# Example value: coreModClass = asm.FMLPlugin + modGroup = com.myname.mymodid -> com.myname.mymodid.asm.FMLPlugin
coreModClass =
# This parameter is for legacy compatibility only
# Example value: (coreModClass = asm.FMLPlugin) + (modGroup = com.myname.mymodid) -> com.myname.mymodid.asm.FMLPlugin
coreModClass = core.StructureLibCore
# If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod ( = some class
# that is annotated with @Mod) you want this to be true. When in doubt: leave it on false!
containsMixinsAndOrCoreModOnly = false
# 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.
# Enables Mixins even if this mod doesn't use them, useful if one of the dependencies uses mixins.
forceEnableMixins = false
# If enabled, you may use 'shadowCompile' for dependencies. They will be integrated into your jar. It is your
# responsibility to check the license and request permission for distribution if required.
usesShadowedDependencies = false
# If disabled, won't remove unused classes from shadowed dependencies. Some libraries use reflection to access
# their own classes, making the minimization unreliable.
minimizeShadowedDependencies = true
# If disabled, won't rename the shadowed classes.
relocateShadowedDependencies = true
# Adds CurseMaven, Modrinth, and some more well-known 1.7.10 repositories.
includeWellKnownRepositories = true
# A list of repositories to exclude from the includeWellKnownRepositories setting. Should be a space separated
# list of strings, with the acceptable keys being(case does not matter):
# cursemaven
# modrinth
excludeWellKnownRepositories =
# Change these to your Maven coordinates if you want to publish to a custom Maven repository instead of the default GTNH Maven.
# Authenticate with the MAVEN_USER and MAVEN_PASSWORD environment variables.
# If you need a more complex setup disable maven publishing here and add a publishing repository to addon.gradle.
usesMavenPublishing = true
# Maven repository to publish the mod to.
# mavenPublishUrl = https\://nexus.gtnewhorizons.com/repository/releases/
# 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 to Modrinth.
modrinthProjectId =
# 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.
# Example: required-project:fplib;optional-project:gasstation;incompatible-project:gregtech
# Note: UniMixins is automatically set as a required dependency if usesMixins = true.
modrinthRelations =
# 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 =
# 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 slug of the other mod.
# Example: requiredDependency:railcraft;embeddedLibrary:cofhlib;incompatible:buildcraft
# Note: UniMixins is automatically set as a required dependency if usesMixins = true.
curseForgeRelations =
# Optional parameter to customize the produced artifacts. Use this to preserve artifact naming when migrating older
# projects. New projects should not use this parameter.
# customArchiveBaseName =
# Optional parameter to customize the default working directory used by the runClient* tasks. Relative to the project directory.
# runClientWorkingDirectory = run/client
# Optional parameter to customize the default working directory used by the runServer* tasks. Relative to the project directory.
# runServerWorkingDirectory = run/server
# Optional parameter to have the build automatically fail if an illegal version is used.
# This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'.
# The check is ONLY performed if the version is a git tag.
# Note: the specified string must be escaped, so e.g. 1\\.1\\.\\d+ instead of 1\.1\.\d+
# versionPattern =
# Uncomment to prevent the source code from being published.
# noPublishedSources = true
# Uncomment this to disable Spotless checks.
# This should only be uncommented to keep it easier to sync with upstream/other forks.
# That is, if there is no other active fork/upstream, NEVER change this.
# disableSpotless = true
# Uncomment this to disable Checkstyle checks (currently wildcard import check).
# disableCheckstyle = true
# Override the IDEA build type. Valid values are: "" (leave blank, do not override), "idea" (force use native IDEA build), "gradle"
# (force use delegated build).
# This is meant to be set in $HOME/.gradle/gradle.properties.
# e.g. add "systemProp.org.gradle.project.ideaOverrideBuildType=idea" will override the build type to be native build.
# WARNING: If you do use this option, it will overwrite whatever you have in your existing projects. This might not be what you want!
# Usually there is no need to uncomment this here as other developers do not necessarily use the same build type as you.
# ideaOverrideBuildType = idea
# Whether IDEA should run spotless checks when pressing the Build button.
# This is meant to be set in $HOME/.gradle/gradle.properties.
# ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
org.gradle.configuration-cache = true
org.gradle.parallel = true
+12
View File
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c2dd35c9d0aaf0ba6ad0791320f99dfc/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/e5810bd7fd1f8a586644409d395a7e55/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/7b3c4877c0749019e6805bb61e421497/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d76df094a9cbbabd3b08251f9e61444a/redirect
toolchainVersion=25
Binary file not shown.
+2 -1
View File
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+22 -18
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015 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.
@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
@@ -55,7 +57,7 @@
# 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
# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -83,10 +85,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# 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"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -114,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -133,10 +132,13 @@ location of your Java installation."
fi
else
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.
if ! command -v java >/dev/null 2>&1
then
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
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
@@ -144,7 +146,7 @@ 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
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -152,7 +154,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -169,7 +171,6 @@ fi
# 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" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -197,16 +198,19 @@ if "$cygwin" || "$msys" ; then
done
fi
# 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.
# 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 optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
Vendored
+13 -12
View File
@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@@ -43,11 +45,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -57,22 +59,21 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
: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 %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
-4
View File
@@ -1,8 +1,4 @@
// Add any additional repositiroes for your dependencies here
repositories {
maven {
name = "GTNH"
url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/"
}
}
+5 -10
View File
@@ -4,10 +4,10 @@ pluginManagement {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/"
allowInsecureProtocol = true
url "https://nexus.gtnewhorizons.com/repository/public/"
mavenContent {
includeGroup("com.gtnewhorizons.retrofuturagradle")
includeGroup("com.gtnewhorizons")
includeGroupByRegex("com\\.gtnewhorizons\\..+")
}
}
gradlePluginPortal()
@@ -17,12 +17,7 @@ pluginManagement {
}
plugins {
id 'com.diffplug.blowdryerSetup' version '1.6.0'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' // Provides java toolchains
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.26'
}
blowdryerSetup {
repoSubfolder 'gtnhShared'
github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.0')
//devLocal '.' // Use this when testing config updates locally
}
@@ -0,0 +1,94 @@
package com.gtnewhorizon.structurelib;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import net.minecraft.item.ItemStack;
import com.gtnewhorizon.gtnhlib.util.map.ItemStackMap;
import cpw.mods.fml.common.Loader;
// this is not an API! go check StructureLibAPI instead!
public class ChannelDescription {
private static final ItemStackMap<Set<ChannelDescription>> itemToChannels = new ItemStackMap<>(true);
private static final Map<String, ChannelDescription> registry = new HashMap<>();
private final String channel;
private final Map<String, String> descriptions = new HashMap<>();
private final ItemStackMap<Integer> items = new ItemStackMap<>(true);
public static ChannelDescription get(final String channel) {
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY");
return registry.computeIfAbsent(channel, ChannelDescription::new);
}
public static boolean has(final String channel) {
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY");
return registry.containsKey(channel);
}
public static Collection<Map.Entry<String, Integer>> iterate(final ItemStack block) {
Set<ChannelDescription> channels = itemToChannels.get(block);
if (channels == null) return Collections.emptySet();
return channels.stream().map(d -> new AbstractMap.SimpleImmutableEntry<>(d.channel, d.items.get(block)))
.collect(Collectors.toList());
}
public static void set(final String channel, final String modid, final String description) {
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY");
registry.computeIfAbsent(channel, ChannelDescription::new).add(modid, description);
}
public static void item(final String channel, int channelValue, ItemStack stack) {
if (StructureLibAPI.isDebugEnabled()) {
if (!channel.toLowerCase(Locale.ROOT).equals(channel)) {
throw new IllegalArgumentException("Channel name can be lower case ONLY");
}
if (channelValue <= 0) {
throw new IllegalArgumentException("Channel value must be greater than 0");
}
}
ChannelDescription inst = registry.computeIfAbsent(channel, ChannelDescription::new);
inst.items.put(stack, channelValue);
itemToChannels.computeIfAbsent(stack, s -> new HashSet<>()).add(inst);
}
public static Map<String, ChannelDescription> getAll() {
return Collections.unmodifiableMap(registry);
}
private ChannelDescription(String channel) {
this.channel = channel;
}
public String getChannel() {
return channel;
}
public ChannelDescription add(String modid, String description) {
if (Loader.instance().getIndexedModList().get(modid) == null) {
throw new IllegalArgumentException("Mod not found: " + modid);
}
descriptions.put(modid, description);
return this;
}
public Map<String, String> getDescriptions() {
return Collections.unmodifiableMap(descriptions);
}
public Map<ItemStack, Integer> getItems() {
return Collections.unmodifiableMap(items);
}
}
@@ -2,16 +2,24 @@ package com.gtnewhorizon.structurelib;
import static com.gtnewhorizon.structurelib.StructureLib.RANDOM;
import java.util.*;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.gui.GuiNewChat;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.culling.Frustrum;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -24,18 +32,27 @@ import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.world.WorldEvent;
import org.apache.commons.lang3.tuple.Pair;
import org.lwjgl.opengl.GL11;
import com.gtnewhorizon.structurelib.entity.fx.WeightlessParticleFX;
import com.gtnewhorizon.structurelib.net.RegistryOrderSyncMessage;
import com.gtnewhorizon.structurelib.net.SetChannelDataMessage;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import cpw.mods.fml.common.network.FMLNetworkEvent;
public class ClientProxy extends CommonProxy {
@@ -47,7 +64,6 @@ public class ClientProxy extends CommonProxy {
*/
private static final List<HintGroup> allGroups = new ArrayList<>();
public static int HOLOGRAM_LIFETIME = 200;
/**
* Current batch of hints. Belongs to the same logical multiblock.
*/
@@ -248,6 +264,47 @@ public class ClientProxy extends CommonProxy {
((IStructureCompat) StructureLib.COMPAT).markTextureUsed(icon);
}
static void sendRegistryOrderToServer() {
if (FMLEventHandler.configSent) return;
FMLEventHandler.configSent = true;
for (String s : SortedRegistry.ALL_REGISTRIES.keySet()) {
Pair<List<String>, List<String>> registryOrder = ConfigurationHandler.INSTANCE.getRegistryOrder(s);
if (registryOrder == null || registryOrder.getKey().isEmpty() && registryOrder.getValue().isEmpty())
continue;
StructureLib.net
.sendToServer(new RegistryOrderSyncMessage(s, registryOrder.getKey(), registryOrder.getValue()));
}
}
@Override
public void loadComplete(FMLLoadCompleteEvent evt) {
super.loadComplete(evt);
for (Map.Entry<String, WeakReference<SortedRegistry<?>>> e : SortedRegistry.ALL_REGISTRIES.entrySet()) {
SortedRegistry<?> r = e.getValue().get();
if (r == null) continue;
Pair<List<String>, List<String>> p = ConfigurationHandler.INSTANCE.getRegistryOrder(e.getKey());
r.registerOrdering(getSPPlayerUUID(), p.getKey(), p.getValue());
}
}
public UUID getSPPlayerUUID() {
return EntityPlayer.func_146094_a(Minecraft.getMinecraft().getSession().func_148256_e());
}
public void displayConfigGUI(String category) {
ConfigElement<Object> element = new ConfigElement<>(
ConfigurationHandler.INSTANCE.getConfig().getCategory(category));
GuiConfig guiConfig = new GuiConfig(
null,
element.getChildElements(),
StructureLibAPI.MOD_ID,
null,
false,
false,
I18n.format(element.getLanguageKey()));
Minecraft.getMinecraft().displayGuiScreen(guiConfig);
}
private static class HintGroup {
private final List<HintParticleInfo> hints = new LinkedList<>();
@@ -271,10 +328,6 @@ public class ClientProxy extends CommonProxy {
private final World w;
// these are the block coordinate for e.g. w.getBlock()
private final int x, y, z;
// these are the lower bounds for rendering. the upper bound would be X + size
// currently size is fixed to be 0.5
// it is not made into a constants because this will allow for easy changing during debug
private final double X, Y, Z;
private final IIcon[] icons;
private short[] tint;
private boolean renderThrough;
@@ -286,9 +339,6 @@ public class ClientProxy extends CommonProxy {
this.x = x;
this.y = y;
this.z = z;
X = x + 0.25;
Y = y + 0.25;
Z = z + 0.25;
this.icons = icons;
this.tint = tint;
}
@@ -296,9 +346,7 @@ public class ClientProxy extends CommonProxy {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HintParticleInfo)) return false;
HintParticleInfo that = (HintParticleInfo) o;
if (!(o instanceof HintParticleInfo that)) return false;
return x == that.x && y == that.y && z == that.z;
}
@@ -324,10 +372,11 @@ public class ClientProxy extends CommonProxy {
}
public boolean isInFrustrum(Frustrum frustrum) {
return frustrum.isBoxInFrustum(X, Y, Z, X + 0.5, Y + 0.5, Z + 0.5);
return frustrum.isBoxInFrustum(x + 0.25, y + 0.25, z + 0.25, x + 0.75, y + 0.75, z + 0.75);
}
public void draw(Tessellator tes, double eyeX, double eyeY, double eyeZ) {
public void draw(Tessellator tes, double eyeX, double eyeY, double eyeZ, int eyeXint, int eyeYint,
int eyeZint) {
double size = 0.5;
int brightness = w.blockExists(x, 0, z) ? w.getLightBrightnessForSkyBlocks(x, y, z, 0) : 0;
@@ -339,70 +388,90 @@ public class ClientProxy extends CommonProxy {
(int) (tint[2] * 1F),
ConfigurationHandler.INSTANCE.getHintTransparency());
for (int i = 0; i < 6; i++) {
if (icons[i] == null) continue;
double X = (x - eyeXint) + 0.25;
double Y = (y - eyeYint) + 0.25;
double Z = (z - eyeZint) + 0.25;
double worldX = x + 0.25;
double worldY = y + 0.25;
double worldZ = z + 0.25;
markTextureUsed(icons[i]);
// cube is a very special model. its facings can be rendered correctly by viewer distance without using
// surface normals and view vector
// here we do a 2 pass render.
// first pass we draw obstructed faces (i.e. faces that are further away from player)
// second pass we draw unobstructed faces
for (int j = 0; j < 2; j++) {
boolean unobstructedPass = j == 1;
for (int i = 0; i < 6; i++) {
if (icons[i] == null) continue;
double u = icons[i].getMinU();
double U = icons[i].getMaxU();
double v = icons[i].getMinV();
double V = icons[i].getMaxV();
markTextureUsed(icons[i]);
// cube is a very special model. its facings can be rendered correctly by viewer distance without using
// surface normals and view vector
// here we do a 2 pass render.
// first pass we draw obstructed faces (i.e. faces that are further away from player)
// second pass we draw unobstructed faces
for (int j = 0; j < 2; j++) {
double u = icons[i].getMinU();
double U = icons[i].getMaxU();
double v = icons[i].getMinV();
double V = icons[i].getMaxV();
switch (i) { // {DOWN, UP, NORTH, SOUTH, WEST, EAST}
case 0:
if ((Y >= eyeY) != (j == 1)) continue;
// all these ifs is in form if ((is face unobstructed) != (is in unobstructred pass))
if ((worldY >= eyeY) != unobstructedPass) continue;
tes.setNormal(0, -1, 0);
tes.addVertexWithUV(X, Y, Z + size, u, V);
tes.addVertexWithUV(X, Y, Z, u, v);
tes.addVertexWithUV(X + size, Y, Z, U, v);
tes.addVertexWithUV(X + size, Y, Z, U, v);
tes.addVertexWithUV(X + size, Y, Z + size, U, V);
tes.addVertexWithUV(X, Y, Z + size, u, V);
break;
case 1:
if ((Y + size <= eyeY) != (j == 1)) continue;
if ((worldY + size <= eyeY) != unobstructedPass) continue;
tes.setNormal(0, 1, 0);
tes.addVertexWithUV(X, Y + size, Z, u, v);
tes.addVertexWithUV(X, Y + size, Z + size, u, V);
tes.addVertexWithUV(X + size, Y + size, Z + size, U, V);
tes.addVertexWithUV(X + size, Y + size, Z + size, U, V);
tes.addVertexWithUV(X + size, Y + size, Z, U, v);
tes.addVertexWithUV(X, Y + size, Z, u, v);
break;
case 2:
if ((Z >= eyeZ) != (j == 1)) continue;
if ((worldZ >= eyeZ) != unobstructedPass) continue;
tes.setNormal(0, 0, -1);
tes.addVertexWithUV(X, Y, Z, U, V);
tes.addVertexWithUV(X, Y + size, Z, U, v);
tes.addVertexWithUV(X + size, Y + size, Z, u, v);
tes.addVertexWithUV(X + size, Y + size, Z, u, v);
tes.addVertexWithUV(X + size, Y, Z, u, V);
tes.addVertexWithUV(X, Y, Z, U, V);
break;
case 3:
if ((Z <= eyeZ) != (j == 1)) continue;
if ((worldZ + size <= eyeZ) != unobstructedPass) continue;
tes.setNormal(0, 0, 1);
tes.addVertexWithUV(X + size, Y, Z + size, U, V);
tes.addVertexWithUV(X + size, Y + size, Z + size, U, v);
tes.addVertexWithUV(X, Y + size, Z + size, u, v);
tes.addVertexWithUV(X, Y + size, Z + size, u, v);
tes.addVertexWithUV(X, Y, Z + size, u, V);
tes.addVertexWithUV(X + size, Y, Z + size, U, V);
break;
case 4:
if ((X >= eyeX) != (j == 1)) continue;
if ((worldX >= eyeX) != unobstructedPass) continue;
tes.setNormal(-1, 0, 0);
tes.addVertexWithUV(X, Y, Z + size, U, V);
tes.addVertexWithUV(X, Y + size, Z + size, U, v);
tes.addVertexWithUV(X, Y + size, Z, u, v);
tes.addVertexWithUV(X, Y + size, Z, u, v);
tes.addVertexWithUV(X, Y, Z, u, V);
tes.addVertexWithUV(X, Y, Z + size, U, V);
break;
case 5:
if ((X + size <= eyeX) != (j == 1)) continue;
if ((worldX + size <= eyeX) != unobstructedPass) continue;
tes.setNormal(1, 0, 0);
tes.addVertexWithUV(X + size, Y, Z, U, V);
tes.addVertexWithUV(X + size, Y + size, Z, U, v);
tes.addVertexWithUV(X + size, Y + size, Z + size, u, v);
tes.addVertexWithUV(X + size, Y + size, Z + size, u, v);
tes.addVertexWithUV(X + size, Y, Z + size, u, V);
tes.addVertexWithUV(X + size, Y, Z, U, V);
break;
}
}
@@ -414,18 +483,40 @@ public class ClientProxy extends CommonProxy {
}
public double getSquareDistanceTo(Vec3 point) {
return point.squareDistanceTo(X, Y, Z);
return point.squareDistanceTo(x + 0.5, y + 0.5, z + 0.5);
}
}
public static class FMLEventHandler {
static boolean connected = false;
static boolean configSent = false;
private void resetPlayerLocation() {
lastPlayerPos.xCoord = Minecraft.getMinecraft().thePlayer.posX;
lastPlayerPos.yCoord = Minecraft.getMinecraft().thePlayer.posY;
lastPlayerPos.zCoord = Minecraft.getMinecraft().thePlayer.posZ;
}
@SubscribeEvent
public void onPlayerLogIn(FMLNetworkEvent.ClientConnectedToServerEvent e) {
connected = true;
configSent = false;
}
@SubscribeEvent
public void onPlayerLogOut(FMLNetworkEvent.ClientDisconnectionFromServerEvent e) {
connected = false;
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onConfigChange(ConfigChangedEvent.PostConfigChangedEvent e) {
if (connected && e.modID.equals(StructureLibAPI.MOD_ID)) {
configSent = false;
sendRegistryOrderToServer();
}
}
@SubscribeEvent
public void onClientTick(ClientTickEvent e) {
if (e.phase == Phase.END && Minecraft.getMinecraft().thePlayer != null) {
@@ -469,6 +560,13 @@ public class ClientProxy extends CommonProxy {
public static class ForgeEventHandler {
@SubscribeEvent
public void onEntityJoinWorld(EntityJoinWorldEvent e) {
if (e.world.isRemote && e.entity instanceof EntityClientPlayerMP) {
sendRegistryOrderToServer();
}
}
@SubscribeEvent
public void onWorldLoad(WorldEvent.Load e) {
if (e.world.isRemote) {
@@ -501,6 +599,7 @@ public class ClientProxy extends CommonProxy {
+ (entitylivingbase.posY - entitylivingbase.lastTickPosY) * e.partialTicks;
double d2 = entitylivingbase.lastTickPosZ
+ (entitylivingbase.posZ - entitylivingbase.lastTickPosZ) * e.partialTicks;
int i0 = (int) d0, i1 = (int) d1, i2 = (int) d2;
frustrum.setPosition(d0, d1, d2);
GL11.glPushMatrix();
@@ -513,25 +612,34 @@ public class ClientProxy extends CommonProxy {
// depth test begin as enabled
boolean renderThrough = false;
Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture);
GL11.glTranslated(-RenderManager.renderPosX, -RenderManager.renderPosY, -RenderManager.renderPosZ);
GL11.glTranslated(-d0 + i0, -d1 + i1, -d2 + i2);
Tessellator tes = Tessellator.instance;
tes.startDrawingQuads();
for (int i = 0, allHintsForRenderSize = allHintsForRender.size(); i < allHintsForRenderSize; i++) {
tes.startDrawing(GL11.GL_TRIANGLES);
for (int i = 0, allHintsForRenderSize = allHintsForRender.size(), cubeDrawn = 0; i
< allHintsForRenderSize; i++, cubeDrawn++) {
HintParticleInfo hint = allHintsForRender.get(i);
if (!hint.isInFrustrum(frustrum)) continue;
if (renderThrough != hint.renderThrough) {
if (i > 0) {
p.endStartSection("Draw");
tes.draw();
tes.startDrawingQuads();
tes.startDrawing(GL11.GL_TRIANGLES);
cubeDrawn = 0;
p.endStartSection("Prepare");
}
if (hint.renderThrough) GL11.glDisable(GL11.GL_DEPTH_TEST);
else GL11.glEnable(GL11.GL_DEPTH_TEST);
renderThrough = hint.renderThrough;
}
// TODO verify if we need to add eyeHeight
hint.draw(tes, d0, d1, d2);
// Minecraft Tessellator draw in batch of 4096. This plays nicely with quads, but for trigs
// it might occasionally end up with one half in first batch and the other half in later batch.
// so we manually flush the buffer here if that would happen.
// 6 faces per particle, 2 trig per face, 3 vertex per trig
if ((cubeDrawn + 1) >= 4096 / (6 * 2 * 3)) {
tes.draw();
tes.startDrawing(GL11.GL_TRIANGLES);
}
hint.draw(tes, d0, d1, d2, i0, i1, i2);
}
p.endStartSection("Draw");
tes.draw();
@@ -12,13 +12,23 @@ import net.minecraft.server.MinecraftServer;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import com.gtnewhorizon.structurelib.net.ErrorHintParticleMessage;
import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
public class CommonProxy {
public CommonProxy() {
super();
MinecraftForge.EVENT_BUS.register(new ForgeEventHandler());
}
public void hintParticleTinted(World w, int x, int y, int z, IIcon[] icons, short[] RGBa) {}
public void hintParticleTinted(World w, int x, int y, int z, Block block, int meta, short[] RGBa) {}
@@ -69,6 +79,10 @@ public class CommonProxy {
}
}
public void loadComplete(FMLLoadCompleteEvent e) {
ConfigurationHandler.INSTANCE.loadRegistryOrder();
}
private final Map<EntityPlayerMP, Map<Object, Long>> throttleMap = new WeakHashMap<>();
public void addThrottledChat(Object throttleKey, EntityPlayer player, IChatComponent text, short intervalRequired,
@@ -93,4 +107,22 @@ public class CommonProxy {
if (!forceUpdateLastSend) submap.put(throttleKey, now);
}
}
public void displayConfigGUI(String category) {}
public static class ForgeEventHandler {
private int ticksSinceLastPurge;
@SubscribeEvent
public void onServerTickEnd(TickEvent.ServerTickEvent e) {
if (e.phase != TickEvent.Phase.END) return;
if (++ticksSinceLastPurge < 20 * 60 * 10) return;
ticksSinceLastPurge = 0;
MinecraftServer server = MinecraftServer.getServer();
// it's hard to tell why server could be null in a server tick handler, but who knows?
if (server == null) return;
SortedRegistry.cleanup(server);
}
}
}
@@ -1,15 +1,27 @@
package com.gtnewhorizon.structurelib;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.gtnewhorizon.structurelib.structure.FluidAutoplace;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
public enum ConfigurationHandler {
@@ -22,6 +34,9 @@ public enum ConfigurationHandler {
private int hintTransparency;
private int autoPlaceBudget;
private int autoPlaceInterval;
private boolean fluidAutoplace = true;
private FluidAutoplace.GateMode fluidGateMode = FluidAutoplace.GateMode.STRICT;
private Map<String, Pair<List<String>, List<String>>> registryOrders;
ConfigurationHandler() {
FMLCommonHandler.instance().bus().register(this);
@@ -85,9 +100,75 @@ public enum ConfigurationHandler {
+ "As expected, server side settings will overrides client settings.\n"
+ "Note this relates to the wall clock, not in game ticks.\n"
+ "Value smaller than default is likely to be perceived as no minimal interval whatsoever.");
fluidAutoplace = config.getBoolean(
"fluidAutoplace",
"common.autoplace",
true,
"Whether survival autoplace may place fluid blocks, e.g. the water a multiblock needs inside itself, by draining fluid from the player's fluid containers.\n"
+ "A multiblock can also provide its own fluid source, see IFluidSource.\n"
+ "This only disables fluid blocks. Multiblocks keep working, they just cannot have those positions filled by autoplace.");
fluidGateMode = readFluidGateMode();
loadRegistryOrder();
saveConfig();
}
private FluidAutoplace.GateMode readFluidGateMode() {
String value = config.getString(
"fluidGateMode",
"common.autoplace",
FluidAutoplace.GateMode.STRICT.name(),
"How careful autoplace is about placing a fluid into a structure that is not finished yet, as a fluid would flow out of it.\n"
+ "NONE: place the fluid right away.\n"
+ "LENIENT: only place the fluid when it cannot flow out of the structure.\n"
+ "STRICT: only place the fluid once every non fluid element of the structure is satisfied. Note that this makes a fluid at worst one auto place round late.");
for (FluidAutoplace.GateMode mode : FluidAutoplace.GateMode.values()) {
if (mode.name().equalsIgnoreCase(value)) return mode;
}
StructureLib.LOGGER.warn("Unknown fluidGateMode '{}', falling back to STRICT", value);
return FluidAutoplace.GateMode.STRICT;
}
void loadRegistryOrder() {
loadRegistryOrderImpl();
setLanguageKeys();
saveConfig();
}
private void loadRegistryOrderImpl() {
registryOrders = new HashMap<>();
for (Map.Entry<String, WeakReference<SortedRegistry<?>>> e : SortedRegistry.ALL_REGISTRIES.entrySet()) {
SortedRegistry<?> r = e.getValue().get();
if (r == null) continue;
String category = "registries." + e.getKey();
if (FMLLaunchHandler.side().isClient()) {
// only meaningful on client, and would crash on server
config.setCategoryConfigEntryClass(category, RegistryOrderEntry.class);
}
Property pOrder = config.get(
category,
"ordering",
Iterables.toArray(r.getCurrentOrdering(), String.class),
"stuff not in this list will be automatically available after all entries listed here in their natural order, unless explicitly disabled in disabled config below.");
Property pDisable = config.get(category, "disabled", new String[0], "stuff in this list will be disabled");
List<String> all = Lists.newArrayList(r.getCurrentOrdering());
List<String> curVal = new ArrayList<>(Arrays.asList(pOrder.getStringList()));
List<String> disabled = new ArrayList<>(Arrays.asList(pDisable.getStringList()));
curVal.removeAll(disabled);
all.removeAll(disabled);
curVal.removeIf(s -> !all.remove(s));
curVal.addAll(all);
pOrder.set(curVal.toArray(new String[0]));
registryOrders.put(e.getKey(), Pair.of(curVal, disabled));
}
saveConfig();
}
private void saveConfig() {
if (config.hasChanged()) {
config.save();
config.load();
}
}
@@ -122,7 +203,26 @@ public enum ConfigurationHandler {
return autoPlaceInterval;
}
/**
* Whether survival autoplace may place fluid blocks by draining fluid from a fluid source.
*/
public boolean isFluidAutoplaceEnabled() {
return fluidAutoplace;
}
/**
* How careful autoplace is about placing a fluid into a structure that is not finished yet.
*/
public FluidAutoplace.GateMode getFluidGateMode() {
return fluidGateMode;
}
public Pair<List<String>, List<String>> getRegistryOrder(String name) {
return registryOrders.get(name);
}
Configuration getConfig() {
return config;
}
}
@@ -0,0 +1,48 @@
package com.gtnewhorizon.structurelib;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import cpw.mods.fml.common.event.FMLInterModComms;
public class DevelopHelper {
private static final boolean DEBUG = Boolean.getBoolean("structurelib.develop_helper");
public static void onPreInit() {
if (!DEBUG) return;
StructureLib.LOGGER.info("Running develop helper");
StructureLibAPI.registerChannelDescription("sandstone", StructureLibAPI.MOD_ID, "variants of Sandstone");
StructureLibAPI.registerChannelItem("sandstone", StructureLibAPI.MOD_ID, 1, new ItemStack(Blocks.sandstone));
StructureLibAPI
.registerChannelItem("sandstone", StructureLibAPI.MOD_ID, 2, new ItemStack(Blocks.sandstone, 1, 1));
StructureLibAPI
.registerChannelItem("sandstone", StructureLibAPI.MOD_ID, 3, new ItemStack(Blocks.sandstone, 1, 2));
StructureLibAPI.registerChannelDescription("sandbricks", StructureLibAPI.MOD_ID, "variants of Sandbricks");
StructureLibAPI.registerChannelDescription("apple", StructureLibAPI.MOD_ID, "apple");
StructureLibAPI.registerChannelDescription("bright", StructureLibAPI.MOD_ID, "bright");
StructureLibAPI.registerChannelDescription("apple_blight", StructureLibAPI.MOD_ID, "apple_blight");
StructureLibAPI.registerChannelDescription("app_eagle", StructureLibAPI.MOD_ID, "app_eagle");
}
public void x() {
NBTTagCompound command = new NBTTagCompound();
NBTTagList items = new NBTTagList();
int[] metas = { 0, 1, 2 };
for (int meta : metas) {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag("Item", new ItemStack(Blocks.sandstone, 1, meta).writeToNBT(new NBTTagCompound()));
NBTTagList channels = new NBTTagList();
NBTTagCompound channel = new NBTTagCompound();
channel.setString("Channel", "sandstone");
channel.setInteger("Value", meta + 1);
channels.appendTag(channel);
tag.setTag("Channels", channels);
items.appendTag(tag);
}
command.setTag("Items", items);
FMLInterModComms.sendMessage("structurelib", "register_channel_item", command);
}
}
@@ -0,0 +1,695 @@
/*
* Forge Mod Loader Copyright (c) 2012-2014 cpw. All rights reserved. This program and the accompanying materials are
* made available under the terms of the GNU Lesser Public License v2.1 which accompanies this distribution, and is
* available at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html Contributors (this class): bspkrs - implementation
*/
package com.gtnewhorizon.structurelib;
import static cpw.mods.fml.client.config.GuiUtils.RESET_CHAR;
import static cpw.mods.fml.client.config.GuiUtils.UNDO_CHAR;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.WeakHashMap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiListExtended;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.client.config.GuiButtonExt;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.GuiUnicodeGlyphButton;
import cpw.mods.fml.client.config.GuiUtils;
import cpw.mods.fml.client.config.HoverChecker;
import cpw.mods.fml.client.config.IConfigElement;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
import cpw.mods.fml.client.event.ConfigChangedEvent.PostConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.eventhandler.Event.Result;
/**
* This class is the base GuiScreen for all config GUI screens. It can be extended by mods to provide the top-level
* config screen that will be called when the Config button is clicked from the Main Menu Mods list.
*
* @author bspkrs
*/
public class GuiEditRegistryConfig extends GuiScreen {
public static final String OMITTED = "..";
public static final int LIST_WINDOW_PADDING = 20;
public static final int MID_SECTION_WIDTH = 10;
/**
* A reference to the screen object that created this. Used for navigating between screens.
*/
public final GuiScreen parentScreen;
private final IConfigElement<String> disabledElement;
private final String[] beforeDisabledValue;
private final IConfigElement<String> orderElement;
private final String[] beforeOrderValue;
final Collection<EntriesList> lists;
private final String registryName;
EntriesList disabledEntries;
EntriesList orderEntries;
public String title = "Config GUI";
public String titleLine2;
private GuiButtonExt btnDefault;
private GuiButtonExt btnUndoAll;
public final String modID;
/**
* When set to a non-null value the OnConfigChanged and PostConfigChanged events will be posted when the Done button
* is pressed if any configElements were changed (includes child screens). If not defined, the events will be posted
* if the parent gui is null or if the parent gui is not an instance of GuiConfig.
*/
public final String configID;
public final boolean isWorldRunning;
public final boolean allRequireWorldRestart;
public final boolean allRequireMcRestart;
public boolean needsRefresh = true;
private HoverChecker undoHoverChecker;
private HoverChecker resetHoverChecker;
@SuppressWarnings({ "rawtypes", "unchecked" })
public GuiEditRegistryConfig(GuiScreen parentScreen, IConfigElement disabled, IConfigElement order,
String registryName, String modID, String configID, boolean allRequireWorldRestart,
boolean allRequireMcRestart, String title, String titleLine2) {
this.mc = parentScreen.mc;
this.lists = Collections.newSetFromMap(new WeakHashMap<>());
this.disabledElement = disabled;
this.beforeDisabledValue = (String[]) this.disabledElement.getList();
this.orderElement = order;
this.beforeOrderValue = (String[]) this.orderElement.getList();
this.parentScreen = parentScreen;
this.allRequireWorldRestart = allRequireWorldRestart;
this.allRequireMcRestart = allRequireMcRestart;
this.registryName = registryName;
this.modID = modID;
this.configID = configID;
this.isWorldRunning = mc.theWorld != null;
if (title != null) this.title = title;
this.titleLine2 = titleLine2;
if (this.titleLine2 != null && this.titleLine2.startsWith(" > "))
this.titleLine2 = this.titleLine2.replaceFirst(" > ", "");
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
@Override
public void initGui() {
Keyboard.enableRepeatEvents(true);
if (this.disabledEntries == null || this.needsRefresh) {
this.disabledEntries = new EntriesList(
(width - MID_SECTION_WIDTH) / 2 - LIST_WINDOW_PADDING,
LIST_WINDOW_PADDING,
I18n.format("structurelib.configgui.disabled"));
this.disabledEntries.initEntries(Arrays.asList(disabledElement.getList()));
} else {
this.disabledEntries.reinit((width - MID_SECTION_WIDTH) / 2 - LIST_WINDOW_PADDING, LIST_WINDOW_PADDING);
}
if (this.orderEntries == null || this.needsRefresh) {
this.orderEntries = new EntriesList(
(width - MID_SECTION_WIDTH) / 2 - LIST_WINDOW_PADDING,
(width + MID_SECTION_WIDTH) / 2,
I18n.format("structurelib.configgui.enabled"));
this.orderEntries.initEntries(Arrays.asList(orderElement.getList()));
} else {
this.orderEntries
.reinit((width - MID_SECTION_WIDTH) / 2 - LIST_WINDOW_PADDING, (width + MID_SECTION_WIDTH) / 2);
}
this.needsRefresh = false;
int undoGlyphWidth = mc.fontRenderer.getStringWidth(UNDO_CHAR) * 2;
int resetGlyphWidth = mc.fontRenderer.getStringWidth(RESET_CHAR) * 2;
int doneWidth = Math.max(mc.fontRenderer.getStringWidth(I18n.format("gui.done")) + 20, 100);
int undoWidth = mc.fontRenderer.getStringWidth(" " + I18n.format("fml.configgui.tooltip.undoChanges"))
+ undoGlyphWidth
+ 20;
int resetWidth = mc.fontRenderer.getStringWidth(" " + I18n.format("fml.configgui.tooltip.resetToDefault"))
+ resetGlyphWidth
+ 20;
int buttonWidthHalf = (doneWidth + 5 + undoWidth + 5 + resetWidth + 5) / 2;
this.buttonList.add(
new GuiButtonExt(
2000,
this.width / 2 - buttonWidthHalf,
this.height - 29,
doneWidth,
20,
I18n.format("gui.done")));
this.buttonList.add(
this.btnDefault = new GuiUnicodeGlyphButton(
2001,
this.width / 2 - buttonWidthHalf + doneWidth + 5 + undoWidth + 5,
this.height - 29,
resetWidth,
20,
" " + I18n.format("fml.configgui.tooltip.resetToDefault"),
RESET_CHAR,
2.0F));
this.buttonList.add(
btnUndoAll = new GuiUnicodeGlyphButton(
2002,
this.width / 2 - buttonWidthHalf + doneWidth + 5,
this.height - 29,
undoWidth,
20,
" " + I18n.format("fml.configgui.tooltip.undoChanges"),
UNDO_CHAR,
2.0F));
this.undoHoverChecker = new HoverChecker(this.btnUndoAll, 800);
this.resetHoverChecker = new HoverChecker(this.btnDefault, 800);
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
@Override
public void onGuiClosed() {
if (this.configID != null && this.parentScreen instanceof GuiConfig parentGuiConfig) {
parentGuiConfig.needsRefresh = true;
parentGuiConfig.initGui();
}
if (!(this.parentScreen instanceof GuiConfig)) Keyboard.enableRepeatEvents(false);
}
public boolean saveConfigElements() {
if (isChanged()) {
disabledElement.set(disabledEntries.entries.stream().map(e -> e.name).toArray(String[]::new));
orderElement.set(orderEntries.entries.stream().map(e -> e.name).toArray(String[]::new));
}
return false;
}
@Override
protected void actionPerformed(GuiButton button) {
if (button.id == 2000) {
try {
if ((configID != null || this.parentScreen == null || !(this.parentScreen instanceof GuiConfig))
&& isChanged()) {
saveConfigElements();
if (Loader.isModLoaded(modID)) {
ConfigChangedEvent event = new OnConfigChangedEvent(modID, configID, isWorldRunning, false);
FMLCommonHandler.instance().bus().post(event);
if (!event.getResult().equals(Result.DENY)) FMLCommonHandler.instance().bus()
.post(new PostConfigChangedEvent(modID, configID, isWorldRunning, false));
if (this.parentScreen instanceof GuiConfig) ((GuiConfig) this.parentScreen).needsRefresh = true;
}
}
} catch (Throwable e) {
e.printStackTrace();
}
this.mc.displayGuiScreen(this.parentScreen);
} else if (button.id == 2001) {
setToDefault();
} else if (button.id == 2002) {
undoChanges();
}
}
public boolean isInitialized() {
return disabledEntries != null && orderEntries != null;
}
public void undoChanges() {
disabledEntries.initEntries(Arrays.asList(beforeDisabledValue));
orderEntries.initEntries(Arrays.asList(beforeOrderValue));
}
public void setToDefault() {
disabledEntries.initEntries(Arrays.asList(disabledElement.getList()));
orderEntries.initEntries(Arrays.asList(orderElement.getList()));
}
public boolean isDefault() {
return !orderEntries.areContentEqual(orderElement.getDefaults())
|| !disabledEntries.areContentEqual(disabledElement.getDefaults());
}
public boolean isChanged() {
return !orderEntries.areContentEqual(beforeOrderValue) || !disabledEntries.areContentEqual(beforeDisabledValue);
}
/**
* Called when the mouse is clicked.
*/
@Override
protected void mouseClicked(int x, int y, int mouseEvent) {
if (mouseEvent != 0 || !this.disabledEntries.func_148179_a(x, y, mouseEvent)
&& !this.orderEntries.func_148179_a(x, y, mouseEvent)) {
super.mouseClicked(x, y, mouseEvent);
}
}
/**
* Called when the mouse is moved or a mouse button is released. Signature: (mouseX, mouseY, which) which==-1 is
* mouseMove, which==0 or which==1 is mouseUp
*/
@Override
protected void mouseMovedOrUp(int x, int y, int mouseEvent) {
if (mouseEvent != 0 || !this.disabledEntries.func_148181_b(x, y, mouseEvent)
&& !this.orderEntries.func_148181_b(x, y, mouseEvent)) {
super.mouseMovedOrUp(x, y, mouseEvent);
}
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
@Override
protected void keyTyped(char eventChar, int eventKey) {
if (eventKey == Keyboard.KEY_ESCAPE) this.mc.displayGuiScreen(parentScreen);
}
String trimStringToWidth(String str, int width) {
int strwidth = mc.fontRenderer.getStringWidth(str);
int elipsisWidth = mc.fontRenderer.getStringWidth(OMITTED);
if (strwidth > width - elipsisWidth && elipsisWidth > strwidth) {
return mc.fontRenderer.trimStringToWidth(str, width - elipsisWidth).trim() + OMITTED;
}
return str;
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
for (EntriesList list : lists) {
list.handleDrag(mouseX, mouseY, partialTicks);
}
this.drawDefaultBackground();
for (EntriesList list : lists) {
list.drawScreen(mouseX, mouseY, partialTicks);
}
this.drawCenteredString(this.fontRendererObj, this.title, this.width / 2, 8, 16777215);
String title2 = this.titleLine2;
if (title2 != null) {
title2 = trimStringToWidth(title2, width - 6);
this.drawCenteredString(this.fontRendererObj, title2, this.width / 2, 18, 16777215);
}
this.btnUndoAll.enabled = isChanged();
this.btnDefault.enabled = isDefault();
super.drawScreen(mouseX, mouseY, partialTicks);
for (EntriesList list : lists) {
list.drawScreenPost(mouseX, mouseY, partialTicks);
}
if (this.undoHoverChecker.checkHover(mouseX, mouseY)) this.func_146283_a(
this.mc.fontRenderer.listFormattedStringToWidth(I18n.format("fml.configgui.tooltip.undoAll"), 300),
mouseX,
mouseY);
if (this.resetHoverChecker.checkHover(mouseX, mouseY)) this.func_146283_a(
this.mc.fontRenderer.listFormattedStringToWidth(I18n.format("fml.configgui.tooltip.resetAll"), 300),
mouseX,
mouseY);
}
private class EntriesList extends GuiListExtended {
final String heading;
final List<ListEntry> entries = new ArrayList<>();
int controlX;
public EntriesList(int width, int left, String heading) {
super(
mc,
width,
GuiEditRegistryConfig.this.height,
titleLine2 != null ? 33 : 23,
GuiEditRegistryConfig.this.height - 32,
20);
this.heading = heading;
if (heading != null) {
setHasListHeader(true, mc.fontRenderer.FONT_HEIGHT + 4);
}
setSlotXBoundsFromLeft(left);
this.controlX = this.getScrollBarX() - 20;
lists.add(this);
}
@Override
public void drawScreen(int p_148128_1_, int p_148128_2_, float p_148128_3_) {
GL11.glEnable(GL11.GL_SCISSOR_TEST);
ScaledResolution scaledresolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);
GL11.glScissor(
(left - 4) * scaledresolution.getScaleFactor(),
(int) ((scaledresolution.getScaledHeight_double() - (bottom + 4))
* scaledresolution.getScaleFactor()),
(width + 8) * scaledresolution.getScaleFactor(),
(height + 8) * scaledresolution.getScaleFactor());
super.drawScreen(p_148128_1_, p_148128_2_, p_148128_3_);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
}
@Override
public void overlayBackground(int p_148136_1_, int p_148136_2_, int p_148136_3_, int p_148136_4_) {}
@Override
protected void drawContainerBackground(Tessellator tessellator) {
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 0, 1);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glDisable(GL11.GL_TEXTURE_2D);
tessellator.startDrawingQuads();
tessellator.setColorRGBA_I(0, 64);
tessellator.addVertex(left, bottom, 0);
tessellator.addVertex(right, bottom, 0);
tessellator.addVertex(right, top, 0);
tessellator.addVertex(left, top, 0);
tessellator.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_BLEND);
}
@Override
protected void drawListHeader(int p_148129_1_, int p_148129_2_, Tessellator p_148129_3_) {
if (heading == null) {
return;
}
FontRenderer fr = mc.fontRenderer;
fr.drawString(
this.heading,
p_148129_1_ + this.width / 2 - fr.getStringWidth(this.heading) / 2,
Math.min(this.top + 3, p_148129_2_),
0xffffff);
}
void reinit(int width, int left) {
this.width = width;
this.bottom = GuiEditRegistryConfig.this.height - 32;
this.setSlotXBoundsFromLeft(left);
this.controlX = this.getScrollBarX() - 20;
}
void initEntries(Iterable<?> entries) {
this.controlX = this.getScrollBarX() - 20;
this.entries.clear();
for (Object entry : entries) {
addEntry(new ListEntry(entry.toString()));
}
}
void addEntry(ListEntry entry) {
entry.entriesList = this;
this.entries.add(entry);
this.controlX = Math.min(this.controlX, this.getScrollBarX() - entry.getControlSetWidth() - 2);
}
@Override
public IGuiListEntry getListEntry(int i) {
return entries.get(i);
}
@Override
protected int getSize() {
return entries.size();
}
int getLabelX() {
return left + 2;
}
int getControlX() {
return controlX;
}
@Override
public int getListWidth() {
return width;
}
@Override
protected int getScrollBarX() {
return left + getListWidth() - 6;
}
public void handleDrag(int mouseX, int mouseY, float partialTicks) {
for (int i = 0, entriesSize = entries.size(); i < entriesSize; i++) {
ListEntry entry = entries.get(i);
if (entry.handleDrag(i, mouseX, mouseY, partialTicks)) {
return;
}
}
}
public void drawScreenPost(int mouseX, int mouseY, float partialTicks) {
for (ListEntry entry : entries) {
entry.drawToolTip(mouseX, mouseY);
}
}
public boolean areContentEqual(Object[] vals) {
if (vals.length != entries.size()) return false;
for (int i = 0; i < entries.size(); i++) {
ListEntry entry = entries.get(i);
if (!entry.name.equals(vals[i])) return false;
}
return true;
}
}
class ListEntry implements GuiListExtended.IGuiListEntry {
private EntriesList entriesList;
private final HoverChecker hoverCheckerText = new HoverChecker(0, 0, 0, 0, 0);
final String name;
final String localizedName;
private final String tooltip;
public boolean modified = false;
private final GuiButtonExt btnDrag = new GuiButtonDrag(1, 0, 0, 20, 20);
private final HoverChecker hoverCheckerBtnDrag = new HoverChecker(btnDrag, 800);
private boolean isDragging = false;
private long lastScroll = 0;
ListEntry(String name) {
this.name = name;
String nameKey = "structurelib.sortedregistry." + registryName + "." + name;
this.localizedName = trans(nameKey, name);
String tooltipKey = nameKey + ".tooltip";
String tooltip = trans(tooltipKey, null);
StringBuilder tooltipBuilder = new StringBuilder();
tooltipBuilder.append(EnumChatFormatting.GREEN);
tooltipBuilder.append(this.localizedName);
if (tooltip != null) {
tooltipBuilder.append('\n').append(EnumChatFormatting.YELLOW).append(tooltip);
}
tooltipBuilder.append('\n');
tooltipBuilder.append(EnumChatFormatting.DARK_GRAY);
tooltipBuilder.append(this.name);
this.tooltip = tooltipBuilder.toString();
}
@Override
public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, Tessellator tessellator,
int mouseX, int mouseY, boolean isSelected) {
drawOutlineBox(x, y, listWidth, slotHeight, tessellator);
drawLabel(y, slotHeight);
drawControlSet(y, slotHeight, mouseX, mouseY);
}
private void drawOutlineBox(int x, int y, int listWidth, int slotHeight, Tessellator tessellator) {
if (isDragging) {
// left x, right x, top y, bottom y
int lx = x, rx = entriesList.getScrollBarX() - 4, ty = y, by = y + slotHeight;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
tessellator.startDrawingQuads();
tessellator.setColorOpaque_I(0x808080);
tessellator.addVertexWithUV(lx - 4, by + 4, 0.0D, 0.0D, 1.0D);
tessellator.addVertexWithUV(rx + 4, by + 4, 0.0D, 1.0D, 1.0D);
tessellator.addVertexWithUV(rx + 4, ty - 4, 0.0D, 1.0D, 0.0D);
tessellator.addVertexWithUV(lx - 4, ty - 4, 0.0D, 0.0D, 0.0D);
tessellator.setColorOpaque_I(0x202020);
tessellator.addVertexWithUV(lx - 2, by + 2, 0.0D, 0.0D, 1.0D);
tessellator.addVertexWithUV(rx + 2, by + 2, 0.0D, 1.0D, 1.0D);
tessellator.addVertexWithUV(rx + 2, ty - 2, 0.0D, 1.0D, 0.0D);
tessellator.addVertexWithUV(lx - 2, ty - 2, 0.0D, 0.0D, 0.0D);
tessellator.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
}
private void drawControlSet(int y, int slotHeight, int mouseX, int mouseY) {
btnDrag.xPosition = entriesList.getControlX();
btnDrag.yPosition = y + (slotHeight - btnDrag.height) / 2;
btnDrag.drawButton(mc, mouseX, mouseY);
}
private void drawLabel(int y, int slotHeight) {
String label = modified ? EnumChatFormatting.ITALIC + localizedName : localizedName;
int allowedWidth = entriesList.getControlX() - entriesList.getLabelX() - 4;
// probably not very wise to recompute this every render tick, but it doesn't matter for now
String toDraw = trimStringToWidth(label, allowedWidth);
hoverCheckerText.updateBounds(
y + slotHeight / 2 - mc.fontRenderer.FONT_HEIGHT / 2,
y + slotHeight / 2 + mc.fontRenderer.FONT_HEIGHT / 2,
entriesList.getLabelX(),
entriesList.getLabelX() + mc.fontRenderer.getStringWidth(toDraw));
mc.fontRenderer.drawString(
toDraw,
entriesList.getLabelX(),
y + slotHeight / 2 - mc.fontRenderer.FONT_HEIGHT / 2,
getLabelColor());
}
void drawToolTip(int mouseX, int mouseY) {
// ensure checkHover() is always called, or the hover threshold might fail under certain corner cases
if (hoverCheckerText.checkHover(mouseX, mouseY)) {
GuiEditRegistryConfig.this.func_146283_a(
mc.fontRenderer.listFormattedStringToWidth(tooltip, entriesList.getListWidth()),
mouseX,
mouseY);
}
if (hoverCheckerBtnDrag.checkHover(mouseX, mouseY) && !isDragging) {
GuiEditRegistryConfig.this.func_146283_a(
mc.fontRenderer.listFormattedStringToWidth(
I18n.format("structurelib.configgui.drag.tooltip"),
entriesList.getListWidth()),
mouseX,
mouseY);
}
}
protected int getLabelColor() {
return isDragging ? 0x888888 : 0xffffff;
}
int getControlSetWidth() {
return this.btnDrag.getButtonWidth();
}
public boolean handleDrag(int index, int mouseX, int mouseY, float partialTicks) {
if (!isDragging) {
return false;
}
for (EntriesList list : lists) {
if (list == entriesList) continue;
if (mouseX > list.left && mouseX < list.right && mouseY > list.top && mouseY < list.bottom) {
int l;
if (list.entries.isEmpty()) l = 0;
else l = list.func_148124_c(mouseX, mouseY);
if (l < 0) {
if (mouseY < (list.bottom + list.top) / 2) {
l = 0;
} else {
l = list.entries.size();
}
}
entriesList.func_148143_b(true);
entriesList.entries.remove(index);
list.func_148143_b(false);
list.entries.add(l, this);
this.entriesList = list;
return true;
}
}
long now = System.currentTimeMillis();
if (now - lastScroll > 20) {
if (mouseY < entriesList.top) {
entriesList.scrollBy(-3);
lastScroll = now;
} else if (mouseY > entriesList.bottom) {
entriesList.scrollBy(3);
lastScroll = now;
}
}
int l = entriesList.func_148124_c(
MathHelper.clamp_int(mouseX, entriesList.left, entriesList.right),
MathHelper.clamp_int(mouseY, entriesList.top, entriesList.bottom));
if (l < 0 || l == index) return true;
entriesList.entries.remove(index);
entriesList.entries.add(l, this);
return true;
}
@Override
public void mouseReleased(int index, int x, int y, int mouseEvent, int relativeX, int relativeY) {
isDragging = false;
}
@Override
public boolean mousePressed(int index, int x, int y, int mouseEvent, int relativeX, int relativeY) {
if (btnDrag.mousePressed(mc, x, y)) {
isDragging = true;
return true;
}
return false;
}
}
private static String trans(String transKey, String fallback) {
String translated = I18n.format(transKey);
return translated.equals(transKey) ? fallback : translated;
}
private static class GuiButtonDrag extends GuiButtonExt {
public GuiButtonDrag(int id, int xPos, int yPos, int width, int height) {
super(id, xPos, yPos, width, height, null);
}
@Override
public void drawButton(Minecraft mc, int mouseX, int mouseY) {
if (this.visible) {
this.field_146123_n = mouseX >= this.xPosition && mouseY >= this.yPosition
&& mouseX < this.xPosition + this.width
&& mouseY < this.yPosition + this.height;
int k = this.getHoverState(this.field_146123_n);
GuiUtils.drawContinuousTexturedBox(
buttonTextures,
this.xPosition,
this.yPosition,
0,
46 + k * 20,
this.width,
this.height,
200,
20,
2,
3,
2,
2,
this.zLevel);
mc.renderEngine.bindTexture(new ResourceLocation("structurelib", "textures/gui/fourwayarrow2.png"));
int x = this.xPosition + (this.width - 12) / 2;
int y = this.yPosition + (this.height - 12) / 2;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(x, y + 12, zLevel, 0, 1);
tessellator.addVertexWithUV(x + 12, y + 12, zLevel, 1, 1);
tessellator.addVertexWithUV(x + 12, y, zLevel, 1, 0);
tessellator.addVertexWithUV(x, y, zLevel, 0, 0);
tessellator.draw();
}
}
}
}
@@ -3,21 +3,28 @@ package com.gtnewhorizon.structurelib;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.gui.EmptyContainer;
import com.gtnewhorizon.structurelib.gui.GuiScreenConfigureChannels;
import cpw.mods.fml.common.network.IGuiHandler;
public class GuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return null;
switch (ID) {
case 0:
return new EmptyContainer(player);
default:
return null;
}
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
switch (ID) {
case 0:
return new GuiScreenConfigureChannels(player.inventory.getStackInSlot(x));
return new GuiScreenConfigureChannels(new EmptyContainer(player), player.inventory.getStackInSlot(x));
default:
return null;
}
@@ -0,0 +1,77 @@
package com.gtnewhorizon.structurelib;
import java.util.List;
import net.minecraft.client.gui.GuiScreen;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.GuiConfigEntries;
import cpw.mods.fml.client.config.IConfigElement;
@SuppressWarnings({ "unchecked" })
public final class RegistryOrderEntry extends GuiConfigEntries.CategoryEntry {
public RegistryOrderEntry(GuiConfig owningScreen, GuiConfigEntries owningEntryList,
IConfigElement<?> configElement) {
super(owningScreen, owningEntryList, configElement);
}
@Override
protected GuiScreen buildChildScreen() {
List<IConfigElement<?>> childElements = this.configElement.getChildElements();
IConfigElement<?> disabled = null, order = null;
for (IConfigElement<?> e : childElements) {
if (e.getName().equals("disabled")) disabled = e;
else if (e.getName().equals("ordering")) order = e;
}
if (disabled == null || order == null) {
throw new IllegalArgumentException("Did not find expected config entires");
}
return new GuiEditRegistryConfig(
this.owningScreen,
disabled,
order,
configElement.getName(),
this.owningScreen.modID,
null,
owningScreen.allRequireWorldRestart || this.configElement.requiresWorldRestart(),
owningScreen.allRequireMcRestart || this.configElement.requiresMcRestart(),
this.owningScreen.title,
((this.owningScreen.titleLine2 == null ? "" : this.owningScreen.titleLine2) + " > " + this.name));
}
private GuiEditRegistryConfig getChildScreen() {
return (GuiEditRegistryConfig) childScreen;
}
@Override
public boolean saveConfigElement() {
GuiEditRegistryConfig c = getChildScreen();
if (c != null && c.isInitialized()) return c.saveConfigElements();
return false;
}
@Override
public boolean isChanged() {
GuiEditRegistryConfig c = getChildScreen();
return c != null && c.isInitialized() && c.isChanged();
}
@Override
public boolean isDefault() {
GuiEditRegistryConfig c = getChildScreen();
return c != null && c.isInitialized() && c.isDefault();
}
@Override
public void setToDefault() {
GuiEditRegistryConfig c = getChildScreen();
if (c != null && c.isInitialized()) c.setToDefault();
}
@Override
public void undoChanges() {
GuiEditRegistryConfig c = getChildScreen();
if (c != null && c.isInitialized()) c.undoChanges();
}
}
@@ -0,0 +1,197 @@
package com.gtnewhorizon.structurelib;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.Spliterator;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import org.apache.commons.lang3.tuple.Pair;
import com.gtnewhorizon.structurelib.net.RegistryOrderSyncMessage;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
public class SortedRegistry<V> implements Iterable<V> {
static final ConcurrentHashMap<String, WeakReference<SortedRegistry<?>>> ALL_REGISTRIES = new ConcurrentHashMap<>();
static {
RegistryOrderSyncMessage.Handler.setAllRegistries(ALL_REGISTRIES);
}
private final NavigableMap<String, V> store = new TreeMap<>();
/**
* Store stuff in an array for faster iteration access than a red black tree
*/
private List<V> baked = Collections.emptyList();
private final Map<UUID, Pair<List<String>, List<String>>> playerOrdering = new HashMap<>();
private final Map<UUID, List<V>> playerBaked = new HashMap<>();
/**
* Construct an unsynchronized registry
*/
public SortedRegistry() {}
/**
* Construct a synchronized registry whose ordering will be synced to the server
*
* @param name network name
*/
public SortedRegistry(String name) {
WeakReference<SortedRegistry<?>> oldValue = ALL_REGISTRIES.put(name, new WeakReference<>(this));
if (oldValue != null && oldValue.get() != null) {
throw new IllegalArgumentException("duplicate name");
}
FMLCommonHandler.instance().bus().register(this);
}
public static Set<String> getRegistryNames() {
return ALL_REGISTRIES.keySet();
}
public static SortedRegistry<?> getRegistry(String name) {
WeakReference<SortedRegistry<?>> ref = ALL_REGISTRIES.get(name);
return ref != null ? ref.get() : null;
}
static void cleanup(MinecraftServer server) {
List<EntityPlayerMP> players = server.getConfigurationManager().playerEntityList;
Set<UUID> onlinePlayerIDs = players.stream().map(EntityPlayerMP::getUniqueID).collect(Collectors.toSet());
int removed = 0;
for (WeakReference<SortedRegistry<?>> ref : ALL_REGISTRIES.values()) {
SortedRegistry<?> registry = ref.get();
if (registry == null) continue;
for (Iterator<UUID> iterator = registry.playerOrdering.keySet().iterator(); iterator.hasNext();) {
UUID uuid = iterator.next();
if (!onlinePlayerIDs.contains(uuid)) {
iterator.remove();
registry.playerBaked.remove(uuid);
removed++;
}
}
}
if (removed > 0) {
StructureLib.LOGGER.debug("Removed {} registry record for logged out players", removed);
}
}
@SubscribeEvent
public void onPlayerLogOut(PlayerEvent.PlayerLoggedOutEvent e) {
playerOrdering.remove(e.player.getUniqueID());
playerBaked.remove(e.player.getUniqueID());
}
public void register(String key, V val) {
if (key == null || val == null) throw new NullPointerException();
V old = store.putIfAbsent(key, val);
if (old != null) {
throw new IllegalArgumentException("Duplicate key: " + key);
}
baked = new ArrayList<>(store.values());
for (Map.Entry<UUID, Pair<List<String>, List<String>>> e : playerOrdering.entrySet()) {
makePlayerBaked(e.getKey(), e.getValue().getKey(), e.getValue().getValue());
}
}
public void registerOrdering(EntityPlayerMP player, List<String> ordering, List<String> disabled) {
registerOrdering(player.getUniqueID(), ordering, disabled);
}
public void registerOrdering(UUID playerID, List<String> ordering, List<String> disabled) {
playerOrdering.put(playerID, Pair.of(ordering, disabled));
makePlayerBaked(playerID, ordering, disabled);
}
private void makePlayerBaked(UUID player, List<String> ordering, List<String> disabled) {
TreeMap<String, V> copy = new TreeMap<>(store);
for (String s : disabled) {
copy.remove(s);
}
List<V> b = new ArrayList<>();
for (String k : ordering) {
V v = copy.remove(k);
if (v != null) {
b.add(v);
}
}
b.addAll(copy.values());
playerBaked.put(player, b);
}
public int size() {
return store.size();
}
public boolean isEmpty() {
return store.isEmpty();
}
public boolean containsKey(String key) {
return store.containsKey(key);
}
public boolean containsValue(V value) {
return store.containsValue(value);
}
public V get(String key) {
return store.get(key);
}
public Iterable<V> getPlayerOrdering(@Nullable EntityPlayerMP player) {
if (player == null) return baked;
List<V> playerPreference = playerBaked.get(player.getUniqueID());
if (playerPreference == null) return baked;
return playerPreference;
}
public Stream<String> getPlayerOrderingKeys(@Nullable EntityPlayerMP player) {
if (player == null) return store.keySet().stream();
List<V> playerOrder = playerBaked.get(player.getUniqueID());
if (playerOrder == null) return store.keySet().stream();
// rebuild the order from the baked map
Map<V, String> reverseMap = new IdentityHashMap<>();
store.forEach((k, v) -> reverseMap.put(v, k));
return playerOrder.stream().map(reverseMap::get);
}
Iterable<String> getCurrentOrdering() {
return store.keySet();
}
@Override
public Iterator<V> iterator() {
return baked.iterator();
}
@Override
public void forEach(Consumer<? super V> action) {
baked.forEach(action);
}
@Override
public Spliterator<V> spliterator() {
return baked.spliterator();
}
}
@@ -4,6 +4,7 @@ import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import com.gtnewhorizon.structurelib.structure.IStructureElement;
import cpw.mods.fml.common.eventhandler.Event;
/**
@@ -1,29 +1,46 @@
package com.gtnewhorizon.structurelib;
import static com.gtnewhorizon.structurelib.StructureLibAPI.CHANNEL_SHOW_ERROR;
import static com.gtnewhorizon.structurelib.StructureLibAPI.MOD_ID;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizon.structurelib.block.BlockHint;
import com.gtnewhorizon.structurelib.command.CommandConfigureChannels;
import com.gtnewhorizon.structurelib.command.CommandRegistryDebug;
import com.gtnewhorizon.structurelib.fluid.FluidPlacementRegistry;
import com.gtnewhorizon.structurelib.fluid.FluidSourceProviders;
import com.gtnewhorizon.structurelib.fluid.FluidStackExtractors;
import com.gtnewhorizon.structurelib.item.ItemBlockHint;
import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger;
import com.gtnewhorizon.structurelib.item.ItemFrontRotationTool;
import com.gtnewhorizon.structurelib.net.AlignmentMessage;
import com.gtnewhorizon.structurelib.net.ErrorHintParticleMessage;
import com.gtnewhorizon.structurelib.net.RegistryOrderSyncMessage;
import com.gtnewhorizon.structurelib.net.SetChannelDataMessage;
import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage;
import com.gtnewhorizon.structurelib.util.InventoryUtility;
import com.gtnewhorizon.structurelib.util.XSTR;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
@@ -36,9 +53,9 @@ import cpw.mods.fml.relauncher.SideOnly;
* This class does not contain a stable API. Refrain from using this class.
*/
@Mod(
modid = StructureLibAPI.MOD_ID,
modid = MOD_ID,
name = "StructureLib",
version = "GRADLETOKEN_VERSION",
version = Tags.VERSION,
acceptableRemoteVersions = "*",
guiFactory = "com.gtnewhorizon.structurelib.GuiFactory")
public class StructureLib {
@@ -53,7 +70,7 @@ public class StructureLib {
clientSide = "com.gtnewhorizon.structurelib.ClientProxy")
static CommonProxy proxy;
static final SimpleNetworkWrapper net = NetworkRegistry.INSTANCE.newSimpleChannel(StructureLibAPI.MOD_ID);
static final SimpleNetworkWrapper net = NetworkRegistry.INSTANCE.newSimpleChannel(MOD_ID);
static {
net.registerMessage(
@@ -65,6 +82,7 @@ public class StructureLib {
net.registerMessage(UpdateHintParticleMessage.Handler.class, UpdateHintParticleMessage.class, 2, Side.CLIENT);
net.registerMessage(SetChannelDataMessage.Handler.class, SetChannelDataMessage.class, 3, Side.SERVER);
net.registerMessage(ErrorHintParticleMessage.Handler.class, ErrorHintParticleMessage.class, 4, Side.CLIENT);
net.registerMessage(RegistryOrderSyncMessage.Handler.class, RegistryOrderSyncMessage.class, 5, Side.SERVER);
try {
DEBUG_MODE = Boolean.parseBoolean(System.getProperty("structurelib.debug"));
@@ -79,7 +97,7 @@ public class StructureLib {
@Mod.Instance
static StructureLib INSTANCE;
@Mod.Instance(STRUCTURECOMPAT_MODID)
static Object COMPAT;
static Block blockHint;
@@ -97,6 +115,10 @@ public class StructureLib {
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent e) {
InventoryUtility.init();
FluidStackExtractors.init();
FluidSourceProviders.init();
FluidPlacementRegistry.init();
ConfigurationHandler.INSTANCE.init(e.getSuggestedConfigurationFile());
GameRegistry.registerBlock(blockHint = new BlockHint(), ItemBlockHint.class, "blockhint");
itemBlockHint = ItemBlock.getItemFromBlock(StructureLibAPI.getBlockHint());
@@ -109,14 +131,104 @@ public class StructureLib {
proxy.preInit(e);
NetworkRegistry.INSTANCE.registerGuiHandler(instance(), new GuiHandler());
if (Loader.isModLoaded(STRUCTURECOMPAT_MODID)) {
COMPAT = Loader.instance().getIndexedModList().get(STRUCTURECOMPAT_MODID).getMod();
}
ChannelDescription.set(CHANNEL_SHOW_ERROR, MOD_ID, "channels.structurelib.show_errors");
DevelopHelper.onPreInit();
}
@Mod.EventHandler
public void loadComplete(FMLLoadCompleteEvent e) {
proxy.loadComplete(e);
}
@Mod.EventHandler
public void serverStarting(FMLServerStartingEvent e) {
e.registerServerCommand(new CommandConfigureChannels());
e.registerServerCommand(new CommandRegistryDebug());
}
@Mod.EventHandler
public void handleIMC(FMLInterModComms.IMCEvent event) {
for (FMLInterModComms.IMCMessage message : event.getMessages()) {
switch (message.key) {
case "register_channel":
processRegisterChannel(message);
break;
case "register_channel_item":
processRegisterChannelItem(message);
break;
case "register_fluid_block_cost":
processRegisterFluidBlockCost(message);
break;
}
}
}
/**
* Teach StructureLib what it costs to place a fluid block, without having to link against StructureLib.
* <p>
* The message must hold a compound with {@code Block} (registry name), {@code Fluid} (fluid name), optionally
* {@code Meta} (default 0), {@code Amount} (default one bucket) and {@code ForceFluid} (default false).
*/
private void processRegisterFluidBlockCost(FMLInterModComms.IMCMessage message) {
if (!message.isNBTMessage()) {
LOGGER.warn("{} sent a register_fluid_block_cost message without any data", message.getSender());
return;
}
NBTTagCompound tag = message.getNBTValue();
String blockName = tag.getString("Block");
String fluidName = tag.getString("Fluid");
Object block = Block.blockRegistry.getObject(blockName);
Fluid fluid = FluidRegistry.getFluid(fluidName);
if (!(block instanceof Block)) {
LOGGER.warn("{} tried to register a fluid block cost for unknown block {}", message.getSender(), blockName);
return;
}
if (fluid == null) {
LOGGER.warn("{} tried to register a fluid block cost for unknown fluid {}", message.getSender(), fluidName);
return;
}
int meta = tag.getInteger("Meta");
int amount = tag.hasKey("Amount") ? tag.getInteger("Amount") : FluidPlacementRegistry.DEFAULT_FLUID_AMOUNT;
boolean forceFluid = tag.getBoolean("ForceFluid");
try {
FluidPlacementRegistry.register((Block) block, meta, new FluidStack(fluid, amount), forceFluid);
} catch (IllegalArgumentException e) {
// never let a badly formed message from another mod break the game
LOGGER.warn(
"{} tried to register a fluid block cost for {}:{} twice",
message.getSender(),
blockName,
meta);
}
}
private void processRegisterChannel(FMLInterModComms.IMCMessage message) {
NBTTagList tags = message.getNBTValue().getTagList("Channels", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tags.tagCount(); i++) {
NBTTagCompound tag = tags.getCompoundTagAt(i);
StructureLibAPI.registerChannelDescription(
tag.getString("Channel"),
message.getSender(),
tag.getString("Description"));
}
}
private void processRegisterChannelItem(FMLInterModComms.IMCMessage message) {
NBTTagList items = message.getNBTValue().getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < items.tagCount(); i++) {
NBTTagCompound itemTag = items.getCompoundTagAt(i);
ItemStack item = ItemStack.loadItemStackFromNBT(itemTag.getCompoundTag("Item"));
NBTTagList tags = itemTag.getTagList("Channels", Constants.NBT.TAG_COMPOUND);
for (int j = 0; j < tags.tagCount(); j++) {
NBTTagCompound tag = tags.getCompoundTagAt(j);
StructureLibAPI.registerChannelItem(
tag.getString("Channel"),
message.getSender(),
tag.getInteger("Value"),
item);
}
}
}
public static void addClientSideChatMessages(String... messages) {
@@ -2,6 +2,8 @@ package com.gtnewhorizon.structurelib;
import static com.gtnewhorizon.structurelib.StructureLib.proxy;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -10,13 +12,23 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import com.gtnewhorizon.gtnhlib.util.AnimatedTooltipHandler;
import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.IAlignmentProvider;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.fluid.FluidBlockPlacement;
import com.gtnewhorizon.structurelib.fluid.FluidBlockPlacer;
import com.gtnewhorizon.structurelib.fluid.FluidPlacementRegistry;
import com.gtnewhorizon.structurelib.fluid.FluidSourceProviders;
import com.gtnewhorizon.structurelib.fluid.FluidStackExtractor;
import com.gtnewhorizon.structurelib.fluid.FluidStackExtractors;
import com.gtnewhorizon.structurelib.fluid.IFluidSourceProvider;
import com.gtnewhorizon.structurelib.net.AlignmentMessage;
import com.gtnewhorizon.structurelib.structure.AutoPlaceEnvironment;
import com.gtnewhorizon.structurelib.structure.IStructureDefinition;
import cpw.mods.fml.common.network.NetworkRegistry;
/**
@@ -42,6 +54,7 @@ public class StructureLibAPI {
public static final int HINT_BLOCK_META_AIR = 13;
public static final int HINT_BLOCK_META_NOT_AIR = 14;
public static final int HINT_BLOCK_META_ERROR = 15;
public static final String CHANNEL_SHOW_ERROR = "show_error";
static final ThreadLocal<Object> instrument = new ThreadLocal<>();
/**
@@ -71,7 +84,7 @@ public class StructureLibAPI {
*/
public static void enableInstrument(Object identifier) {
if (isInstrumentEnabled()) throw new IllegalStateException();
instrument.set(instrument);
instrument.set(identifier);
}
/**
@@ -317,6 +330,26 @@ public class StructureLibAPI {
return block.isAir(w, x, y, z) || block.isReplaceable(w, x, y, z);
}
/**
* Put back the block that was at a position, which is what a placement that could not be paid for should roll back
* to.
* <p>
* Restoring the previous state instead of clearing the position matters whenever the position held something
* autoplace is allowed to replace, e.g. a fluid that is not a source block: the player would otherwise be left with
* a hole where their fluid used to be.
*
* @param world world to write to
* @param x x coord
* @param y y coord
* @param z z coord
* @param block the block that was there, or null for air
* @param meta the meta that was there
*/
public static void restoreBlock(World world, int x, int y, int z, @Nullable Block block, int meta) {
if (block == null || block.isAir(world, x, y, z)) world.setBlockToAir(x, y, z);
else world.setBlock(x, y, z, block, meta, 3);
}
/**
* Send chat to player, but throttled.
*
@@ -349,4 +382,167 @@ public class StructureLibAPI {
short intervalRequired, boolean forceUpdateLastSend) {
proxy.addThrottledChat(throttleKey, player, text, intervalRequired, forceUpdateLastSend);
}
/**
* Register a channel description here. The description should describe how a channel will be used inside your mod.
*
* @param channel channel key
* @param modid your modid
* @param description localization key for your description
*/
public static void registerChannelDescription(final String channel, final String modid, final String description) {
ChannelDescription.set(channel, modid, description);
}
/**
* Register what it costs to place a fluid block, and how to place it.
* <p>
* Water and lava are registered by default, and every Forge fluid block is recognised automatically, so this is
* only needed for a fluid block that costs something else than one bucket, for a fluid block that has to be written
* into the world in a special way, or for a block that has an item form but should always be paid for with fluid.
*
* @param block the fluid block
* @param meta the block meta. {@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE} covers every
* meta of this block.
* @param placement what this block state costs and how to place it
*/
public static void registerFluidBlockCost(Block block, int meta, FluidBlockPlacement placement) {
FluidPlacementRegistry.register(block, meta, placement);
}
/**
* Register what it costs to place a fluid block, preferring the item form when the block has one.
*
* @param block the fluid block
* @param meta the block meta
* @param cost how much fluid one block of this state costs
* @see #registerFluidBlockCost(Block, int, FluidBlockPlacement)
*/
public static void registerFluidBlockCost(Block block, int meta, FluidStack cost) {
FluidPlacementRegistry.register(block, meta, cost);
}
/**
* Register what it costs to place a fluid block.
*
* @param block the fluid block
* @param meta the block meta
* @param cost how much fluid one block of this state costs
* @param forceFluid whether to always pay with fluid, even when this block also has an item form
* @see #registerFluidBlockCost(Block, int, FluidBlockPlacement)
*/
public static void registerFluidBlockCost(Block block, int meta, FluidStack cost, boolean forceFluid) {
FluidPlacementRegistry.register(block, meta, cost, forceFluid);
}
/**
* Register what it costs to place a fluid block, with {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of the
* fluid the block holds, preferring the item form when the block has one.
* <p>
* The amount is the whole cost of that state, so a block whose meta says how full it is wants one registration per
* meta it can be in, or no registration at all, in which case the default amount is scaled down for a partially
* filled position.
*
* @param block the fluid block
* @param meta the block meta. {@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE} covers every meta of
* this block.
* @throws IllegalArgumentException if the block holds no fluid, or this state is already registered
* @see #registerFluidBlockCost(Block, int, FluidBlockPlacement)
*/
public static void registerFluidBlockCost(Block block, int meta) {
FluidPlacementRegistry.register(block, meta);
}
/**
* Register what it costs to place a fluid block, with {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of the
* fluid the block holds.
*
* @param block the fluid block
* @param meta the block meta. {@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE} covers every
* meta of this block.
* @param forceFluid whether to always pay with fluid, even when this block also has an item form
* @see #registerFluidBlockCost(Block, int)
*/
public static void registerFluidBlockCost(Block block, int meta, boolean forceFluid) {
FluidPlacementRegistry.register(block, meta, forceFluid);
}
/**
* Register the whole block, i.e. every meta of it that has no registration of its own, with
* {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of the fluid it holds.
*
* @param block the fluid block
* @see #registerFluidBlockCost(Block, int)
*/
public static void registerFluidBlockCost(Block block) {
FluidPlacementRegistry.register(block);
}
/**
* Register what it costs to place a fluid block, with {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of the
* fluid the block holds, and placed the way the given placer says.
* <p>
* Use this for a fluid block that cannot be placed with a plain block set, e.g. one that has to be filled through
* its own API.
*
* @param block the fluid block
* @param meta the block meta. {@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE} covers every meta
* of this block.
* @param placer how to write the block into the world
* @see #registerFluidBlockCost(Block, int, FluidBlockPlacement)
*/
public static void registerFluidBlockCost(Block block, int meta, FluidBlockPlacer placer) {
FluidPlacementRegistry.register(block, meta, placer);
}
/**
* Register a way to pull fluid out of an item, so that autoplace can pay for a fluid block with it.
* <p>
* Forge's fluid container item and Forge's fluid container registry are both supported out of the box, which covers
* buckets and most modded cells. Register your own extractor for a container that exposes its fluid by other means.
*
* @param key unique key. Matches the key shown in the config gui.
* @param extractor the extractor
*/
public static void registerFluidStackExtractor(String key, FluidStackExtractor extractor) {
FluidStackExtractors.register(key, extractor);
}
/**
* Register a way to hand StructureLib fluid without the player having to carry a fluid container, e.g. the ME
* network behind a wireless terminal the player has on them.
* <p>
* Providers are asked before the fluid containers the player is carrying, in the order the player configured, so
* the player can reorder or disable every provider in StructureLib's config. A provider should look up what it
* drains from every time it is asked for fluid rather than when it is created, as the player can walk out of range
* or put a terminal away between two rounds of autoplace.
*
* @param key unique key. Matches the key shown in the config gui.
* @param provider the provider
*/
public static void registerFluidSourceProvider(String key, IFluidSourceProvider provider) {
FluidSourceProviders.register(key, provider);
}
/**
* Register an item stack as an indicator for a (channel, value) pair.
*
* @param channel channel key
* @param modid your modid
* @param channelValue value
* @param stack item stack. having a metadata of
* {@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE} will match without comparing
* NBT or metadata value. having a tag with {@code tag.getBoolean("*") == true} will match
* without comparing NBT.
*/
public static void registerChannelItem(final String channel, final String modid, final int channelValue,
final ItemStack stack) {
ChannelDescription.item(channel, channelValue, stack);
AnimatedTooltipHandler.addItemTooltip(
stack,
AnimatedTooltipHandler.translatedText("structurelib.tooltip.channelvalue", channelValue, channel));
AnimatedTooltipHandler.addItemTooltip(
stack,
AnimatedTooltipHandler.translatedText("structurelib.tooltip.indicator_dnd", channelValue, channel));
}
}
@@ -190,4 +190,28 @@ public interface IAlignment extends IAlignmentLimits, IAlignmentProvider {
return getAlignmentLimits()
.isNewExtendedFacingValid(alignment.getDirection(), alignment.getRotation(), alignment.getFlip());
}
/**
* Check if this object support a flip change, assuming both direction and rotation is not changed.
*/
default boolean isFlipChangeAllowed() {
ExtendedFacing facing = getExtendedFacing();
for (Flip flip : Flip.VALUES) {
if (flip == getFlip()) continue;
if (isNewExtendedFacingValid(facing.with(flip))) return true;
}
return false;
}
/**
* Check if this object support a rotation change, assuming both direction and flip is not changed.
*/
default boolean isRotationChangeAllowed() {
ExtendedFacing facing = getExtendedFacing();
for (Rotation rotation : Rotation.VALUES) {
if (rotation == getRotation()) continue;
if (isNewExtendedFacingValid(facing.with(rotation))) return true;
}
return false;
}
}
@@ -14,8 +14,28 @@ import com.gtnewhorizon.structurelib.alignment.enumerable.Rotation;
public interface IAlignmentLimits {
/**
* Can be placed in any orientation.
*/
IAlignmentLimits UNLIMITED = (direction, rotation, flip) -> true;
/**
* Must be standing upright; i.e., top side of the block facing up.
*/
IAlignmentLimits UPRIGHT = (direction, rotation, flip) -> direction.offsetY == 0
&& (flip.isVerticallyFliped() ? rotation.isUpsideDown() : rotation.isNotRotated());
/**
* Can be in any orientation except upside down; i.e., top side of the block facing down.
*/
IAlignmentLimits NOT_UPSIDE_DOWN = (direction, rotation, flip) -> direction.offsetY != 0
|| (flip.isVerticallyFliped() ? !rotation.isNotRotated() : !rotation.isUpsideDown());
/**
* Front side of the block must be facing up.
*/
IAlignmentLimits FACING_UP = (direction, rotation, flip) -> direction == ForgeDirection.UP;
boolean isNewExtendedFacingValid(ForgeDirection direction, Rotation rotation, Flip flip);
default boolean isNewExtendedFacingValid(ExtendedFacing alignment) {
@@ -16,6 +16,7 @@ import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.fluid.FluidSourceProviders;
import com.gtnewhorizon.structurelib.structure.IItemSource;
import com.gtnewhorizon.structurelib.structure.ISurvivalBuildEnvironment;
@@ -70,8 +71,7 @@ public class ConstructableUtility {
if (constructable == null) return false;
if (aPlayer instanceof EntityPlayerMP) {
EntityPlayerMP playerMP = (EntityPlayerMP) aPlayer;
if (aPlayer instanceof EntityPlayerMP playerMP) {
// server side and sneaking (already checked above)
// do construct
if (aPlayer.capabilities.isCreativeMode) {
@@ -80,7 +80,13 @@ public class ConstructableUtility {
int built = ((ISurvivalConstructable) constructable).survivalConstruct(
aStack,
ConfigurationHandler.INSTANCE.getAutoPlaceBudget(),
ISurvivalBuildEnvironment.create(IItemSource.fromPlayer(playerMP), playerMP));
ISurvivalBuildEnvironment.create(
IItemSource.fromPlayer(playerMP),
// What the player can offer: every registered fluid source provider, e.g. the ME
// network
// behind a wireless terminal they have on them, and then the fluid they are carrying.
FluidSourceProviders.getSourceFor(playerMP),
playerMP));
if (built > 0) {
playerMP.addChatMessage(new ChatComponentTranslation("structurelib.autoplace.built_stat", built));
} else if (built == -1) {
@@ -8,7 +8,9 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.AutoPlaceEnvironment;
import com.gtnewhorizon.structurelib.structure.IItemSource;
import com.gtnewhorizon.structurelib.structure.ISurvivalBuildEnvironment;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@@ -41,24 +43,35 @@ public interface IMultiblockInfoContainer<T> {
/**
* Construct the structure using
* {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, IItemSource, EntityPlayerMP, java.util.function.Consumer)}
*
* {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
*
* @return -1 if done, a helping pointer
*/
default int survivalConstruct(ItemStack stackSize, int elementBudge, IItemSource source,
EntityPlayerMP actorProfile, T tileEntity, ExtendedFacing aSide) {
return -1;
}
int survivalConstruct(ItemStack stackSize, int elementBudge, ISurvivalBuildEnvironment env, T tileEntity,
ExtendedFacing aSide);
@SideOnly(Side.CLIENT)
String[] getDescription(ItemStack stackSize);
/**
* Override this and return {@link #toConstructable(IMultiblockInfoContainer, Object, ExtendedFacing)} if
* {@link #survivalConstruct(ItemStack, int, IItemSource, EntityPlayerMP, Object, ExtendedFacing)} isn't a stub
*/
default IConstructable toConstructable(T tileEntity, ExtendedFacing aSide) {
return new IConstructable() {
default ISurvivalConstructable toConstructable(T tileEntity, ExtendedFacing aSide) {
return new ISurvivalConstructable() {
@Override
public int survivalConstruct(ItemStack stackSize, int elementBudget, ISurvivalBuildEnvironment env) {
return IMultiblockInfoContainer.this
.survivalConstruct(stackSize, elementBudget, env, tileEntity, aSide);
}
@Override
public int survivalConstruct(ItemStack stackSize, int elementBudget, IItemSource source,
EntityPlayerMP actor) {
return IMultiblockInfoContainer.this.survivalConstruct(
stackSize,
elementBudget,
ISurvivalBuildEnvironment.create(source, actor),
tileEntity,
aSide);
}
@Override
public void construct(ItemStack stackSize, boolean hintsOnly) {
@@ -71,26 +84,4 @@ public interface IMultiblockInfoContainer<T> {
}
};
}
static <T> ISurvivalConstructable toConstructable(IMultiblockInfoContainer<T> thiz, T tileEntity,
ExtendedFacing aSide) {
return new ISurvivalConstructable() {
@Override
public int survivalConstruct(ItemStack stackSize, int elementBudget, IItemSource source,
EntityPlayerMP actor) {
return thiz.survivalConstruct(stackSize, elementBudget, source, actor, tileEntity, aSide);
}
@Override
public void construct(ItemStack stackSize, boolean hintsOnly) {
thiz.construct(stackSize, hintsOnly, tileEntity, aSide);
}
@Override
public String[] getStructureDescription(ItemStack stackSize) {
return thiz.getDescription(stackSize);
}
};
}
}
@@ -4,9 +4,18 @@ import static com.gtnewhorizon.structurelib.alignment.IAlignment.FLIPS_COUNT;
import static com.gtnewhorizon.structurelib.alignment.IAlignment.ROTATIONS_COUNT;
import static java.lang.Math.abs;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.*;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import java.util.*;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
@@ -50,6 +50,10 @@ public class BlockHint extends Block {
@Override
public IIcon getIcon(int aSide, int aMeta) {
// For numbered hints, top and bottom are blank
if (aSide <= 1 && aMeta <= 11) {
return hint[13];
}
return hint[aMeta];
}
@@ -61,10 +65,9 @@ public class BlockHint extends Block {
}
@Override
@SuppressWarnings("unchecked")
public void getSubBlocks(Item aItem, CreativeTabs par2CreativeTabs, List aList) {
public void getSubBlocks(Item item, CreativeTabs tab, List<ItemStack> list) {
for (int i = 0; i <= 15; i++) {
aList.add(new ItemStack(aItem, 1, i));
list.add(new ItemStack(item, 1, i));
}
}
}
@@ -35,7 +35,7 @@ public class CommandConfigureChannels extends CommandBase {
}
@Override
public List<?> addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_) {
public List<String> addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_) {
if (p_71516_2_.length == 1)
return getListOfStringsMatchingLastWord(p_71516_2_, "get", "set", "unset", "wipe", "getall");
return null;
@@ -45,9 +45,7 @@ public class CommandConfigureChannels extends CommandBase {
public void processCommand(ICommandSender sender, String[] args) {
if (args.length == 0) throw new WrongUsageException(getCommandUsage(sender));
if (!(sender instanceof EntityPlayerMP)) throw new WrongUsageException("must be a player");
EntityPlayerMP player = (EntityPlayerMP) sender;
if (!(sender instanceof EntityPlayerMP player)) throw new WrongUsageException("must be a player");
ItemStack heldItem = player.getHeldItem();
if (heldItem == null || !(heldItem.getItem() instanceof ItemConstructableTrigger)) {
@@ -0,0 +1,50 @@
package com.gtnewhorizon.structurelib.command;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ChatComponentText;
import com.gtnewhorizon.structurelib.SortedRegistry;
public class CommandRegistryDebug extends CommandBase {
@Override
public String getCommandName() {
return "sl_registry_debug";
}
@Override
public String getCommandUsage(ICommandSender p_71518_1_) {
return "/sl_registry_debug <registry name>";
}
@Override
public int getRequiredPermissionLevel() {
return 0;
}
@Override
public List<String> addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_) {
if (p_71516_2_.length == 1) return getListOfStringsMatchingLastWord(
p_71516_2_,
SortedRegistry.getRegistryNames().toArray(new String[0]));
return null;
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length != 1) throw new WrongUsageException(getCommandUsage(sender));
if (!(sender instanceof EntityPlayerMP player)) throw new WrongUsageException("must be a player");
SortedRegistry<?> registry = SortedRegistry.getRegistry(args[0]);
if (registry == null) throw new WrongUsageException("registry not found");
player.addChatMessage(new ChatComponentText("Current order:"));
registry.getPlayerOrderingKeys(player).map(ChatComponentText::new).forEach(player::addChatMessage);
}
}
@@ -0,0 +1,49 @@
package com.gtnewhorizon.structurelib.core;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.gtnewhorizon.gtnhmixins.IEarlyMixinLoader;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
@IFMLLoadingPlugin.MCVersion("1.7.10")
public class StructureLibCore implements IFMLLoadingPlugin, IEarlyMixinLoader {
@Override
public String[] getASMTransformerClass() {
return null;
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {
}
@Override
public String getAccessTransformerClass() {
return null;
}
@Override
public String getMixinConfig() {
return "mixins.structurelib.early.json";
}
@Override
public List<String> getMixins(Set<String> loadedCoreMods) {
return Arrays.asList("blockChangeNotifier.MixinForgeHooks", "blockChangeNotifier.MixinWorld");
}
}
@@ -0,0 +1,11 @@
package com.gtnewhorizon.structurelib.event;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
public interface BlockChangeListener {
void onBlockChange(World world, Chunk chunk, int x, int y, int z, Block oldBlock, Block newBlock, int oldMeta,
int newMeta);
}
@@ -0,0 +1,33 @@
package com.gtnewhorizon.structurelib.event;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
@SuppressWarnings("ForLoopReplaceableByForEach")
public class BlockChangeNotifier {
private static final List<BlockChangeListener> listeners = new ArrayList<>();
public static synchronized void addListener(BlockChangeListener listener) {
listeners.add(listener);
}
public static void onBlockChange(World world, Chunk chunk, int x, int y, int z, Block oldBlock, Block newBlock,
int oldMeta, int newMeta) {
if (oldBlock == newBlock && oldMeta == newMeta) return;
if (chunk == null) {
chunk = world.getChunkFromBlockCoords(x, z);
}
final int numListeners = listeners.size();
for (int i = 0; i < numListeners; i++) {
final BlockChangeListener listener = listeners.get(i);
listener.onBlockChange(world, chunk, x, y, z, oldBlock, newBlock, oldMeta, newMeta);
}
}
}
@@ -0,0 +1,66 @@
package com.gtnewhorizon.structurelib.fluid;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraftforge.fluids.BlockFluidFinite;
import net.minecraftforge.fluids.IFluidBlock;
/**
* Measure how much fluid a block in the world holds.
* <p>
* Fluid blocks disagree on what their meta means. A vanilla style liquid counts down as it thins out, some modded
* fluids count up instead, and a Forge fluid block can report its own fill. These helpers hide that difference, which
* is what allows autoplace to charge only for the fluid that is actually missing from a position.
*/
public class FluidAmounts {
private FluidAmounts() {}
/**
* How much fluid a block of given meta holds, assuming it is a fluid block whose meta encodes a level.
* <p>
* Blocks implementing Forge's {@code IFluidBlock} answer this themselves once they are in the world, so this is
* only used to derive a cost for a state that is not in the world yet.
*
* @param block the fluid block. Must not be null.
* @param meta the meta to interpret
* @param fullAmount how much fluid a full block of this fluid holds
* @return amount of fluid, between 0 and {@code fullAmount} inclusive
*/
public static int getAmountForMeta(Block block, int meta, int fullAmount) {
if (block == null) throw new IllegalArgumentException();
int level = meta & 7;
// A finite fluid counts up: meta 0 is the thinnest state, meta 7 is a full block.
if (block instanceof BlockFluidFinite) return fullAmount * (level + 1) / 8;
// Everything else counts down: meta 0 is a source block, meta 7 is the thinnest state.
return fullAmount * (8 - level) / 8;
}
/**
* How full the block at given position is, as a fraction of a full block.
*
* @return a fraction between 0 and 1 inclusive. 0 when the position does not hold a fluid block.
*/
public static float getStoredFraction(World world, int x, int y, int z) {
Block block = world.getBlock(x, y, z);
if (block == null) return 0;
if (block instanceof IFluidBlock fluidBlock) {
// A negative percentage means the block fills from the top down. Only its magnitude is interesting here.
return Math.min(1f, Math.abs(fluidBlock.getFilledPercentage(world, x, y, z)));
}
if (block.getMaterial() != null && block.getMaterial().isLiquid()) {
return getAmountForMeta(block, world.getBlockMetadata(x, y, z), 8) / 8f;
}
return 0;
}
/**
* How much fluid the block at given position holds.
*
* @param capacity how much fluid a full block of this kind holds, i.e. the amount to scale the fill fraction by
* @return amount of fluid, between 0 and {@code capacity} inclusive
*/
public static int getStoredAmount(World world, int x, int y, int z, int capacity) {
return Math.round(getStoredFraction(world, x, y, z) * capacity);
}
}
@@ -0,0 +1,104 @@
package com.gtnewhorizon.structurelib.fluid;
import javax.annotation.Nullable;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import com.github.bsideup.jabel.Desugar;
/**
* How a specific block state is placed by autoplace: what fluid it costs, and how to write it into the world.
* <p>
* Register one of these through {@link FluidPlacementRegistry} to teach StructureLib about a fluid block that it cannot
* figure out on its own, e.g. a fluid block that stores its fluid somewhere else, or one whose fluid cost is not the
* default bucket.
*
* @param cost the fluid that has to be paid for one block of this state. Must hold a fluid and a positive amount.
* @param forceFluid whether to always pay with fluid, even when this block also has an item form. When false, the item
* form is preferred, which keeps the behaviour of existing multiblocks unchanged.
* @param placer how to actually place the block, or null to place it with a plain block set
*/
@Desugar
public record FluidBlockPlacement(FluidStack cost, boolean forceFluid, @Nullable FluidBlockPlacer placer) {
public FluidBlockPlacement {
if (cost == null || cost.getFluid() == null) throw new IllegalArgumentException("cost must hold a fluid");
if (cost.amount <= 0) throw new IllegalArgumentException("cost must have a positive amount");
}
/**
* A placement that pays with given fluid, prefers the item form when there is one, and places the block directly.
*/
public static FluidBlockPlacement of(FluidStack cost) {
return new FluidBlockPlacement(cost, false, null);
}
/**
* A placement that pays with given fluid, and always pays with fluid even when the block has an item form.
*/
public static FluidBlockPlacement forced(FluidStack cost) {
return new FluidBlockPlacement(cost, true, null);
}
/**
* A placement that pays {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of given fluid, prefers the item form
* when there is one, and places the block directly.
*/
public static FluidBlockPlacement of(Fluid fluid) {
return of(defaultCost(fluid));
}
/**
* A placement that pays {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of given fluid, and always pays with
* fluid even when the block has an item form.
*/
public static FluidBlockPlacement forced(Fluid fluid) {
return forced(defaultCost(fluid));
}
/**
* A placement that pays with given fluid, and writes the block into the world the way the given placer says.
* <p>
* Use this for a fluid block that cannot be placed with a plain block set, e.g. one that has to be filled through
* its own API.
*/
public static FluidBlockPlacement of(FluidStack cost, @Nullable FluidBlockPlacer placer) {
return new FluidBlockPlacement(cost, false, placer);
}
/**
* A placement that pays with given fluid, always pays with fluid, and writes the block into the world the way the
* given placer says.
*/
public static FluidBlockPlacement forced(FluidStack cost, @Nullable FluidBlockPlacer placer) {
return new FluidBlockPlacement(cost, true, placer);
}
/**
* A placement that pays {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of given fluid, and writes the block
* into the world the way the given placer says.
*/
public static FluidBlockPlacement of(Fluid fluid, @Nullable FluidBlockPlacer placer) {
return of(defaultCost(fluid), placer);
}
/**
* A placement that pays {@link FluidPlacementRegistry#DEFAULT_FLUID_AMOUNT} of given fluid, always pays with fluid,
* and writes the block into the world the way the given placer says.
*/
public static FluidBlockPlacement forced(Fluid fluid, @Nullable FluidBlockPlacer placer) {
return forced(defaultCost(fluid), placer);
}
/**
* What one block of given fluid costs unless something else was registered for it, which is one bucket.
*
* @param fluid the fluid to pay with
* @throws IllegalArgumentException if the fluid is null
*/
public static FluidStack defaultCost(Fluid fluid) {
if (fluid == null) throw new IllegalArgumentException("fluid must not be null");
return new FluidStack(fluid, FluidPlacementRegistry.DEFAULT_FLUID_AMOUNT);
}
}
@@ -0,0 +1,30 @@
package com.gtnewhorizon.structurelib.fluid;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
/**
* Put a fluid block into the world.
* <p>
* The default implementation used by StructureLib is a plain {@code world.setBlock(x, y, z, block, meta, 2)}, which is
* what every vanilla and Forge fluid block expects. Register a custom placer for a fluid block that needs more than
* that, e.g. one that keeps its fluid inside a tile entity.
*/
public interface FluidBlockPlacer {
/**
* Place the fluid block.
*
* @param world world to place in. Never a client side world.
* @param x x coord
* @param y y coord
* @param z z coord
* @param block block to place
* @param meta block meta to place
* @param fluid the fluid that has been paid for, and how much of it. Never null.
* @return true if the block has been placed, false otherwise. Autoplace rolls back and refunds nothing when this
* returns false before anything was consumed.
*/
boolean place(World world, int x, int y, int z, Block block, int meta, FluidStack fluid);
}
@@ -0,0 +1,55 @@
package com.gtnewhorizon.structurelib.fluid;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraftforge.fluids.FluidStack;
import com.github.bsideup.jabel.Desugar;
/**
* A concrete request to put one fluid block at one position: which block and meta the structure wants there, what that
* costs, and how strict the check for an already partially filled position is.
* <p>
* Structure elements create one of these, either from the {@link FluidPlacementRegistry} or from their own parameters,
* and hand it to the autoplace helper.
*
* @param block the block the structure wants at that position
* @param meta the block meta the structure wants at that position
* @param cost the fluid that has to be paid for a position that holds nothing yet. Must hold a fluid and a positive
* amount.
* @param policy how much fluid an existing position has to hold to be accepted as is
* @param placer how to actually place the block, or null to place it with a plain block set
*/
@Desugar
public record FluidBlockRequirement(Block block, int meta, FluidStack cost, FluidFillPolicy policy,
@Nullable FluidBlockPlacer placer) {
public FluidBlockRequirement {
if (block == null) throw new IllegalArgumentException("block must not be null");
if (cost == null || cost.getFluid() == null) throw new IllegalArgumentException("cost must hold a fluid");
if (cost.amount <= 0) throw new IllegalArgumentException("cost must have a positive amount");
if (policy == null) throw new IllegalArgumentException("policy must not be null");
}
/**
* Build a requirement from a registered placement.
*
* @param placement what the registry knows about this block state
* @param block the block the structure wants
* @param meta the block meta the structure wants
* @param policy how strict the check for an already partially filled position is
*/
public static FluidBlockRequirement of(FluidBlockPlacement placement, Block block, int meta,
FluidFillPolicy policy) {
if (placement == null) throw new IllegalArgumentException("placement must not be null");
return new FluidBlockRequirement(block, meta, placement.cost(), policy, placement.placer());
}
/**
* Build a requirement that pays with given fluid, and that places the block directly.
*/
public static FluidBlockRequirement of(Block block, int meta, FluidStack cost, FluidFillPolicy policy) {
return new FluidBlockRequirement(block, meta, cost, policy, null);
}
}
@@ -0,0 +1,43 @@
package com.gtnewhorizon.structurelib.fluid;
/**
* How much fluid a position has to hold before a fluid structure element considers it satisfied.
* <p>
* Structure definitions pick a policy, which allows a structure to accept an already partially filled position, e.g.
* one that got filled by fluid that spread from somewhere else, instead of insisting on a full source block.
*/
public enum FluidFillPolicy {
/**
* The position has to hold exactly the amount of fluid the structure element asks for. This is the default, and it
* accepts a full source block while rejecting anything that holds less.
*/
EXACT_STATE,
/**
* The position has to hold at least the amount of fluid the structure element asks for. A position holding more
* fluid than asked for is accepted as is, and is never drained down by autoplace.
*/
AT_LEAST,
/**
* The position has to hold any amount of the same fluid at all. Only a position that holds no fluid of that kind is
* topped up.
*/
ANY_FILLED;
/**
* Test whether the given amount is acceptable.
*
* @param existingAmount how much fluid the position holds right now
* @param targetAmount how much fluid the structure element asks for
*/
public boolean isSatisfied(int existingAmount, int targetAmount) {
switch (this) {
case EXACT_STATE:
return existingAmount == targetAmount;
case AT_LEAST:
return existingAmount >= targetAmount;
default:
return existingAmount > 0;
}
}
}
@@ -0,0 +1,263 @@
package com.gtnewhorizon.structurelib.fluid;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidBlock;
import net.minecraftforge.oredict.OreDictionary;
/**
* Tells StructureLib what it costs to place a fluid block, and how to place it.
* <p>
* A structure element that wants a fluid block, e.g. one created by {@code StructureUtility.ofBlock(Block, int)}, asks
* this registry what the block state costs. Water and lava are registered by default, every other Forge fluid block is
* recognised automatically with {@link #DEFAULT_FLUID_AMOUNT} per block, and a mod can register its own fluids, its own
* costs, and its own placement logic here.
* <p>
* Registrations are keyed by block and block meta. Registering the wildcard meta {@link OreDictionary#WILDCARD_VALUE}
* covers every meta of that block that does not have its own registration.
*/
public class FluidPlacementRegistry {
/**
* How much fluid one block of an automatically recognised fluid costs, which is one bucket by default.
*/
public static final int DEFAULT_FLUID_AMOUNT = 1000;
private static final Map<Block, Map<Integer, FluidBlockPlacement>> REGISTRY = new ConcurrentHashMap<>();
/**
* Block to fluid index, so that looking up a block that turns out not to be a fluid doesn't have to walk every
* registered fluid. Rebuilt whenever the fluid registry grows, e.g. when a mod registers its fluids later than the
* first lookup.
*/
private static final Map<Block, Fluid> FLUID_BLOCKS = new ConcurrentHashMap<>();
private static volatile int indexedFluidCount = -1;
static {
register(Blocks.water, 0);
register(Blocks.flowing_water, 0);
register(Blocks.lava, 0);
register(Blocks.flowing_lava, 0);
}
private FluidPlacementRegistry() {}
/**
* Dummy method to force the class to initialize, and with it the default water and lava registrations.
*/
public static void init() {}
/**
* Register what it costs to place the given block state, preferring the item form when the block has one.
*
* @param block the fluid block
* @param meta the block meta. {@link OreDictionary#WILDCARD_VALUE} covers every meta of this block.
* @param cost how much fluid one block of this state costs
* @throws IllegalArgumentException if the block is null, the cost is invalid, or this state is already registered
*/
public static void register(Block block, int meta, FluidStack cost) {
register(block, meta, FluidBlockPlacement.of(cost));
}
/**
* Register what it costs to place the given block state, with {@link #DEFAULT_FLUID_AMOUNT} of the fluid the block
* holds, preferring the item form when the block has one.
* <p>
* The amount is the whole cost of that state. A block whose meta says how full it is therefore wants one
* registration per meta it can be in, or no registration at all, in which case {@link #resolve(Block, int)} scales
* the default amount down for a partially filled block.
*
* @param block the fluid block
* @param meta the block meta. {@link OreDictionary#WILDCARD_VALUE} covers every meta of this block.
* @throws IllegalArgumentException if the block holds no fluid, or this state is already registered
*/
public static void register(Block block, int meta) {
register(block, meta, false);
}
/**
* Register what it costs to place the given block state, with {@link #DEFAULT_FLUID_AMOUNT} of the fluid the block
* holds.
*
* @param block the fluid block
* @param meta the block meta. {@link OreDictionary#WILDCARD_VALUE} covers every meta of this block.
* @param forceFluid whether to always pay with fluid, even when this block also has an item form
* @throws IllegalArgumentException if the block holds no fluid, or this state is already registered
*/
public static void register(Block block, int meta, boolean forceFluid) {
FluidStack cost = FluidBlockPlacement.defaultCost(fluidOf(block));
register(block, meta, forceFluid ? FluidBlockPlacement.forced(cost) : FluidBlockPlacement.of(cost));
}
/**
* Register the whole block, i.e. every meta of it that has no registration of its own, with
* {@link #DEFAULT_FLUID_AMOUNT} of the fluid it holds.
*
* @param block the fluid block
* @throws IllegalArgumentException if the block holds no fluid, or the wildcard meta is already registered
*/
public static void register(Block block) {
register(block, OreDictionary.WILDCARD_VALUE);
}
/**
* Register what it costs to place the given block state, with {@link #DEFAULT_FLUID_AMOUNT} of the fluid the block
* holds, and placed the way the given placer says.
* <p>
* Use this for a fluid block that cannot be placed with a plain block set, e.g. one that has to be filled through
* its own API.
*
* @param block the fluid block
* @param meta the block meta. {@link OreDictionary#WILDCARD_VALUE} covers every meta of this block.
* @param placer how to write the block into the world
* @throws IllegalArgumentException if the block holds no fluid, or this state is already registered
*/
public static void register(Block block, int meta, FluidBlockPlacer placer) {
register(block, meta, FluidBlockPlacement.of(FluidBlockPlacement.defaultCost(fluidOf(block)), placer));
}
/**
* Register what it costs to place the given block state.
*
* @param block the fluid block
* @param meta the block meta. {@link OreDictionary#WILDCARD_VALUE} covers every meta of this block.
* @param forceFluid whether to always pay with fluid, even when this block also has an item form
* @param cost how much fluid one block of this state costs
* @throws IllegalArgumentException if the block is null, the cost is invalid, or this state is already registered
*/
public static void register(Block block, int meta, FluidStack cost, boolean forceFluid) {
register(block, meta, new FluidBlockPlacement(cost, forceFluid, null));
}
/**
* Register what it costs to place the given block state, and how to place it.
*
* @param block the fluid block
* @param meta the block meta. {@link OreDictionary#WILDCARD_VALUE} covers every meta of this block.
* @param placement the cost and the placement logic
* @throws IllegalArgumentException if the block or the placement is null, or this state is already registered
*/
public static void register(Block block, int meta, FluidBlockPlacement placement) {
if (block == null) throw new IllegalArgumentException("block must not be null");
if (placement == null) throw new IllegalArgumentException("placement must not be null");
Map<Integer, FluidBlockPlacement> byMeta = REGISTRY.computeIfAbsent(block, b -> new ConcurrentHashMap<>());
if (byMeta.putIfAbsent(meta, placement) != null) {
throw new IllegalArgumentException(
"Duplicate fluid placement for " + block.getUnlocalizedName() + ":" + meta);
}
}
/**
* What has been registered for exactly this block state.
*
* @return the registration, or null when there is none
*/
@Nullable
public static FluidBlockPlacement get(Block block, int meta) {
if (block == null) return null;
Map<Integer, FluidBlockPlacement> byMeta = REGISTRY.get(block);
if (byMeta == null) return null;
FluidBlockPlacement placement = byMeta.get(meta);
return placement != null ? placement : byMeta.get(OreDictionary.WILDCARD_VALUE);
}
/**
* What it costs to place this block state, whether it has been registered or not.
* <p>
* This is what autoplace asks. A registered state answers with its registration. Otherwise a block implementing
* Forge's {@code IFluidBlock}, and any block whose material is a liquid, answer with {@link #DEFAULT_FLUID_AMOUNT}
* of the fluid they hold, scaled down for a meta that asks for a partial block.
*
* @return the placement, or null when this block state is not a fluid block
*/
@Nullable
public static FluidBlockPlacement resolve(Block block, int meta) {
FluidBlockPlacement placement = get(block, meta);
if (placement != null) return placement;
Fluid fluid = getFluidOf(block);
if (fluid == null) return null;
int amount = FluidAmounts.getAmountForMeta(block, meta, DEFAULT_FLUID_AMOUNT);
if (amount <= 0) return null;
return FluidBlockPlacement.of(new FluidStack(fluid, amount));
}
/**
* Whether this block state is a fluid block that autoplace can place.
*/
public static boolean isFluidBlock(Block block, int meta) {
return resolve(block, meta) != null;
}
/**
* Whether this block state can be placed as an item, i.e. whether the block has an item form.
* <p>
* Autoplace prefers the item form when there is one, so that blocks that are both a fluid block and an item keep
* behaving the way they did before fluid autoplace existed.
*/
public static boolean hasItemForm(Block block) {
if (block == null) return false;
return Item.getItemFromBlock(block) != null;
}
/**
* The fluid held by given block, if any.
* <p>
* A block implementing Forge's {@code IFluidBlock} answers directly. Everything else is looked up in an index of
* every registered fluid, and finally by material, which covers the vanilla water and lava blocks that no fluid
* claims.
*
* @return the fluid, or null when this block does not hold one
*/
@Nullable
public static Fluid getFluidOf(Block block) {
if (block == null) return null;
if (block instanceof IFluidBlock fluidBlock) {
Fluid fluid = fluidBlock.getFluid();
if (fluid != null) return fluid;
}
Fluid byBlock = indexFluidBlocks().get(block);
if (byBlock != null) return byBlock;
Material material = block.getMaterial();
if (material == Material.water) return FluidRegistry.WATER;
if (material == Material.lava) return FluidRegistry.LAVA;
return null;
}
/**
* The fluid held by given block, for the registrations that default to {@link #DEFAULT_FLUID_AMOUNT} of it.
*
* @throws IllegalArgumentException if the block is null or holds no fluid
*/
private static Fluid fluidOf(Block block) {
Fluid fluid = getFluidOf(block);
if (fluid == null) {
throw new IllegalArgumentException(
"Block " + (block == null ? "null" : block.getUnlocalizedName())
+ " holds no fluid,"
+ " register it with an explicit cost instead");
}
return fluid;
}
private static synchronized Map<Block, Fluid> indexFluidBlocks() {
Map<String, Fluid> fluids = FluidRegistry.getRegisteredFluids();
if (fluids.size() == indexedFluidCount) return FLUID_BLOCKS;
FLUID_BLOCKS.clear();
for (Fluid fluid : fluids.values()) {
if (fluid == null) continue;
Block block = fluid.getBlock();
if (block != null) FLUID_BLOCKS.put(block, fluid);
}
indexedFluidCount = fluids.size();
return FLUID_BLOCKS;
}
}
@@ -0,0 +1,56 @@
package com.gtnewhorizon.structurelib.fluid;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.entity.player.EntityPlayerMP;
import com.gtnewhorizon.structurelib.SortedRegistry;
/**
* The registry of everything that can hand out fluid on a player's behalf, plus the composition that autoplace uses.
* <p>
* This mirrors {@link FluidStackExtractors}: it is a {@link SortedRegistry}, so the player can reorder or disable every
* provider in StructureLib's config, and the ordering can be synced to the server. Providers are asked in order, and
* whatever the player is carrying comes last, so a provider that holds a lot of fluid, e.g. an ME network, is drained
* before the player's buckets are emptied.
*/
public class FluidSourceProviders {
private static final SortedRegistry<IFluidSourceProvider> PROVIDERS = new SortedRegistry<>("fluidsourceproviders");
private FluidSourceProviders() {}
/**
* Dummy method to force the class to initialize, and with it the registry and its config entry.
*/
public static void init() {}
/**
* Register a provider. Lower keys are asked first.
*
* @param key unique key. Matches the key shown in the config gui.
* @param provider the provider
*/
public static void register(String key, IFluidSourceProvider provider) {
PROVIDERS.register(key, provider);
}
/**
* The fluid source to use for a player: every provider that has something to offer, in their configured order,
* followed by the fluid containers the player is carrying.
*
* @param player the player the structure is being built for
* @return a source that never returns more than it was asked for. never null.
*/
public static IFluidSource getSourceFor(EntityPlayerMP player) {
if (player == null) throw new IllegalArgumentException();
List<IFluidSource> sources = new ArrayList<>();
for (IFluidSourceProvider provider : PROVIDERS.getPlayerOrdering(player)) {
IFluidSource source = provider.getFluidSource(player);
if (source != null) sources.add(source);
}
sources.add(IFluidSource.fromPlayer(player));
return IFluidSource.composite(sources.toArray(new IFluidSource[0]));
}
}
@@ -0,0 +1,78 @@
package com.gtnewhorizon.structurelib.fluid;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
/**
* Extract fluid from a single item stack, e.g. a bucket or a cell.
* <p>
* Implementations are registered in {@link FluidStackExtractors}. StructureLib ships implementations for Forge's
* {@code IFluidContainerItem} and for {@code FluidContainerRegistry}, which together cover the vast majority of fluid
* containers. Register your own implementation when your containers expose their fluid by other means, e.g. fluid
* stored inside a backpack or inside a custom NBT layout.
* <p>
* All methods must be side effect free when a simulation is requested, and must never depend on a world.
*/
public interface FluidStackExtractor {
/**
* Whether this extractor can work with given item stack. This must be a cheap, side effect free check.
*
* @param stack the stack to test. never null.
*/
boolean isValidSource(ItemStack stack);
/**
* Extract up to {@code resource.amount} of fluid from this container.
* <p>
* The container item itself is never swapped by this method. A container whose fluid is stored in its NBT may
* mutate that NBT in place when {@code simulate} is false. A container that has to turn into another item, or to
* disappear, declares so through {@link #convertsContainer(ItemStack, FluidStack)} and
* {@link #getReplacement(ItemStack)} instead.
* <p>
* A container that is consumed as a whole, i.e. one that answers true from
* {@link #convertsContainer(ItemStack, FluidStack)}, cannot be split, so it may report the whole content of the
* container even when that is more than was asked for. Such a surplus is spent, as a half emptied bucket does not
* exist.
*
* @param container what to drain from. never null, and always accepted by {@link #isValidSource(ItemStack)}.
* @param resource the fluid to drain, and how much of it at most. never null, and never mutated.
* @param simulate whether to actually commit the modification. true for dry run, false otherwise.
* @return amount of fluid drained. never negative, and never more than {@code resource.amount} unless this
* container is consumed as a whole
*/
int drain(ItemStack container, FluidStack resource, boolean simulate);
/**
* Whether draining this container would turn it into another item, or make it disappear.
* <p>
* Called before draining, with the container still holding its fluid. When this returns true, the caller replaces
* the whole slot with {@link #getReplacement(ItemStack)} after a successful drain, so the implementation is
* responsible for the whole stack: either it has to be a container that is drained as a unit, e.g. a bucket, or
* {@link #drain(ItemStack, FluidStack, boolean)} has to reduce {@code stackSize} itself, as a stack of fluid drops
* does.
*
* @param container the container stack, in its state before being drained
* @param resource the fluid that is about to be drained, and how much of it at most
*/
default boolean convertsContainer(ItemStack container, FluidStack resource) {
return false;
}
/**
* The item stack that should replace given container once it got drained, or null when the container slot should
* become empty instead.
* <p>
* The caller refuses to drain a container that has to be replaced by another item while its slot holds more than
* one item, as it cannot hand the replacement back to the player safely. A null replacement is always allowed, as
* it only empties the slot.
*
* @param container the container stack, in its state before being drained
*/
@Nullable
default ItemStack getReplacement(ItemStack container) {
return null;
}
}
@@ -0,0 +1,285 @@
package com.gtnewhorizon.structurelib.fluid;
import java.util.Iterator;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import com.gtnewhorizon.structurelib.SortedRegistry;
import com.gtnewhorizon.structurelib.util.InventoryIterable;
import com.gtnewhorizon.structurelib.util.InventoryUtility;
import com.gtnewhorizon.structurelib.util.InventoryUtility.InventoryProvider;
import com.gtnewhorizon.structurelib.util.InventoryUtility.ItemStackExtractor;
/**
* The registry of every way StructureLib knows how to pull fluid out of an item, plus the inventory walk that uses
* these extractors.
* <p>
* This is the fluid counterpart of the item extraction facilities that survival autoplace already relies on, including
* the fact that the registry is a {@link SortedRegistry}: entries can be reordered or disabled by the player in
* StructureLib's config, and the ordering can be synced to the server.
*/
public class FluidStackExtractors {
private static final SortedRegistry<FluidStackExtractor> EXTRACTORS = new SortedRegistry<>("fluidstackextractors");
static {
register("3000-forge-fluid-container-item", new ForgeFluidContainerItemExtractor());
register("5000-forge-fluid-container-registry", new ForgeFluidContainerRegistryExtractor());
}
private FluidStackExtractors() {}
/**
* Dummy method to force the class to initialize, and with it the builtin extractors.
*/
public static void init() {}
/**
* Register an extractor. Lower keys are tried first, so a mod that wants its extractor to take priority over
* StructureLib builtin ones should use a key sorting before {@code "3000-forge-fluid-container-item"}.
*
* @param key unique key. Matches the key shown in the config gui.
* @param val the extractor
*/
public static void register(String key, FluidStackExtractor val) {
EXTRACTORS.register(key, val);
}
/**
* Extract fluid from every inventory associated with the given player.
* <p>
* This walks exactly the same inventories as item autoplace does, see
* {@link com.gtnewhorizon.structurelib.util.InventoryUtility}: the main inventory first, then whatever else is
* registered, which currently means the ender chest when a mod asked for it and every inventory a mod registered
* for a backpack. Inside every item that holds an inventory the walk goes one level deep, so a bucket a player left
* in a backpack is found, and a mod that already lets autoplace take items out of its backpacks does not have to do
* anything for the fluid containers inside them.
* <p>
* Armor slots are excluded, as there is no fluid container that goes into one.
*
* @param player where to take fluid from
* @param resource what fluid to take, and how much of it at most
* @param simulate whether to actually take the fluid
* @return what has actually been taken. Never null, and never holding more than requested.
*/
public static FluidStack takeFromPlayer(EntityPlayerMP player, FluidStack resource, boolean simulate) {
if (player == null) throw new IllegalArgumentException();
if (resource == null || resource.getFluid() == null) throw new IllegalArgumentException();
int remaining = resource.amount;
for (InventoryProvider<?> provider : InventoryUtility.getInventoryProviders(player)) {
if (remaining <= 0) break;
remaining -= takeFromProvider(player, provider, new FluidStack(resource, remaining), simulate);
}
return new FluidStack(resource, resource.amount - remaining);
}
/**
* Extract fluid from one registered inventory of a player, and let its provider know it changed.
* <p>
* The wildcard of {@link InventoryProvider} is captured by this method's type parameter, which is what allows the
* inventory to be handed back to {@code markDirty}.
*/
private static <R extends Iterable<ItemStack>> int takeFromProvider(EntityPlayerMP player,
InventoryProvider<R> provider, FluidStack resource, boolean simulate) {
R inventory = provider.getInventory(player);
if (inventory == null) return 0;
// Only an inventory that is backed by an IInventory can have a slot written back, which a container such as a
// bucket needs when it is emptied into the world. A provider that hands out its stacks some other way is
// skipped rather than drained in place, as draining without replacing would leave the player a filled
// container that is already spent.
if (!(inventory instanceof InventoryIterable<?>iterable)) return 0;
int taken = takeFromInventory(iterable.getInventory(), resource, simulate, player, iterable.getMaxSlot(), true);
if (taken > 0 && !simulate && hasConnection(player)) provider.markDirty(inventory);
return taken;
}
/**
* Whether the inventory of given player has a client to be kept in sync with. A fake player, e.g. the one a
* structure preview tool uses, has no connection, and an inventory it changed never has to be sent anywhere.
*/
private static boolean hasConnection(EntityPlayerMP player) {
return player.playerNetServerHandler != null;
}
/**
* Extract fluid from given inventory.
* <p>
* Containers held inside an item of this inventory, e.g. in a backpack, are not looked into here. Take from a
* player through {@link #takeFromPlayer(EntityPlayerMP, FluidStack, boolean)} to look into those as well.
*
* @param inv where to take fluid from
* @param resource what fluid to take, and how much of it at most
* @param simulate whether to actually take the fluid
* @return what has actually been taken. Never null, and never holding more than requested.
*/
public static FluidStack takeFromInventory(IInventory inv, FluidStack resource, boolean simulate) {
if (inv == null) throw new IllegalArgumentException();
if (resource == null || resource.getFluid() == null) throw new IllegalArgumentException();
return new FluidStack(resource, takeFromInventory(inv, resource, simulate, null, -1, false));
}
/**
* Walk the slots of one inventory and take as much of the requested fluid as they hold.
*
* @param maxSlot slot to stop at, exclusive. -1 for every slot
* @param recursive whether to look inside the items of this inventory, e.g. into a backpack
* @return how much has been taken, never more than requested
*/
private static int takeFromInventory(IInventory inv, FluidStack resource, boolean simulate,
@Nullable EntityPlayerMP player, int maxSlot, boolean recursive) {
int slots = maxSlot < 0 ? inv.getSizeInventory() : Math.min(maxSlot, inv.getSizeInventory());
int remaining = resource.amount;
for (int slot = 0; slot < slots && remaining > 0; slot++) {
ItemStack stack = inv.getStackInSlot(slot);
if (stack == null || stack.getItem() == null || stack.stackSize <= 0) continue;
int taken = takeFromStack(stack, inv, slot, resource, remaining, simulate, player);
if (taken > 0) {
remaining -= taken;
continue;
}
if (recursive && player != null) {
remaining -= takeFromNested(player, stack, new FluidStack(resource, remaining), simulate);
}
}
return resource.amount - remaining;
}
/**
* Take fluid out of a single slot, using the first extractor that recognises what is in it.
*
* @return how much has been taken out of this slot, never more than requested
*/
private static int takeFromStack(ItemStack stack, IInventory owner, int slot, FluidStack resource, int maxAmount,
boolean simulate, @Nullable EntityPlayerMP player) {
for (FluidStackExtractor extractor : EXTRACTORS.getPlayerOrdering(player)) {
if (!extractor.isValidSource(stack)) continue;
FluidStack request = new FluidStack(resource, maxAmount);
boolean converts = extractor.convertsContainer(stack, request);
ItemStack replacement = converts ? extractor.getReplacement(stack) : null;
// A container that turns into another item can only be replaced when it is the only item in its slot.
if (replacement != null && stack.stackSize != 1) continue;
int drained = extractor.drain(stack, request, simulate);
if (drained <= 0) continue;
if (!simulate && converts) {
// A null replacement means the whole slot is spent, e.g. the drops of a fluid that was paid in full.
owner.setInventorySlotContents(slot, replacement);
owner.markDirty();
}
return Math.min(drained, maxAmount);
}
return 0;
}
/**
* Look inside the given stack for an inventory, e.g. a backpack, and take fluid out of the containers it holds.
* <p>
* Which stacks hold an inventory is decided by {@link InventoryUtility}, which is the same registry item autoplace
* uses, so a mod that already lets autoplace take items out of its backpacks gets the fluid containers inside them
* for free and never has to register anything for fluid. Only one level is looked into, exactly like the item walk
* does.
*
* @return how much has been taken, never more than requested
*/
private static int takeFromNested(EntityPlayerMP player, ItemStack stack, FluidStack resource, boolean simulate) {
int taken = 0;
for (Iterator<? extends ItemStackExtractor> iter = InventoryUtility.getStackExtractors(player); iter
.hasNext();) {
ItemStackExtractor extractor = iter.next();
if (!extractor.isValidSource(stack, player)) continue;
IInventory nested = extractor.getInventory(stack, player);
if (nested == null) continue;
int fromNested = takeFromInventory(
nested,
new FluidStack(resource, resource.amount - taken),
simulate,
player,
-1,
false);
if (fromNested <= 0) continue;
if (!simulate) nested.markDirty();
taken += fromNested;
break;
}
return taken;
}
/**
* Builtin extractor for containers implementing Forge's {@code IFluidContainerItem}, e.g. cells. Such containers
* keep their own fluid inside their NBT, so they are drained in place, and only turn into another item when their
* item declares a container item.
*/
public static class ForgeFluidContainerItemExtractor implements FluidStackExtractor {
@Override
public boolean isValidSource(ItemStack stack) {
return stack != null && stack.getItem() instanceof IFluidContainerItem;
}
@Override
public int drain(ItemStack container, FluidStack resource, boolean simulate) {
IFluidContainerItem item = (IFluidContainerItem) container.getItem();
FluidStack contained = item.getFluid(container);
if (contained == null || !contained.isFluidEqual(resource)) return 0;
FluidStack drained = item.drain(container, Math.min(contained.amount, resource.amount), !simulate);
return drained == null ? 0 : Math.min(drained.amount, resource.amount);
}
@Override
public boolean convertsContainer(ItemStack container, FluidStack resource) {
Item item = container.getItem();
if (item == null || !item.hasContainerItem(container)) return false;
FluidStack contained = ((IFluidContainerItem) item).getFluid(container);
// The container only turns into another item when this drain empties it for good.
return contained != null && contained.amount <= resource.amount;
}
@Nullable
@Override
public ItemStack getReplacement(ItemStack container) {
Item item = container.getItem();
return item == null ? null : item.getContainerItem(container);
}
}
/**
* Builtin extractor for containers registered with Forge's {@code FluidContainerRegistry}, e.g. buckets. Such
* containers are consumed as a whole, and are replaced by their container item.
*/
public static class ForgeFluidContainerRegistryExtractor implements FluidStackExtractor {
@Override
public boolean isValidSource(ItemStack stack) {
return stack != null && stack.getItem() != null && FluidContainerRegistry.isFilledContainer(stack);
}
@Override
public int drain(ItemStack container, FluidStack resource, boolean simulate) {
if (container.stackSize != 1) return 0;
FluidStack contained = FluidContainerRegistry.getFluidForFilledItem(container);
if (contained == null || !contained.isFluidEqual(resource)) return 0;
// A bucket cannot be half emptied. Report the whole bucket, even when only part of it is needed.
return contained.amount;
}
@Override
public boolean convertsContainer(ItemStack container, FluidStack resource) {
return container.stackSize == 1;
}
@Nullable
@Override
public ItemStack getReplacement(ItemStack container) {
Item item = container.getItem();
if (item != null && item.hasContainerItem(container)) return item.getContainerItem(container);
return null;
}
}
}
@@ -0,0 +1,149 @@
package com.gtnewhorizon.structurelib.fluid;
import javax.annotation.Nonnull;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidHandler;
/**
* Represent a source of fluid. Take only, cannot be put back. This is the fluid counterpart of the item source that
* survival autoplace already uses for blocks with an item form.
* <p>
* A structure element that has to place a fluid block asks the autoplace environment for a fluid source. When the
* environment doesn't carry one, StructureLib falls back to {@link #fromPlayer(EntityPlayerMP)} as long as the actor is
* a server side player, so multiblocks and third party tools that were written before this API existed keep working
* without any change.
* <p>
* Implementations are expected to be side effect free when {@code simulate} is true. A failed simulation followed by a
* successful one is not guaranteed to succeed, but it is not expected to happen either as autoplace runs on the server
* thread with no concurrent inventory modification.
*/
public interface IFluidSource {
/**
* Retrieve up to {@code resource.amount} of the given fluid from this source.
* <p>
* The given resource is never mutated.
*
* @param resource what fluid to extract, and how much of it at most. must have a positive amount.
* @param simulate whether to actually commit the modification. true for dry run, false otherwise.
* @return a new fluid stack describing what has actually been extracted. Never null. A zero amount means nothing
* could be extracted. The returned stack keeps the NBT tag of the requested fluid.
* @throws IllegalArgumentException if the given resource is null or has no fluid
*/
@Nonnull
FluidStack take(FluidStack resource, boolean simulate);
/**
* Take exactly {@code resource.amount} amount of fluid. Nothing is taken if the full amount isn't available.
*
* @param resource what fluid to extract, and how much of it. must have a positive amount.
* @param simulate whether to actually commit the modification. true for dry run, false otherwise.
* @return true if at least this much fluid can be/is taken.
* @throws IllegalArgumentException if the given resource is null or has no fluid
*/
default boolean takeAll(FluidStack resource, boolean simulate) {
if (resource == null || resource.getFluid() == null) throw new IllegalArgumentException();
if (resource.amount <= 0) return true;
if (getAvailable(resource) < resource.amount) return false;
if (simulate) return true;
FluidStack taken = take(resource, false);
return taken != null && taken.amount >= resource.amount;
}
/**
* Query how much of the given fluid this source could provide right now.
*
* @param resource what fluid to query. must have a positive amount, which acts as the upper bound of the result.
* @return amount available, between 0 and {@code resource.amount} inclusive
* @throws IllegalArgumentException if the given resource is null or has no fluid
*/
default int getAvailable(FluidStack resource) {
if (resource == null || resource.getFluid() == null) throw new IllegalArgumentException();
FluidStack taken = take(resource, true);
return taken == null ? 0 : Math.max(0, Math.min(taken.amount, resource.amount));
}
/**
* A source that never provides anything. Useful as a placeholder for a fluid source that is not available.
*/
static IFluidSource empty() {
return (resource, simulate) -> {
if (resource == null || resource.getFluid() == null) throw new IllegalArgumentException();
return new FluidStack(resource, 0);
};
}
/**
* Combine several sources into one, asking them in order until the requested amount is met.
* <p>
* This is how a multiblock that wants its fluid to come from somewhere else than the player keeps the player's own
* containers as a fallback: {@code composite(custom, env.getEffectiveFluidSource())}.
*
* @param sources the sources to ask, in order. Null entries are skipped.
*/
static IFluidSource composite(IFluidSource... sources) {
if (sources == null || sources.length == 0) return empty();
return (resource, simulate) -> {
if (resource == null || resource.getFluid() == null) throw new IllegalArgumentException();
int remaining = resource.amount;
for (IFluidSource source : sources) {
if (source == null || remaining <= 0) continue;
FluidStack taken = source.take(new FluidStack(resource, remaining), simulate);
if (taken == null || taken.amount <= 0) continue;
remaining -= Math.min(remaining, taken.amount);
}
return new FluidStack(resource, resource.amount - remaining);
};
}
/**
* Construct a fluid source from the fluid containers held by given player.
* <p>
* This will be backed by {@link FluidStackExtractors}, which covers every fluid container registered with Forge,
* and every container type registered by another mod through
* {@link FluidStackExtractors#register(String, FluidStackExtractor)}.
*/
static IFluidSource fromPlayer(EntityPlayerMP player) {
return (resource, simulate) -> FluidStackExtractors.takeFromPlayer(player, resource, simulate);
}
/**
* Construct a fluid source from given inventory. Useful for multiblocks that want to drain fluid from a nearby
* machine instead of from the player.
* <p>
* This will be backed by {@link FluidStackExtractors}.
*/
static IFluidSource fromInventory(IInventory inv) {
return (resource, simulate) -> FluidStackExtractors.takeFromInventory(inv, resource, simulate);
}
/**
* Construct a fluid source from a Forge fluid handler, e.g. a tank or a machine.
* <p>
* This is the intended way for a multiblock to pull fluid from a world container instead of from the player. A
* multiblock that wants to do so hands the source to autoplace through its own autoplace environment.
*
* @param handler the handler to drain from. must not be null.
* @param sides sides to try, in order. An empty or null array means every side.
*/
static IFluidSource fromHandler(IFluidHandler handler, ForgeDirection... sides) {
if (handler == null) throw new IllegalArgumentException();
ForgeDirection[] directions = sides == null || sides.length == 0 ? ForgeDirection.VALID_DIRECTIONS
: sides.clone();
return (resource, simulate) -> {
if (resource == null || resource.getFluid() == null) throw new IllegalArgumentException();
int remaining = resource.amount;
for (ForgeDirection direction : directions) {
if (remaining <= 0) break;
FluidStack drained = handler.drain(direction, new FluidStack(resource, remaining), !simulate);
if (drained == null || drained.getFluid() != resource.getFluid()) continue;
remaining -= Math.min(remaining, drained.amount);
}
return new FluidStack(resource, resource.amount - remaining);
};
}
}
@@ -0,0 +1,28 @@
package com.gtnewhorizon.structurelib.fluid;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayerMP;
/**
* Offers a fluid source to ask before the fluid containers a player is carrying.
* <p>
* This is how a mod that can hand out fluid without an item in the player's inventory plugs into autoplace, e.g. the ME
* network behind a wireless fluid terminal the player has on them, or the tanks of a network the player has access to.
* Providers are registered in {@link FluidSourceProviders}, so the player can reorder or disable them in StructureLib's
* config like every other registered feature.
* <p>
* A provider is only ever asked for a server side player, and only while autoplace is placing a fluid block, so it does
* not have to be cheap, but it should still avoid work it can do lazily: the returned source is asked for fluid more
* than once, and should look up whatever it drains from at that point rather than when it is created.
*/
public interface IFluidSourceProvider {
/**
* A fluid source for the given player, or null when this provider has nothing to contribute right now.
*
* @param player the player the structure is being built for. never null, and never a client side player.
*/
@Nullable
IFluidSource getFluidSource(EntityPlayerMP player);
}
@@ -0,0 +1,18 @@
package com.gtnewhorizon.structurelib.gui;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
public class EmptyContainer extends Container {
private final EntityPlayer player;
public EmptyContainer(EntityPlayer player) {
this.player = player;
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return player == this.player;
}
}
@@ -1,45 +1,85 @@
package com.gtnewhorizon.structurelib.gui;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import com.google.common.base.Splitter;
import com.gtnewhorizon.structurelib.ChannelDescription;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.gui.GuiScrollableList.IGuiScreen;
public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen {
import codechicken.nei.VisiblityData;
import codechicken.nei.api.INEIGuiHandler;
import codechicken.nei.api.TaggedInventoryArea;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Optional;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
@Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems")
public class GuiScreenConfigureChannels extends GuiContainer implements IGuiScreen, INEIGuiHandler {
private static final String I18N_PREFIX = "item.structurelib.constructableTrigger.gui.";
private static final int ADD_BTN = 0;
private static final int UNSET_BTN = 1;
private static final int WIPE_BTN = 2;
private static final int KEY_MAX_WIDTH = 50;
private static final int INFO_BOX_SIZE = 11;
private final ItemStack trigger;
private final GuiChannelsList list;
private final GuiAutoCompleteList autoCompleteList;
private final Map<String, List<String>> tooltipSplitCache = new HashMap<>();
private final TIntObjectMap<Map<String, String>> trimCache = new TIntObjectHashMap<>();
private GuiTextField key, value;
protected int guiTop, guiLeft;
private List<String> info;
private boolean wipePending = false;
private long wipePendingTime = 0;
private static final long WIPE_CONFIRM_TIMEOUT_MS = 3000;
public GuiScreenConfigureChannels(Container container, ItemStack trigger) {
super(container);
public GuiScreenConfigureChannels(ItemStack trigger) {
this.trigger = trigger;
list = new GuiChannelsList(152, 100, 12, 12, 14);
list = new GuiChannelsList(152, 91, 12, 21, 14);
list.addSelectionListener((list, selectedIndex) -> {
Entry<String, Integer> e = list.getElementAt(selectedIndex);
key.setText(e.getKey());
value.setText(e.getValue().toString());
updateButtons();
});
autoCompleteList = new GuiAutoCompleteList(151 + 12 - 45 - 2, 50, 45, 119 + 12, 14);
}
@Override
@@ -125,33 +165,20 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
};
list.onGuiInit(this);
autoCompleteList.onGuiInit(this);
addButton(
new GuiButton(
0,
guiLeft + 12,
guiTop + 157,
47,
20,
I18n.format("item.structurelib.constructableTrigger.gui.add")));
addButton(
new GuiButton(
1,
guiLeft + 65,
guiTop + 157,
47,
20,
I18n.format("item.structurelib.constructableTrigger.gui.unset")));
addButton(
new GuiButton(
2,
guiLeft + 118,
guiTop + 157,
47,
20,
I18n.format("item.structurelib.constructableTrigger.gui.wipe")));
addButton(new GuiButton(ADD_BTN, guiLeft + 12, guiTop + 157, 47, 20, I18n.format(I18N_PREFIX + "add")));
addButton(new GuiButton(UNSET_BTN, guiLeft + 65, guiTop + 157, 47, 20, I18n.format(I18N_PREFIX + "unset")));
addButton(new GuiButton(WIPE_BTN, guiLeft + 118, guiTop + 157, 47, 20, I18n.format(I18N_PREFIX + "wipe")));
updateButtons();
tooltipSplitCache.clear();
info = StreamSupport
.stream(
Splitter.on("\\n").split(StatCollector.translateToLocal(I18N_PREFIX + "info")).spliterator(),
false)
.flatMap(line -> fontRendererObj.listFormattedStringToWidth(line, width * 1 / 3).stream())
.collect(Collectors.toList());
}
@Override
@@ -194,30 +221,54 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
actionPerformed(but);
}
@SuppressWarnings("unchecked")
private List<GuiButton> getButtonList() {
public List<GuiButton> getButtonList() {
return buttonList;
}
private boolean isMouseOverValue() {
int mx = Mouse.getEventX() * this.width / this.mc.displayWidth;
int my = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1;
return mx >= value.xPosition && mx < value.xPosition + value.width
&& my >= value.yPosition
&& my < value.yPosition + value.height;
}
@Override
public void handleMouseInput() {
int delta = Mouse.getEventDWheel();
if (delta != 0) list.handleDWheel(delta);
if (delta != 0) {
if (isMouseOverValue()) {
if (delta > 0) {
value.setText(String.valueOf(getValue() + 1));
} else {
value.setText(String.valueOf(Math.max(getValue() - 1, 1)));
}
} else {
list.handleDWheel(delta);
}
}
super.handleMouseInput();
}
@Override
protected void mouseClicked(int mX, int mY, int button) {
super.mouseClicked(mX, mY, button);
key.mouseClicked(mX, mY, button);
value.mouseClicked(mX, mY, button);
super.mouseClicked(mX, mY, button);
}
@Override
protected void keyTyped(char aChar, int aKey) {
GuiScrollableList<?> l = key.isFocused() ? autoCompleteList : list;
switch (aKey) {
case Keyboard.KEY_TAB:
if (key.isFocused()) {
if (autoCompleteList.getSelectedElement() != null) {
key.setText(autoCompleteList.getSelectedElement());
return;
}
key.setFocused(false);
value.setFocused(true);
} else {
@@ -227,21 +278,38 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
return;
case Keyboard.KEY_RETURN:
case Keyboard.KEY_NUMPADENTER:
GuiButton add = getButtonList().get(0);
if (key.isFocused() && autoCompleteList.getSelectedElement() != null) {
key.setText(autoCompleteList.getSelectedElement());
key.setFocused(false);
value.setFocused(true);
value.setText("1");
value.setSelectionPos(0);
return;
}
GuiButton add = getButtonList().get(ADD_BTN);
if (add.enabled) doActionPerformed(add);
return;
case Keyboard.KEY_UP:
if (list.selectedIndex > 0) list.setSelection(list.selectedIndex - 1);
if (l.selectedIndex > 0) l.setSelection(l.selectedIndex - 1);
return;
case Keyboard.KEY_DOWN:
if (list.selectedIndex < list.getNumElements() - 1) list.setSelection(list.selectedIndex + 1);
if (l.selectedIndex < l.getNumElements() - 1) l.setSelection(l.selectedIndex + 1);
return;
case Keyboard.KEY_ESCAPE:
if (key.isFocused()) {
if (autoCompleteList.getSelectedElement() != null) {
autoCompleteList.reset();
} else {
key.setFocused(false);
}
return;
}
break;
}
if (key.textboxKeyTyped(aChar, aKey)) {
if (key.textboxKeyTyped(aChar, aKey) || value.textboxKeyTyped(aChar, aKey)) {
updateButtons();
return;
}
if (value.textboxKeyTyped(aChar, aKey)) return;
super.keyTyped(aChar, aKey);
}
@@ -250,10 +318,14 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
// STACKOVERFLOW!
String keyText = key.getText();
boolean existing = !StringUtils.isEmpty(keyText) && ChannelDataAccessor.hasSubChannel(trigger, keyText);
getButtonList().get(0).displayString = existing ? I18n.format("item.structurelib.constructableTrigger.gui.set")
: I18n.format("item.structurelib.constructableTrigger.gui.add");
getButtonList().get(0).enabled = !StringUtils.isBlank(value.getText());
getButtonList().get(1).enabled = existing && !StringUtils.isBlank(value.getText());
getButtonList().get(ADD_BTN).displayString = existing ? I18n.format(I18N_PREFIX + "set")
: I18n.format(I18N_PREFIX + "add");
getButtonList().get(ADD_BTN).enabled = !StringUtils.isBlank(key.getText())
&& !StringUtils.isBlank(value.getText())
&& Integer.parseInt(value.getText()) > 0;
getButtonList().get(UNSET_BTN).enabled = existing && !StringUtils.isBlank(value.getText());
autoCompleteList.reset();
}
private int getValue() {
@@ -268,18 +340,31 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
protected void actionPerformed(GuiButton btn) {
if (btn == null) return;
switch (btn.id) {
case 0:
case ADD_BTN:
int value = getValue();
if (value <= 0) return;
ChannelDataAccessor.setChannelData(trigger, key.getText(), value);
break;
case 1:
case UNSET_BTN:
ChannelDataAccessor.unsetChannelData(trigger, key.getText());
break;
case 2:
ChannelDataAccessor.wipeChannelData(trigger);
case WIPE_BTN:
if (!wipePending) {
wipePending = true;
wipePendingTime = System.currentTimeMillis();
btn.displayString = I18n.format(I18N_PREFIX + "wipe.confirm");
} else {
wipePending = false;
btn.displayString = I18n.format(I18N_PREFIX + "wipe");
ChannelDataAccessor.wipeChannelData(trigger);
key.setText("");
this.value.setText("");
}
break;
}
updateButtons();
super.actionPerformed(btn);
}
@@ -295,35 +380,241 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
super.updateScreen();
key.updateCursorCounter();
value.updateCursorCounter();
if (wipePending && System.currentTimeMillis() - wipePendingTime > WIPE_CONFIRM_TIMEOUT_MS) {
wipePending = false;
getButtonList().get(WIPE_BTN).displayString = I18n.format(I18N_PREFIX + "wipe");
}
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
@Override
public void drawScreen(int mX, int mY, float partialTick) {
public void drawGuiContainerBackgroundLayer(float partialTick, int mX, int mY) {
mc.renderEngine.bindTexture(new ResourceLocation("structurelib", "textures/gui/channels.png"));
int topLeftX = (this.width - this.getXSize()) / 2;
int topLeftY = (this.height - this.getYSize()) / 2;
drawTexturedModalRect(topLeftX, topLeftY, 0, 0, getXSize(), getYSize());
super.drawScreen(mX, mY, partialTick);
list.drawScreen(mX, mY, partialTick);
fontRendererObj.drawString(
I18n.format("item.structurelib.constructableTrigger.gui.key"),
guiLeft + 12,
guiTop + 122,
0);
fontRendererObj.drawString(I18n.format(I18N_PREFIX + "title"), guiLeft + 12, guiTop + 9, 0);
fontRendererObj.drawString(I18n.format(I18N_PREFIX + "key"), guiLeft + 12, guiTop + 122, 0);
key.drawTextBox();
fontRendererObj.drawString(
I18n.format("item.structurelib.constructableTrigger.gui.value"),
guiLeft + 12,
guiTop + 142,
0);
fontRendererObj.drawString(I18n.format(I18N_PREFIX + "value"), guiLeft + 12, guiTop + 142, 0);
value.drawTextBox();
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
if (key.isFocused() && autoCompleteList.getNumElements() > 0) {
autoCompleteList.drawScreen(mouseX, mouseY, 0);
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
String highlight = null;
if (key.isFocused() && autoCompleteList.getNumElements() > 0) {
highlight = autoCompleteList.getSelectedElement();
}
if (highlight == null && ChannelDescription.has(key.getText())) {
highlight = key.getText();
}
if (highlight != null) {
drawChannelDescriptionTooltip(highlight);
}
if (mouseX > xSize + guiLeft - INFO_BOX_SIZE - 12 && mouseX < xSize + guiLeft - 12
&& mouseY > guiTop + 7
&& mouseY < guiTop + INFO_BOX_SIZE + 7) {
drawHoveringText(info, mouseX, mouseY, fontRendererObj);
}
}
private void drawChannelDescriptionTooltip(String candidate) {
List<String> tooltip = tooltipSplitCache.computeIfAbsent(candidate, this::getChannelDescriptionTooltip);
drawHoveringText(tooltip, guiLeft + 151 + 12, guiTop + 122, fontRendererObj);
}
private List<String> getChannelDescriptionTooltip(String candidate) {
List<String> tooltip = new ArrayList<>();
int maxLine = width - (guiLeft + 151 + 12) - 12;
for (Entry<String, String> e : ChannelDescription.get(candidate).getDescriptions().entrySet()) {
tooltip.addAll(
fontRendererObj.listFormattedStringToWidth(
StatCollector.translateToLocalFormatted(
I18N_PREFIX + "channels.from",
Loader.instance().getIndexedModList().get(e.getKey()).getName()),
maxLine));
tooltip.addAll(
fontRendererObj.listFormattedStringToWidth(StatCollector.translateToLocal(e.getValue()), maxLine));
}
return tooltip;
}
public String trim(String str, int keyMaxWidth) {
Map<String, String> cache = trimCache.get(keyMaxWidth);
if (cache == null) {
trimCache.put(keyMaxWidth, cache = new HashMap<>());
}
return cache.computeIfAbsent(str, e -> {
String s = fontRendererObj.trimStringToWidth(e, keyMaxWidth);
if (s.length() != e.length()) {
StringBuilder buffer = new StringBuilder(s).deleteCharAt(s.length() - 1).append("...");
while ((s = fontRendererObj.trimStringToWidth(buffer.toString(), keyMaxWidth)).length()
!= buffer.length())
// drop last original char
buffer.deleteCharAt(s.length() - 4);
do {
buffer.append('.');
} while (fontRendererObj.getStringWidth(buffer.toString()) <= keyMaxWidth);
s = buffer.deleteCharAt(s.length() - 1).insert(s.length() - 3, EnumChatFormatting.GRAY).toString();
}
return s;
});
}
@Override
@Optional.Method(modid = "NotEnoughItems")
public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) {
return null;
}
@Override
public Iterable<Integer> getItemSpawnSlots(GuiContainer gui, ItemStack item) {
return Collections.emptyList();
}
@Override
public List<TaggedInventoryArea> getInventoryAreas(GuiContainer gui) {
return Collections.emptyList();
}
@Override
public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) {
if (button != 0 || mousex <= guiLeft
|| mousey <= guiTop
|| mousex >= guiLeft + getXSize()
|| mousey >= guiTop + getYSize()) {
return false;
}
Collection<Entry<String, Integer>> channels = ChannelDescription.iterate(draggedStack);
switch (channels.size()) {
case 0:
return false;
case 1:
default: // TODO implement a GUI to select which pair to use, instead of blindly using the first
Entry<String, Integer> e = channels.iterator().next();
ChannelDataAccessor.setChannelData(trigger, e.getKey(), e.getValue());
key.setText(e.getKey());
value.setText(e.getValue().toString());
draggedStack.stackSize = 0;
return true;
}
}
@Override
public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) {
return false;
}
private class GuiAutoCompleteList extends GuiScrollableList<String> {
private List<Entry<String, String>> cache; // <key, display string>
public GuiAutoCompleteList(int width, int height, int originX, int originY, int slotHeight) {
super(width, height, originX, originY, slotHeight);
margin = 2;
}
private List<Entry<String, String>> getOptions() {
if (cache == null) {
cache = search();
}
return cache;
}
private List<Entry<String, String>> search() {
List<Entry<String, String>> cache = new ArrayList<>();
Set<String> added = new HashSet<>();
String term = key.getText();
String[] subjects = ChannelDescription.getAll().keySet().toArray(new String[0]);
Arrays.sort(subjects);
if (StringUtils.isBlank(term)) {
// nothing. just gives out everything
for (String subject : subjects) {
cache.add(new AbstractMap.SimpleImmutableEntry<>(subject, EnumChatFormatting.GRAY + subject));
}
return cache;
}
// prefix match
for (String s : subjects) {
if (s.startsWith(term)) {
cache.add(
new AbstractMap.SimpleImmutableEntry<>(
s,
term + EnumChatFormatting.GRAY + s.substring(term.length())));
added.add(s);
}
}
// subsequence match
for (String subject : subjects) {
if (!added.contains(subject) && subject.length() > term.length()) {
int i = 0, j = 0;
StringBuilder sb = new StringBuilder();
boolean mode = true;
sb.append(EnumChatFormatting.WHITE);
while (i < term.length() && j < subject.length()) {
if (term.codePointAt(i) == subject.codePointAt(j)) {
if (!mode) {
sb.append(EnumChatFormatting.WHITE);
mode = true;
}
sb.appendCodePoint(term.codePointAt(i));
i++;
j++;
} else {
if (mode) {
sb.append(EnumChatFormatting.GRAY);
mode = false;
}
sb.appendCodePoint(subject.codePointAt(j));
j++;
}
}
if (i == term.length()) {
if (j < subject.length()) {
sb.append(EnumChatFormatting.GRAY);
sb.append(subject, j, subject.length());
}
cache.add(new AbstractMap.SimpleImmutableEntry<>(subject, sb.toString()));
added.add(subject);
}
}
}
return cache;
}
public void reset() {
cache = search();
selectedIndex = cache.isEmpty() ? -1 : 0;
resetScroll();
}
@Override
public String getElementAt(int index) {
return index >= 0 && index < cache.size() ? getOptions().get(index).getKey() : null;
}
@Override
public int getNumElements() {
return getOptions().size();
}
@Override
protected void drawElement(int elementIndex, int x, int y, int height, Tessellator tessellator,
boolean isHovering) {
int color = elementIndex == selectedIndex ? 0xffffff : 0xcccccc;
fontRendererObj.drawString(getOptions().get(elementIndex).getValue(), x + margin, y + margin / 2, color);
}
}
private class GuiChannelsList extends GuiScrollableList<Entry<String, Integer>> {
private List<Entry<String, Integer>> cache;
@@ -350,6 +641,7 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
Entry<String, Integer> e = getElementAt(elementIndex);
if (e != null) {
ChannelDataAccessor.unsetChannelData(trigger, e.getKey());
updateButtons();
return false;
}
}
@@ -390,22 +682,5 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
// args x1, y1, y2, color
drawVerticalLine(minX + margin + margin / 2 + KEY_MAX_WIDTH * 2, minY + 1, maxY - 1, 0xffaaaaaa);
}
public String trim(String e, int keyMaxWidth) {
// TODO optimize this to not create a billion string, or maybe cache this
String s = fontRendererObj.trimStringToWidth(e, keyMaxWidth);
if (s.length() != e.length()) {
StringBuilder buffer = new StringBuilder(s).deleteCharAt(s.length() - 1).append("...");
while ((s = fontRendererObj.trimStringToWidth(buffer.toString(), keyMaxWidth)).length()
!= buffer.length())
// drop last original char
buffer.deleteCharAt(s.length() - 4);
do {
buffer.append('.');
} while (fontRendererObj.getStringWidth(buffer.toString()) <= keyMaxWidth);
s = buffer.deleteCharAt(s.length() - 1).insert(s.length() - 3, EnumChatFormatting.GRAY).toString();
}
return s;
}
}
}
@@ -16,7 +16,7 @@ import org.lwjgl.opengl.GL11;
* <p>
* As the code has been released into public domain, it is now LGPL as part of this library as a whole. You can go to
* EnderCore's repository to obtain a public domain copy though
*
* <p>
* Major edits
* <ul>
* <li>Separate dwheel handling to handleDWheel. The next event calls often cause the mouse click event to not fire on
@@ -167,10 +167,17 @@ public abstract class GuiScrollableList<T> {
}
}
protected void resetScroll() {
amountScrolled = 0;
}
/**
* draws the slot to the screen, pass in mouse's current x and y and partial ticks
*/
public void drawScreen(int mX, int mY, float partialTick) {
GL11.glPushMatrix();
GL11.glLoadIdentity();
GL11.glTranslatef(0.0F, 0.0F, -2000.0F);
this.mouseX = mX;
this.mouseY = mY;
@@ -199,13 +206,26 @@ public abstract class GuiScrollableList<T> {
int contentYOffset = this.minY + margin - amountScrolled;
boolean hoveringPrecondition = mX >= minX && mX <= maxX && mY >= minY && mY <= maxY;
int slotHeight = this.slotHeight - margin;
if (selectedIndex != -1) {
int elementY = contentYOffset + selectedIndex * this.slotHeight;
if (elementY + slotHeight > maxY) {
this.amountScrolled = (selectedIndex + 1) * this.slotHeight - this.height + margin;
amountScrolled = (int) this.amountScrolled;
contentYOffset = this.minY + margin - amountScrolled;
} else if (elementY < minY) {
this.amountScrolled = selectedIndex * this.slotHeight;
amountScrolled = (int) this.amountScrolled;
contentYOffset = this.minY + margin - amountScrolled;
}
}
prepareDrawElements();
for (int i = 0; i < getNumElements(); ++i) {
int elementY = contentYOffset + i * this.slotHeight;
int slotHeight = this.slotHeight - margin;
if (elementY <= maxY && elementY + slotHeight >= minY) {
@@ -264,6 +284,7 @@ public abstract class GuiScrollableList<T> {
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_BLEND);
GL11.glPopMatrix();
}
protected void prepareDrawElements() {}
@@ -412,7 +433,7 @@ public abstract class GuiScrollableList<T> {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
tess.startDrawingQuads();
tess.setColorOpaque_I(2105376);
tess.setColorOpaque_I(0x202020);
tess.addVertex(minX, maxY, 0.0D);
tess.addVertex(maxX, maxY, 0.0D);
tess.addVertex(maxX, minY, 0.0D);
@@ -21,10 +21,9 @@ public class ItemBlockHint extends ItemBlock {
}
@Override
@SuppressWarnings("unchecked")
public void addInformation(ItemStack aStack, EntityPlayer aPlayer, List aList, boolean aF3_H) {
aList.add(translateToLocal("structurelib.blockhint.desc.0")); // Helps while building
switch (aStack.getItemDamage()) {
public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean adv) {
tooltip.add(translateToLocal("structurelib.blockhint.desc.0")); // Helps while building
switch (stack.getItemDamage()) {
case 0:
case 1:
case 2:
@@ -37,35 +36,36 @@ public class ItemBlockHint extends ItemBlock {
case 9:
case 10:
case 11:
aList.add(
// Placeholder for a certain group.
tooltip.add(
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.1")); // Placeholder for a certain
// group.
+ translateToLocal("structurelib.blockhint.desc.1"));
break;
case 12:
aList.add(
// General placeholder.
tooltip.add(
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.2")); // General placeholder.
+ translateToLocal("structurelib.blockhint.desc.2"));
break;
case 13:
aList.add(
// Make sure it contains Air material.
tooltip.add(
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.3")); // Make sure it contains Air
// material.
+ translateToLocal("structurelib.blockhint.desc.3"));
break;
case 14:
aList.add(
// Make sure it does not contain Air material.
tooltip.add(
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.4")); // Make sure it does not contain
// Air material.
+ translateToLocal("structurelib.blockhint.desc.4"));
break;
case 15:
aList.add(EnumChatFormatting.BLUE + translateToLocal("structurelib.blockhint.desc.5")); // ERROR, what
// did u expect?
// ERROR, what did u expect?
tooltip.add(EnumChatFormatting.BLUE + translateToLocal("structurelib.blockhint.desc.5"));
break;
default: // WTF?
aList.add("Damn son where did you get that!?");
aList.add(EnumChatFormatting.BLUE + "From outer space... I guess...");
tooltip.add("Damn son where did you get that!?");
tooltip.add(EnumChatFormatting.BLUE + "From outer space... I guess...");
}
}
@@ -28,8 +28,14 @@ public class ItemConstructableTrigger extends Item {
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (world.isRemote && getMovingObjectPositionFromPlayer(world, player, true) == null)
player.openGui(StructureLib.instance(), 0, world, player.inventory.currentItem, 0, 0);
if (getMovingObjectPositionFromPlayer(world, player, true) == null) {
// channel gui is opened from server and config gui from client
if (!world.isRemote && !player.isSneaking()) {
player.openGui(StructureLib.instance(), 0, world, player.inventory.currentItem, 0, 0);
} else if (world.isRemote && player.isSneaking()) {
StructureLib.instance().proxy().displayConfigGUI("registries");
}
}
return super.onItemRightClick(stack, world, player);
}
@@ -39,31 +45,30 @@ public class ItemConstructableTrigger extends Item {
return ConstructableUtility.handle(stack, player, world, x, y, z, side);
}
@SuppressWarnings("unchecked")
@Override
public void addInformation(ItemStack aStack, EntityPlayer ep, List aList, boolean boo) {
public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean adv) {
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
aList.add(
tooltip.add(
translateToLocalFormatted(
"item.structurelib.constructableTrigger.desc.lshift.0",
ChannelDataAccessor.countChannelData(aStack)));
ChannelDataAccessor.iterateChannelData(aStack).map(e -> e.getKey() + ": " + e.getValue())
.forEach(aList::add);
ChannelDataAccessor.countChannelData(stack)));
ChannelDataAccessor.iterateChannelData(stack).map(e -> e.getKey() + ": " + e.getValue())
.forEach(tooltip::add);
} else {
aList.add(translateToLocal("item.structurelib.constructableTrigger.desc.0")); // Triggers Constructable
// Interface
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.1")); // Shows multiblock
// construction
// details,
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.2")); // just Use on a
// multiblock
// controller.
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.3")); // (Sneak Use in
// creative to build)
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.4")); // Quantity affects
// tier/mode/type
if (ChannelDataAccessor.hasSubChannel(aStack))
aList.add(translateToLocal("item.structurelib.constructableTrigger.desc.5"));
// Tooltip text:
// Triggers Constructable Interface
// Shows multiblock construction details,
// just Use on a multiblock controller.
// (Sneak Use in creative to build)
// Quantity affects tier/mode/type
tooltip.add(translateToLocal("item.structurelib.constructableTrigger.desc.0"));
tooltip.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.1"));
tooltip.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.2"));
tooltip.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.3"));
tooltip.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.4"));
if (ChannelDataAccessor.hasSubChannel(stack))
tooltip.add(translateToLocal("item.structurelib.constructableTrigger.desc.5"));
}
}
}
@@ -34,15 +34,14 @@ public class ItemFrontRotationTool extends Item {
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List aList, boolean p_77624_4_) {
aList.add(translateToLocal("item.structurelib.frontRotationTool.desc.0")); // Triggers Front Rotation Interface
aList.add(EnumChatFormatting.BLUE + translateToLocal("item.structurelib.frontRotationTool.desc.1")); // Rotates
// only the
// front
// panel,
aList.add(EnumChatFormatting.BLUE + translateToLocal("item.structurelib.frontRotationTool.desc.2")); // which
// allows
// structure
// rotation.
public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean adv) {
// Tooltip Text:
// Triggers Front Rotation Interface
// Rotates only the front panel,
// which allows structure rotation.
tooltip.add(translateToLocal("item.structurelib.frontRotationTool.desc.0"));
tooltip.add(EnumChatFormatting.BLUE + translateToLocal("item.structurelib.frontRotationTool.desc.1"));
tooltip.add(EnumChatFormatting.BLUE + translateToLocal("item.structurelib.frontRotationTool.desc.2"));
}
}
@@ -0,0 +1,30 @@
package com.gtnewhorizon.structurelib.mixins;
import cpw.mods.fml.common.Mod;
public enum TargetedMod {
VANILLA("Minecraft", null);
/** The "name" in the {@link Mod @Mod} annotation */
public final String modName;
/** Class that implements the IFMLLoadingPlugin interface */
public final String coreModClass;
/** The "modid" in the {@link Mod @Mod} annotation */
public final String modId;
TargetedMod(String modName, String coreModClass) {
this(modName, coreModClass, null);
}
TargetedMod(String modName, String coreModClass, String modId) {
this.modName = modName;
this.coreModClass = coreModClass;
this.modId = modId;
}
@Override
public String toString() {
return "TargetedMod{modName='" + modName + "', coreModClass='" + coreModClass + "', modId='" + modId + "'}";
}
}
@@ -0,0 +1,44 @@
package com.gtnewhorizon.structurelib.mixins.early.blockChangeNotifier;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.util.BlockSnapshot;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.gtnewhorizon.structurelib.event.BlockChangeNotifier;
import com.llamalad7.mixinextras.sugar.Local;
@Mixin(ForgeHooks.class)
public class MixinForgeHooks {
@Inject(
method = "onPlaceItemIntoWorld",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/World;markAndNotifyBlock(IIILnet/minecraft/world/chunk/Chunk;Lnet/minecraft/block/Block;Lnet/minecraft/block/Block;I)V",
shift = At.Shift.AFTER),
remap = false)
private static void onBlockChange(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z,
int side, float hitX, float hitY, float hitZ, CallbackInfoReturnable<Boolean> cir,
@Local(name = "blocksnapshot") BlockSnapshot blocksnapshot, @Local(name = "newBlock") Block newBlock,
@Local(name = "metadata") int newMetadata) {
BlockChangeNotifier.onBlockChange(
world,
null,
blocksnapshot.x,
blocksnapshot.y,
blocksnapshot.z,
blocksnapshot.replacedBlock,
newBlock,
blocksnapshot.meta,
newMetadata);
}
}
@@ -0,0 +1,55 @@
package com.gtnewhorizon.structurelib.mixins.early.blockChangeNotifier;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.gtnewhorizon.structurelib.event.BlockChangeNotifier;
import com.llamalad7.mixinextras.sugar.Local;
import com.llamalad7.mixinextras.sugar.Share;
import com.llamalad7.mixinextras.sugar.ref.LocalIntRef;
import com.llamalad7.mixinextras.sugar.ref.LocalRef;
@Mixin(World.class)
public class MixinWorld {
@Inject(
method = "Lnet/minecraft/world/World;setBlock(IIILnet/minecraft/block/Block;II)Z",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/World;markAndNotifyBlock(IIILnet/minecraft/world/chunk/Chunk;Lnet/minecraft/block/Block;Lnet/minecraft/block/Block;I)V",
shift = At.Shift.AFTER,
remap = false))
public void setBlockObserve(int x, int y, int z, Block newBlock, int newMeta, int flags,
CallbackInfoReturnable<Boolean> cir, @Local(name = "block1") Block originalBlock,
@Share("originalMeta") LocalIntRef originalMeta, @Share("chunk") LocalRef<Chunk> chunkLocalRef) {
BlockChangeNotifier.onBlockChange(
(World) ((Object) (this)),
chunkLocalRef.get(),
x,
y,
z,
originalBlock,
newBlock,
originalMeta.get(),
newMeta);
}
@Inject(
method = "Lnet/minecraft/world/World;setBlock(IIILnet/minecraft/block/Block;II)Z",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/chunk/Chunk;func_150807_a(IIILnet/minecraft/block/Block;I)Z",
shift = At.Shift.BEFORE))
public void captureChunkAndOriginalMetadata(int x, int y, int z, Block blockIn, int metadataIn, int flags,
CallbackInfoReturnable<Boolean> cir, @Local(name = "chunk") Chunk chunk,
@Share("originalMeta") LocalIntRef originalMeta, @Share("chunk") LocalRef<Chunk> chunkLocalRef) {
chunkLocalRef.set(chunk);
originalMeta.set(chunk.getBlockMetadata(x & 15, y, z & 15));
}
}
@@ -0,0 +1,77 @@
package com.gtnewhorizon.structurelib.net;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.gtnewhorizon.structurelib.SortedRegistry;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf;
public class RegistryOrderSyncMessage implements IMessage {
private String name;
private List<String> order;
private List<String> disabled;
public RegistryOrderSyncMessage() {}
public RegistryOrderSyncMessage(String name, List<String> order, List<String> disabled) {
this.name = name;
this.order = order;
this.disabled = disabled;
}
@Override
public void fromBytes(ByteBuf buf) {
name = ByteBufUtils.readUTF8String(buf);
int size = ByteBufUtils.readVarInt(buf, 2);
order = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
order.add(ByteBufUtils.readUTF8String(buf));
}
size = ByteBufUtils.readVarInt(buf, 2);
disabled = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
disabled.add(ByteBufUtils.readUTF8String(buf));
}
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeUTF8String(buf, name);
ByteBufUtils.writeVarInt(buf, order.size(), 2);
for (String s : order) {
ByteBufUtils.writeUTF8String(buf, s);
}
ByteBufUtils.writeVarInt(buf, disabled.size(), 2);
for (String s : disabled) {
ByteBufUtils.writeUTF8String(buf, s);
}
}
public static class Handler implements IMessageHandler<RegistryOrderSyncMessage, IMessage> {
private static ConcurrentHashMap<String, WeakReference<SortedRegistry<?>>> ALL_REGISTRIES;
public static void setAllRegistries(ConcurrentHashMap<String, WeakReference<SortedRegistry<?>>> r) {
if (ALL_REGISTRIES == null) ALL_REGISTRIES = r;
}
@Override
public IMessage onMessage(RegistryOrderSyncMessage message, MessageContext ctx) {
if (ALL_REGISTRIES == null) return null;
WeakReference<SortedRegistry<?>> ref = ALL_REGISTRIES.get(message.name);
if (ref == null) return null;
SortedRegistry<?> r = ref.get();
if (r == null) return null;
r.registerOrdering(ctx.getServerHandler().playerEntity, message.order, message.disabled);
return null;
}
}
}
@@ -5,6 +5,7 @@ import java.util.function.Consumer;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -12,6 +13,8 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.fluid.FluidSourceProviders;
import com.gtnewhorizon.structurelib.fluid.IFluidSource;
/**
* Represent the environment in which autoplace of a single element took place.
@@ -19,6 +22,7 @@ import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
public class AutoPlaceEnvironment {
private IItemSource source;
private IFluidSource fluidSource;
private final EntityPlayer actor;
private final Consumer<IChatComponent> chatter;
private final IStructureDefinition<?> definition;
@@ -26,6 +30,9 @@ public class AutoPlaceEnvironment {
private final ExtendedFacing facing;
final int[] offsetABC;
private final int[] baseOffsetABC;
private final int[] basePositionXYZ;
private final Object contextObject;
private final FluidRoundState fluidRoundState;
public static AutoPlaceEnvironment fromLegacy(IItemSource source, EntityPlayer actor,
Consumer<IChatComponent> chatter) {
@@ -41,12 +48,14 @@ public class AutoPlaceEnvironment {
}
return original;
}
return new AutoPlaceEnvironment(source, actor, chatter, null, null, null, null, null);
return new AutoPlaceEnvironment(source, null, actor, chatter, null, null, null, null, null, null, null);
}
AutoPlaceEnvironment(EntityPlayer actor, Consumer<IChatComponent> chatter, IStructureDefinition<?> definition,
String piece, ExtendedFacing facing, int[] baseOffsetABC) {
String piece, ExtendedFacing facing, int[] baseOffsetABC, int[] basePositionXYZ, Object contextObject,
IFluidSource fluidSource, FluidRoundState fluidRoundState) {
this.source = null;
this.fluidSource = fluidSource;
this.actor = actor;
this.chatter = chatter;
this.definition = definition;
@@ -54,14 +63,37 @@ public class AutoPlaceEnvironment {
this.facing = facing;
this.offsetABC = new int[3];
this.baseOffsetABC = baseOffsetABC;
this.basePositionXYZ = basePositionXYZ;
this.contextObject = contextObject;
this.fluidRoundState = fluidRoundState;
}
AutoPlaceEnvironment(IItemSource source, EntityPlayer actor, Consumer<IChatComponent> chatter,
IStructureDefinition<?> definition, String piece, ExtendedFacing facing, int[] offsetABC,
int[] baseOffsetABC) {
AutoPlaceEnvironment(IItemSource source, IFluidSource fluidSource, EntityPlayer actor,
Consumer<IChatComponent> chatter, IStructureDefinition<?> definition, String piece, ExtendedFacing facing,
int[] offsetABC, int[] baseOffsetABC, int[] basePositionXYZ, Object contextObject) {
this(
source,
fluidSource,
actor,
chatter,
definition,
piece,
facing,
offsetABC,
baseOffsetABC,
basePositionXYZ,
contextObject,
null);
}
private AutoPlaceEnvironment(IItemSource source, IFluidSource fluidSource, EntityPlayer actor,
Consumer<IChatComponent> chatter, IStructureDefinition<?> definition, String piece, ExtendedFacing facing,
int[] offsetABC, int[] baseOffsetABC, int[] basePositionXYZ, Object contextObject,
FluidRoundState fluidRoundState) {
this.source = definition != null && !(source instanceof WrappedIItemSource)
? new WrappedIItemSource(this, source)
: source;
this.fluidSource = fluidSource;
this.actor = actor;
this.chatter = chatter;
this.definition = definition;
@@ -69,18 +101,25 @@ public class AutoPlaceEnvironment {
this.facing = facing;
this.offsetABC = offsetABC;
this.baseOffsetABC = baseOffsetABC;
this.basePositionXYZ = basePositionXYZ;
this.contextObject = contextObject;
this.fluidRoundState = fluidRoundState;
}
protected AutoPlaceEnvironment(AutoPlaceEnvironment parent) {
this(
parent.getSource(),
parent.fluidSource,
parent.getActor(),
parent.getChatter(),
parent.definition,
parent.piece,
parent.facing,
parent.offsetABC,
parent.baseOffsetABC);
parent.baseOffsetABC,
parent.basePositionXYZ,
parent.contextObject,
parent.fluidRoundState);
}
void setSource(IItemSource source) {
@@ -101,6 +140,33 @@ public class AutoPlaceEnvironment {
return source;
}
/**
* The fluid source this environment has been given, or null when it has none.
* <p>
* A structure element that has to place fluid blocks should ask {@link #getEffectiveFluidSource()} instead, which
* falls back to whatever the actor can offer when there is no explicit fluid source.
*/
@Nullable
public IFluidSource getFluidSource() {
return fluidSource;
}
/**
* From where survival autoplace will drain fluid.
* <p>
* This is the fluid source this environment has been given, or what the actor can offer when the actor is a server
* side player: the {@linkplain com.gtnewhorizon.structurelib.fluid.FluidSourceProviders registered fluid source
* providers}, e.g. the ME network behind a wireless terminal the player has on them, and then the fluid containers
* the player is carrying. It is null when the actor isn't a server side player and no fluid source has been given,
* in which case fluid blocks cannot be placed at all.
*/
@Nullable
public IFluidSource getEffectiveFluidSource() {
if (fluidSource != null) return fluidSource;
if (actor instanceof EntityPlayerMP) return FluidSourceProviders.getSourceFor((EntityPlayerMP) actor);
return null;
}
/**
* The initiator of actions. for very critical errors you can also just send the error messages here, bypassing any
* filter that {@link #getChatter()} might have. You might want to use
@@ -142,32 +208,153 @@ public class AutoPlaceEnvironment {
/**
* Return a new instance with source modified to given value.
* <p>
* The returned instance shares the fluid source, and every bookkeeping about the current autoplace round, with this
* one.
*
* @param source new source
* @return new instance
*/
public AutoPlaceEnvironment withSource(IItemSource source) {
return new AutoPlaceEnvironment(source, actor, chatter, definition, piece, facing, offsetABC, baseOffsetABC);
return new AutoPlaceEnvironment(
source,
fluidSource,
actor,
chatter,
definition,
piece,
facing,
offsetABC,
baseOffsetABC,
basePositionXYZ,
contextObject,
fluidRoundState);
}
/**
* Return a new instance with actor modified to given value.
* <p>
* The returned instance shares the fluid source, and every bookkeeping about the current autoplace round, with this
* one.
*
* @param actor new actor
* @return new instance
*/
public AutoPlaceEnvironment withActor(EntityPlayer actor) {
return new AutoPlaceEnvironment(source, actor, chatter, definition, piece, facing, offsetABC, baseOffsetABC);
return new AutoPlaceEnvironment(
source,
fluidSource,
actor,
chatter,
definition,
piece,
facing,
offsetABC,
baseOffsetABC,
basePositionXYZ,
contextObject,
fluidRoundState);
}
/**
* Return a new instance with chatter modified to given value.
* <p>
* The returned instance shares the fluid source, and every bookkeeping about the current autoplace round, with this
* one.
*
* @param chatter new chatter
* @return new instance
*/
public AutoPlaceEnvironment withChatter(Consumer<IChatComponent> chatter) {
return new AutoPlaceEnvironment(source, actor, chatter, definition, piece, facing, offsetABC, baseOffsetABC);
return new AutoPlaceEnvironment(
source,
fluidSource,
actor,
chatter,
definition,
piece,
facing,
offsetABC,
baseOffsetABC,
basePositionXYZ,
contextObject,
fluidRoundState);
}
/**
* Return a new instance with an explicit fluid source.
* <p>
* This is how a multiblock that wants its fluid to come from somewhere else than the player inventory, e.g. from a
* tank, hands its fluid source to autoplace.
*
* @param fluidSource new fluid source
* @return new instance
*/
public AutoPlaceEnvironment withFluidSource(@Nullable IFluidSource fluidSource) {
return new AutoPlaceEnvironment(
source,
fluidSource,
actor,
chatter,
definition,
piece,
facing,
offsetABC,
baseOffsetABC,
basePositionXYZ,
contextObject,
fluidRoundState);
}
IStructureDefinition<?> getDefinition() {
return definition;
}
String getPiece() {
return piece;
}
int[] getBaseOffsetABC() {
return baseOffsetABC;
}
@Nullable
int[] getBasePositionXYZ() {
return basePositionXYZ;
}
@Nullable
Object getContextObject() {
return contextObject;
}
/**
* The answer to the fluid placement gate of the current autoplace round, or null when it has not been asked yet.
*/
@Nullable
Boolean getFluidGateResult() {
return fluidRoundState == null ? null : fluidRoundState.getGateResult();
}
void setFluidGateResult(boolean ready) {
if (fluidRoundState != null) fluidRoundState.setGateResult(ready);
}
void clearFluidGateResult() {
if (fluidRoundState != null) fluidRoundState.clearGateResult();
}
/**
* Flag that at least one fluid element wanted to place its fluid, but had to wait for the structure to be built
* first. An autoplace round that did nothing but wait reports zero placed elements instead of reporting that the
* structure is done.
*/
void markFluidPlacementDeferred() {
if (fluidRoundState != null) fluidRoundState.markDeferred();
}
boolean isFluidPlacementDeferred() {
return fluidRoundState != null && fluidRoundState.isDeferred();
}
private static class WrappedIItemSource implements IItemSource {
@@ -207,6 +394,43 @@ public class AutoPlaceEnvironment {
}
}
/**
* Bookkeeping about the current autoplace round, shared by every instance {@link AutoPlaceEnvironment} hands out
* for itself. Implemented by the autoplace walker. Third parties should neither implement nor call this.
*/
public interface FluidRoundState {
/**
* The answer the fluid placement gate gave earlier in this round, or null when it has not been asked yet.
*/
@Nullable
Boolean getGateResult();
/**
* Remember the answer of the fluid placement gate for the rest of this round.
*/
void setGateResult(boolean ready);
/**
* Forget the answer of the fluid placement gate, so that it is asked again.
* <p>
* The answer describes the world as it was before this round built anything, so it has to be dropped once the
* round has placed something and the fluids that had to wait are retried. An implementation that keeps no
* answer at all can leave this alone.
*/
default void clearGateResult() {}
/**
* Remember that a fluid element had to wait for the structure to be built first.
*/
void markDeferred();
/**
* Whether any fluid element had to wait for the structure to be built in this round.
*/
boolean isDeferred();
}
/**
* Defines the various API level an {@link AutoPlaceEnvironment} has implemented.
* <p>
@@ -14,9 +14,7 @@ class ChatThrottleKey {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof NoExplicitChannel)) return false;
NoExplicitChannel that = (NoExplicitChannel) o;
if (!(o instanceof NoExplicitChannel that)) return false;
return subchannel.equals(that.subchannel);
}
@@ -1,14 +1,24 @@
package com.gtnewhorizon.structurelib.structure;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import com.gtnewhorizon.structurelib.fluid.IFluidSource;
class DefaultSurvivalBuildEnvironment implements ISurvivalBuildEnvironment {
private final IItemSource source;
private final IFluidSource fluidSource;
private final EntityPlayer actor;
public DefaultSurvivalBuildEnvironment(IItemSource source, EntityPlayer actor) {
this(source, null, actor);
}
public DefaultSurvivalBuildEnvironment(IItemSource source, @Nullable IFluidSource fluidSource, EntityPlayer actor) {
this.source = source;
this.fluidSource = fluidSource;
this.actor = actor;
}
@@ -17,6 +27,11 @@ class DefaultSurvivalBuildEnvironment implements ISurvivalBuildEnvironment {
return source;
}
@Override
public IFluidSource getFluidSource() {
return fluidSource;
}
@Override
public EntityPlayer getActor() {
return actor;
@@ -0,0 +1,335 @@
package com.gtnewhorizon.structurelib.structure;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidBlock;
import com.gtnewhorizon.gtnhlib.chat.customcomponents.ChatComponentFluid;
import com.gtnewhorizon.gtnhlib.chat.customcomponents.ChatComponentFluidName;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
import com.gtnewhorizon.structurelib.ConfigurationHandler;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.fluid.FluidAmounts;
import com.gtnewhorizon.structurelib.fluid.FluidBlockRequirement;
import com.gtnewhorizon.structurelib.fluid.FluidFillPolicy;
import com.gtnewhorizon.structurelib.fluid.IFluidSource;
import com.gtnewhorizon.structurelib.structure.IStructureElement.PlaceResult;
/**
* Autoplace of fluid blocks.
* <p>
* Placing a fluid is not the same as placing a block. A block stays where it was put, while a fluid flows out of an
* unfinished structure, floods the surroundings, and turns a partially filled position into something that no longer
* counts as a source block. This class handles that:
* <ul>
* <li>It only places a fluid once the rest of the structure is in place, so that the fluid has something to hold it.
* See {@link GateMode} for how strict that gate is.</li>
* <li>It charges only for the fluid that is actually missing from a position, so topping a position up after a leak
* costs the difference instead of a whole bucket.</li>
* <li>It only consumes fluid after the block has been placed successfully, and puts the previous block back if the
* fluid turns out to be gone by then.</li>
* </ul>
* Structure elements reach this class through
* {@link StructureUtility#survivalPlaceBlock(Block, int, World, int, int, int, IItemSource, EntityPlayer, Consumer)} or
* {@link StructureUtility#ofFluidBlock(Block, int)}, and custom elements may call
* {@link #tryPlace(World, int, int, int, AutoPlaceEnvironment, FluidBlockRequirement)} directly.
*/
public class FluidAutoplace {
/**
* How careful autoplace is about placing a fluid into a structure that is not finished yet.
*/
public enum GateMode {
/**
* Place the fluid right away. The fluid can flow out of the unfinished structure.
*/
NONE,
/**
* Only place the fluid when none of its six neighbours is a position that the fluid can flow into and that
* doesn't belong to the structure. The fluid can still flow into the part of the structure that is not built
* yet, but it cannot leave the structure.
*/
LENIENT,
/**
* Only place the fluid once every non fluid element of the structure is satisfied. This is the default.
* <p>
* The fluid is placed as soon as the structure can hold it, which is normally the round that finishes the
* structure: the fluids that round could not place yet are tried once more when it is done building, so they do
* not have to wait for another round.
*/
STRICT
}
private FluidAutoplace() {}
/**
* Try to place a fluid block, draining the fluid from the autoplace environment's fluid source.
* <p>
* Nothing is consumed when this returns anything other than {@link PlaceResult#ACCEPT}, and the block that was
* there before is put back when the fluid cannot be taken after the block has been placed.
*
* @param world world to place in
* @param x x coord
* @param y y coord
* @param z z coord
* @param env autoplace environment, providing the fluid source, the actor and the chatter
* @param requirement which block the structure wants there, what it costs, and how strict the check is
* @return {@link PlaceResult#SKIP} when the position is already good enough, {@link PlaceResult#ACCEPT} when the
* fluid block has been placed, {@link PlaceResult#REJECT_CONTINUE} when the structure is not ready for its
* fluid yet or fluid autoplace is off, and {@link PlaceResult#REJECT} when the fluid is missing
*/
public static PlaceResult tryPlace(World world, int x, int y, int z, AutoPlaceEnvironment env,
FluidBlockRequirement requirement) {
if (world.isRemote || !ConfigurationHandler.INSTANCE.isFluidAutoplaceEnabled()) {
return PlaceResult.REJECT_CONTINUE;
}
if (isSatisfied(world, x, y, z, requirement)) return PlaceResult.SKIP;
if (!canReplace(world, x, y, z, env.getActor())) return PlaceResult.REJECT;
if (!isGateOpen(world, x, y, z, env)) {
env.markFluidPlacementDeferred();
return PlaceResult.REJECT_CONTINUE;
}
IFluidSource source = env.getEffectiveFluidSource();
if (source == null) {
reportMissingFluid(env, requirement, requirement.cost().amount);
return PlaceResult.REJECT;
}
Block existingBlock = world.getBlock(x, y, z);
int existingMeta = world.getBlockMetadata(x, y, z);
int target = requirement.cost().amount;
int existing = existingBlock == requirement.block() ? FluidAmounts.getStoredAmount(world, x, y, z, target) : 0;
int missing = Math.max(0, target - existing);
if (missing > 0 && !source.takeAll(new FluidStack(requirement.cost(), missing), true)) {
reportMissingFluid(
env,
requirement,
missing - source.getAvailable(new FluidStack(requirement.cost(), missing)));
return PlaceResult.REJECT;
}
if (!placeFluidBlock(world, x, y, z, requirement)) return PlaceResult.REJECT;
if (missing > 0 && !source.takeAll(new FluidStack(requirement.cost(), missing), false)) {
restore(world, x, y, z, existingBlock, existingMeta);
return PlaceResult.REJECT;
}
return PlaceResult.ACCEPT;
}
/**
* Try to place one of several fluid blocks, in order, and stop at the first one that is already there or that could
* be placed.
*
* @return the result of the first attempt that was more than a {@link PlaceResult#REJECT_CONTINUE}, or
* {@link PlaceResult#REJECT} when the fluid of an alternative was missing, or
* {@link PlaceResult#REJECT_CONTINUE} when every alternative had to wait
* @see #tryPlace(World, int, int, int, AutoPlaceEnvironment, FluidBlockRequirement)
*/
public static PlaceResult tryPlace(World world, int x, int y, int z, AutoPlaceEnvironment env,
Iterable<FluidBlockRequirement> requirements) {
PlaceResult result = PlaceResult.REJECT_CONTINUE;
for (FluidBlockRequirement requirement : requirements) {
PlaceResult attempt = tryPlace(world, x, y, z, env, requirement);
if (attempt == PlaceResult.REJECT_CONTINUE) continue;
if (attempt == PlaceResult.REJECT) {
result = PlaceResult.REJECT;
continue;
}
return attempt;
}
return result;
}
/**
* Whether the position already holds as much fluid as the structure asks for.
* <p>
* This is what a fluid structure element uses for its check, so that a check and an autoplace always agree.
*
* @param world world to look at
* @param x x coord
* @param y y coord
* @param z z coord
* @param requirement which block the structure wants there, and how strict the check is
*/
public static boolean isSatisfied(World world, int x, int y, int z, FluidBlockRequirement requirement) {
Block worldBlock = world.getBlock(x, y, z);
if (worldBlock != requirement.block()) return false;
if (world.getBlockMetadata(x, y, z) == requirement.meta()) return true;
if (requirement.policy() == FluidFillPolicy.EXACT_STATE) return false;
int target = requirement.cost().amount;
return requirement.policy().isSatisfied(FluidAmounts.getStoredAmount(world, x, y, z, target), target);
}
/**
* Put the fluid block into the world without paying for it, which is what a creative mode build does.
* <p>
* Unlike {@link #tryPlace(World, int, int, int, AutoPlaceEnvironment, FluidBlockRequirement)} this does not check
* whether the structure is ready to hold the fluid. A creative mode build places everything that isn't a fluid
* first for that reason.
*
* @return true if the block has been placed
*/
public static boolean place(World world, int x, int y, int z, FluidBlockRequirement requirement) {
return placeFluidBlock(world, x, y, z, requirement);
}
/**
* Returns a human-readable description of the structure element requirement.
*/
public static String describe(FluidBlockRequirement requirement) {
FluidStack stack = requirement.cost();
return StatCollector.translateToLocalFormatted(
"structurelib.autoplace.requirement_fluid",
stack.getLocalizedName(),
NumberFormatUtil.formatFluid(stack.amount));
}
/**
* Whether a fluid may be placed at this position right now.
* <p>
* With {@link GateMode#STRICT} the answer is computed by a walk over the whole structure and cached for the rest of
* the round, as that walk is expensive. The cache is dropped as soon as the round has built something, so that the
* fluids which waited for it are not held back by an answer that predates those placements.
*
* @param world world to place in
* @param x x coord
* @param y y coord
* @param z z coord
* @param env autoplace environment
*/
public static boolean isGateOpen(World world, int x, int y, int z, AutoPlaceEnvironment env) {
GateMode mode = ConfigurationHandler.INSTANCE.getFluidGateMode();
if (mode == GateMode.NONE) return true;
if (mode == GateMode.LENIENT) return isLocallyContained(world, x, y, z, env);
Boolean cached = env.getFluidGateResult();
if (cached != null) return cached;
boolean ready = isStructureReady(world, env);
env.setFluidGateResult(ready);
return ready;
}
/**
* Whether every non fluid element of the structure is satisfied, i.e. whether the structure is built far enough to
* hold the fluid.
* <p>
* An autoplace environment that doesn't know its structure, e.g. one handed to a legacy caller, always answers
* true, as there is nothing to be checked against.
*/
private static boolean isStructureReady(World world, AutoPlaceEnvironment env) {
IStructureDefinition<?> definition = env.getDefinition();
int[] base = env.getBasePositionXYZ();
if (definition == null || base == null) return true;
Object context = env.getContextObject();
int[] baseOffset = env.getBaseOffsetABC();
ExtendedFacing facing = env.getFacing();
IStructureElement<Object>[] elements = getElements(definition, env.getPiece());
if (elements == null) return true;
return StructureUtility.iterateV2(
elements,
world,
facing,
base[0],
base[1],
base[2],
baseOffset[0],
baseOffset[1],
baseOffset[2],
(element, w, ex, ey, ez, a, b, c) -> element.isFluidElement(context)
|| element.check(context, w, ex, ey, ez),
"fluid gate");
}
@SuppressWarnings("unchecked")
@Nullable
private static IStructureElement<Object>[] getElements(IStructureDefinition<?> definition, String piece) {
try {
return (IStructureElement<Object>[]) definition.getStructureFor(piece);
} catch (RuntimeException e) {
StructureLib.LOGGER
.warn("Could not look up structure piece {} to check whether it can hold fluid", piece, e);
return null;
}
}
/**
* Whether the fluid cannot flow out of the structure from this position, i.e. whether every neighbour is either
* blocked, or part of the structure and therefore eventually filled by it.
*/
private static boolean isLocallyContained(World world, int x, int y, int z, AutoPlaceEnvironment env) {
ExtendedFacing facing = env.getFacing();
// An environment that doesn't know the structure cannot tell which neighbours belong to it. Don't block then.
if (facing == null) return true;
int[] abcOffset = new int[3];
int[] xyzOffset = new int[3];
for (ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) {
int nx = x + direction.offsetX;
int ny = y + direction.offsetY;
int nz = z + direction.offsetZ;
if (isBlocking(world, nx, ny, nz)) continue;
xyzOffset[0] = direction.offsetX;
xyzOffset[1] = direction.offsetY;
xyzOffset[2] = direction.offsetZ;
facing.getOffsetABC(xyzOffset, abcOffset);
if (env.isContainedInPiece(abcOffset[0], abcOffset[1], abcOffset[2])) continue;
return false;
}
return true;
}
private static boolean isBlocking(World world, int x, int y, int z) {
Block block = world.getBlock(x, y, z);
if (block == null) return true;
if (block.isAir(world, x, y, z)) return false;
if (block.getMaterial() != null && block.getMaterial().isLiquid()) return false;
return !block.isReplaceable(world, x, y, z);
}
private static boolean canReplace(World world, int x, int y, int z, EntityPlayer actor) {
Block block = world.getBlock(x, y, z);
if (block == null || block.isAir(world, x, y, z)) return true;
if (block.getMaterial() != null && block.getMaterial().isLiquid()) return true;
if (block instanceof IFluidBlock) return true;
return StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor);
}
private static boolean placeFluidBlock(World world, int x, int y, int z, FluidBlockRequirement requirement) {
FluidStack fluid = requirement.cost();
Block block = requirement.block();
if (requirement.placer() != null) {
if (!requirement.placer().place(world, x, y, z, block, requirement.meta(), fluid)) return false;
} else {
// The notification flags matter here. A fluid that is put into the world silently neither flows nor tells
// its neighbours about itself, so it would sit where it was placed until something else happens to touch
// it, which for water inside a multiblock can be never.
if (!world.setBlock(x, y, z, block, requirement.meta(), 3)) return false;
}
// A fluid that is never ticked does not spread, and a fluid placed as a flowing one would never settle.
world.scheduleBlockUpdate(x, y, z, block, block.tickRate(world));
return true;
}
private static void restore(World world, int x, int y, int z, Block block, int meta) {
StructureLibAPI.restoreBlock(world, x, y, z, block, meta);
}
private static void reportMissingFluid(AutoPlaceEnvironment env, FluidBlockRequirement requirement, int missing) {
Consumer<IChatComponent> chatter = env.getChatter();
if (chatter == null) return;
FluidStack stack = new FluidStack(requirement.cost(), Math.max(1, missing));
chatter.accept(
new ChatComponentTranslation(
"structurelib.autoplace.missing_fluid",
new ChatComponentFluidName(stack),
new ChatComponentFluid(stack)));
}
}
@@ -10,8 +10,10 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.ConfigurationHandler;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
@@ -50,7 +52,7 @@ import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
* itself.</li>
* <li>The "C" position would be the number of blocks between you and controller, not counting controller itself.</li>
* </ul>
*
*
* @param <T> Type of the context object. Usually this will be the multiblock controller.
*/
public interface IStructureDefinition<T> {
@@ -72,7 +74,7 @@ public interface IStructureDefinition<T> {
/**
* Run a structure check.
*
*
* @param object context object. usually multiblock controller.
* @param piece the structure piece's string identifier.
* @param world the world object this check takes place in.
@@ -107,7 +109,7 @@ public interface IStructureDefinition<T> {
/**
* Spawn hint particles. Should not be called on server side.
*
*
* @param object context object. usually multiblock controller.
* @param piece the structure piece's string identifier.
* @param world the world object this check takes place in.
@@ -302,6 +304,7 @@ public interface IStructureDefinition<T> {
piece,
extendedFacing,
new int[] { basePositionA, basePositionB, basePositionC },
new int[] { basePositionX, basePositionY, basePositionZ },
check);
StructureUtility.iterateV2(
getStructureFor(piece),
@@ -315,12 +318,31 @@ public interface IStructureDefinition<T> {
basePositionC,
walker,
"survivalBuild");
// A fluid position is often visited before the blocks that hold it, so give the fluids that had to wait for
// those blocks a chance to be placed in this round rather than the next one.
walker.finishRound(world);
return walker.getBuilt();
}
default void iterate(String piece, World world, ExtendedFacing extendedFacing, int basePositionX, int basePositionY,
int basePositionZ, int basePositionA, int basePositionB, int basePositionC, IStructureWalker<T> predicate) {
StructureUtility.iterateV2(
getStructureFor(piece),
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
predicate,
"customIterate");
}
/**
* Low level utility.
*
*
* @param object context object. usually multiblock controller.
* @param trigger The trigger item that contains channel data.
* @param elements the structure piece
@@ -394,10 +416,14 @@ public interface IStructureDefinition<T> {
basePositionC,
ignoreBlockUnloaded((e, w, x, y, z, a, b, c) -> {
e.spawnHint(object, world, x, y, z, trigger);
if (ChannelDataAccessor.hasSubChannel(trigger, StructureLibAPI.CHANNEL_SHOW_ERROR)
&& !e.couldBeValid(object, world, x, y, z, trigger)) {
StructureLibAPI.markHintParticleError(StructureLib.getCurrentPlayer(), world, x, y, z);
}
return true;
}),
"spawnHint");
} else {
} else if (ConfigurationHandler.INSTANCE.getFluidGateMode() == FluidAutoplace.GateMode.NONE) {
StructureUtility.iterateV2(
elements,
world,
@@ -413,6 +439,40 @@ public interface IStructureDefinition<T> {
return true;
}),
"placeBlock");
} else {
// Build everything that isn't a fluid first, then fill the structure with fluid. That way a fluid has
// something holding it by the time it is placed. This is the creative mode counterpart of the fluid
// placement gate that survival autoplace uses.
StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
ignoreBlockUnloaded((e, w, x, y, z, a, b, c) -> {
if (!e.isFluidElement(object)) e.placeBlock(object, world, x, y, z, trigger);
return true;
}),
"placeBlock");
StructureUtility.iterateV2(
elements,
world,
extendedFacing,
basePositionX,
basePositionY,
basePositionZ,
basePositionA,
basePositionB,
basePositionC,
ignoreBlockUnloaded((e, w, x, y, z, a, b, c) -> {
if (e.isFluidElement(object)) e.placeBlock(object, world, x, y, z, trigger);
return true;
}),
"placeFluid");
}
}
return true;
@@ -420,7 +480,7 @@ public interface IStructureDefinition<T> {
/**
* Create a new instance of builder.
*
*
* @param <T> type of context object
*/
static <T> StructureDefinition.Builder<T> builder() {
@@ -3,8 +3,10 @@ package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.StructureLib.LOGGER;
import static com.gtnewhorizon.structurelib.StructureLib.PANIC_MODE;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -21,6 +23,10 @@ import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.fluid.FluidBlockPlacement;
import com.gtnewhorizon.structurelib.fluid.FluidBlockRequirement;
import com.gtnewhorizon.structurelib.fluid.FluidFillPolicy;
import com.gtnewhorizon.structurelib.fluid.FluidPlacementRegistry;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
@@ -32,6 +38,40 @@ public interface IStructureElement<T> {
boolean check(T t, World world, int x, int y, int z);
/**
* Pure (stateless and side effect free) function to test if current block could be valid. Used to give user hints
* about incorrectly placed blocks given a controller and trigger item. If couldBeValid(...) == false for a set of
* channels, with those same tiers, check(...) == false. Not required, defaults to true which is always safe but
* won't give the user error hints.
*/
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
}
/**
* Returns a human-readable description of what block(s) this element accepts. Used for diagnostic messages when
* structure checks fail (e.g. "expected Input Bus at (1, 2, 3)").
* <p>
* Unlike {@link #getBlocksToPlace}, which returns the full set of concrete block variants for autoplacing (e.g.
* every tier of Input Bus), this method returns <b>category-level</b> descriptions suitable for display to the
* player (e.g. just "Input Bus"). It also requires no parameters, no world, trigger item, or environment, making it
* usable in contexts where those are unavailable.
* <p>
* Implementations should return <b>lang keys</b> (e.g. {@code "tile.blockGlass.name"}) rather than pre-translated
* display names. The caller is responsible for translating these keys on the client side via
* {@code StatCollector.translateToLocal()}. If a key has no matching translation, {@code translateToLocal} returns
* the input string unchanged, so pre-translated fallback strings also work.
*
* @param context the context object (e.g. the multiblock controller), used to determine state-dependent
* descriptions
* @return a list of accepted block descriptions as lang keys (or display names as fallback), or null if no
* description is available
*/
@Nullable
default List<String> getDescription(T context) {
return null;
}
boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger);
boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger);
@@ -61,7 +101,7 @@ public interface IStructureElement<T> {
"Default implementation of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}",
getClass().getName());
if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT;
return PlaceResult.SKIP;
return PlaceResult.REJECT_CONTINUE;
}
/**
@@ -90,6 +130,23 @@ public interface IStructureElement<T> {
return null;
}
/**
* Whether this element is responsible for placing fluid blocks, e.g. an element that accepts a water block created
* by {@link StructureUtility#ofBlock(Block, int)} or {@link StructureUtility#ofFluidBlock(Block, int)}.
* <p>
* Autoplace uses this to keep a fluid from flowing out of a structure that is not finished yet: a fluid is only
* placed once every element that does not answer true has been satisfied. An element that wraps another element
* must forward this call, otherwise a fluid inside of it is treated as a block that still has to be built, and is
* never placed at all.
* <p>
* The default is false, which is the safe answer for every element that was written before fluid autoplace existed.
*
* @param t the context object, used to resolve an element that is built on demand
*/
default boolean isFluidElement(T t) {
return false;
}
/**
* Try place the block by taking resource from given {@link IItemSource}.
* <p>
@@ -105,7 +162,7 @@ public interface IStructureElement<T> {
* <li>call {@link #check(Object, World, int, int, int)}. If this returns {@code true}, {@link PlaceResult#SKIP}
* will be returned without further action.</li>
* <li>Use the {@link BlocksToPlace} retrieved earlier and passed in {@link IItemSource} to determine an item to
* place</li>
* place, or the fluid it carries to place a fluid block</li>
* <li>Hand over control to
* {@link StructureUtility#survivalPlaceBlock(ItemStack, NBTMode, NBTTagCompound, boolean, World, int, int, int, IItemSource, EntityPlayer, Consumer)}</li>
* </ol>
@@ -135,6 +192,10 @@ public interface IStructureElement<T> {
if (check(t, world, x, y, z)) return PlaceResult.SKIP;
if (e.getStacks() == null) {
ItemStack taken = source.takeOne(e.getPredicate(), true);
if (taken == null) {
return e.getFluidRequirements().isEmpty() ? PlaceResult.REJECT
: FluidAutoplace.tryPlace(world, x, y, z, env, e.getFluidRequirements());
}
return StructureUtility.survivalPlaceBlock(
taken,
NBTMode.EXACT,
@@ -163,7 +224,8 @@ public interface IStructureElement<T> {
actor,
chatter);
}
return PlaceResult.REJECT;
return e.getFluidRequirements().isEmpty() ? PlaceResult.REJECT
: FluidAutoplace.tryPlace(world, x, y, z, env, e.getFluidRequirements());
}
if (actor instanceof EntityPlayerMP)
return survivalPlaceBlock(t, world, x, y, z, trigger, source, (EntityPlayerMP) actor, chatter);
@@ -171,7 +233,7 @@ public interface IStructureElement<T> {
if (StructureLibAPI.isDebugEnabled()) LOGGER.info(
"Fallback shim code of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}",
getClass().getName());
return PlaceResult.SKIP;
return PlaceResult.REJECT_CONTINUE;
}
/**
@@ -185,10 +247,21 @@ public interface IStructureElement<T> {
return IStructureElement.this.check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return IStructureElement.this.couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return IStructureElement.this.spawnHint(t, world, x, y, z, trigger);
}
@Nullable
@Override
public List<String> getDescription(T context) {
return IStructureElement.this.getDescription(context);
}
};
}
@@ -222,16 +295,21 @@ public interface IStructureElement<T> {
enum PlaceResult {
/**
* This element either exists already, or does not yet have an implementation for survivalPlaceBlock, or some
* other unforeseen situations. TODO this definition doesn't seem right. Should we separate SKIP from EXISTS, or
* SKIP from ERROR?
* The element's check passed, the position is already valid. No placement is needed. In the walker: continue
* iteration (no error, not counted as placed). In ofChain: short-circuits, remaining alternatives are skipped.
*/
SKIP,
/**
* This element's space is occupied by other stuff and require player attention, or player missing required
* resource, or the block cannot be placed due to obscure mechanisms, or some other unforeseen situations.
* The element cannot handle this position (occupied, missing resources, etc.). In the walker: stop iteration
* with error particles. In ofChain: try next alternative.
*/
REJECT,
/**
* This element has no survivalPlaceBlock implementation (default fallback), or otherwise cannot place but is
* not an error condition. In the walker: continue iteration silently (like SKIP). In ofChain: try next
* alternative (like REJECT), so a better-suited element can handle it.
*/
REJECT_CONTINUE,
/**
* Autoplace cannot proceed within this tick. To proceed further would require stopping the placement and wait
* for next round.
@@ -254,6 +332,7 @@ public interface IStructureElement<T> {
public static final BlocksToPlace errored = createEmpty();
private final Predicate<ItemStack> predicate;
private final Iterable<ItemStack> stacks;
private final List<FluidBlockRequirement> fluidRequirements;
public static BlocksToPlace createEmpty() {
return new BlocksToPlace(s -> false, Collections.emptyList());
@@ -275,8 +354,22 @@ public interface IStructureElement<T> {
return new BlocksToPlace(predicate, stacks);
}
/**
* Accept a block state, describing what has to be paid for it.
* <p>
* A block that has no item form, e.g. a fluid block, is described by what it costs to place it with fluid. Such
* a block can only be placed in survival mode when fluid autoplace knows how to pay for it.
*/
public static BlocksToPlace create(Block block, int meta) {
FluidBlockPlacement placement = FluidPlacementRegistry.resolve(block, meta);
Item itemBlock = Item.getItemFromBlock(block);
if (itemBlock == null) {
if (placement == null) return createEmpty();
return createFluid(FluidBlockRequirement.of(placement, block, meta, FluidFillPolicy.EXACT_STATE));
}
if (placement != null && placement.forceFluid()) {
return createFluid(FluidBlockRequirement.of(placement, block, meta, FluidFillPolicy.EXACT_STATE));
}
if (itemBlock instanceof ISpecialItemBlock) {
meta = ((ISpecialItemBlock) itemBlock).getItemMetaFromBlockMeta(block, meta);
}
@@ -297,9 +390,33 @@ public interface IStructureElement<T> {
return new BlocksToPlace(predicate, null);
}
/**
* Describe a block state that is paid for with fluid instead of with an item.
*/
public static BlocksToPlace createFluid(FluidBlockRequirement... requirements) {
return createFluid(Arrays.asList(requirements));
}
/**
* Describe block states that are paid for with fluid instead of with an item.
*/
public static BlocksToPlace createFluid(Iterable<FluidBlockRequirement> requirements) {
List<FluidBlockRequirement> list = new ArrayList<>();
for (FluidBlockRequirement requirement : requirements) {
if (requirement != null) list.add(requirement);
}
return new BlocksToPlace(s -> false, Collections.emptyList(), list);
}
BlocksToPlace(Predicate<ItemStack> predicate, Iterable<ItemStack> stacks) {
this(predicate, stacks, Collections.emptyList());
}
BlocksToPlace(Predicate<ItemStack> predicate, Iterable<ItemStack> stacks,
List<FluidBlockRequirement> fluidRequirements) {
this.predicate = predicate;
this.stacks = stacks;
this.fluidRequirements = fluidRequirements;
}
/**
@@ -326,5 +443,18 @@ public interface IStructureElement<T> {
public Iterable<ItemStack> getStacks() {
return stacks;
}
/**
* Get the block states that this one is known to accept, and that have to be paid for with fluid.
* <p>
* Suitable for use with {@link FluidAutoplace#tryPlace(World, int, int, int, AutoPlaceEnvironment, Iterable)}.
* Item forms are tried first, so this is only consulted when no item was found.
*
* @return a possibly empty list. never null. do not mutate it.
*/
@Nonnull
public List<FluidBlockRequirement> getFluidRequirements() {
return fluidRequirements;
}
}
}
@@ -1,7 +1,9 @@
package com.gtnewhorizon.structurelib.structure;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -13,6 +15,7 @@ import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import com.google.common.collect.Iterables;
import com.gtnewhorizon.structurelib.fluid.FluidBlockRequirement;
/**
* Use StructureUtility to instantiate
@@ -31,6 +34,16 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
return false;
}
@Override
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
for (IStructureElement<T> fallback : fallbacks()) {
if (fallback.couldBeValid(t, world, x, y, z, trigger)) {
return true;
}
}
return false;
}
@Override
default boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
for (IStructureElement<T> fallback : fallbacks()) {
@@ -41,6 +54,18 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
return false;
}
/**
* A chain counts as a fluid element as soon as one of its fallbacks is one, as the fluid it places is paid for with
* fluid even though another fallback might have been satisfied by an item.
*/
@Override
default boolean isFluidElement(T t) {
for (IStructureElement<T> fallback : fallbacks()) {
if (fallback.isFluidElement(t)) return true;
}
return false;
}
@Override
default boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
for (IStructureElement<T> fallback : fallbacks()) {
@@ -51,67 +76,87 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
return false;
}
@Nullable
@Override
default List<String> getDescription(T context) {
Set<String> descriptions = new LinkedHashSet<>();
for (IStructureElement<T> fallback : fallbacks()) {
List<String> desc = fallback.getDescription(context);
if (desc != null) {
descriptions.addAll(desc);
}
}
return descriptions.isEmpty() ? null : new ArrayList<>(descriptions);
}
@Nullable
@Override
default BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
Predicate<ItemStack> predicate = null;
List<Iterable<ItemStack>> is = new ArrayList<>();
List<FluidBlockRequirement> fluids = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) {
BlocksToPlace e = fallback.getBlocksToPlace(t, world, x, y, z, trigger, env);
if (e == null) continue;
if (predicate == null) predicate = e.getPredicate();
else predicate = predicate.or(e.getPredicate());
is.add(e.getStacks());
Iterable<ItemStack> stacks = e.getStacks();
if (stacks != null) is.add(stacks);
fluids.addAll(e.getFluidRequirements());
}
if (predicate == null) return null;
return new BlocksToPlace(predicate, Iterables.concat(is));
return new BlocksToPlace(predicate, Iterables.concat(is), fluids);
}
@Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s,
EntityPlayerMP actor, Consumer<IChatComponent> chatter) {
boolean haveSkip = false;
boolean allContinue = true;
List<IChatComponent> bufferedNoise = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) {
PlaceResult result = fallback.survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, bufferedNoise::add);
switch (result) {
case REJECT_CONTINUE:
break;
case REJECT:
allContinue = false;
break;
case SKIP:
haveSkip = true;
break;
bufferedNoise.forEach(chatter);
return PlaceResult.SKIP;
default:
return result;
}
}
// dump all that noise back into upstream
bufferedNoise.forEach(chatter);
// TODO need reconsider to ensure this is the right course of action
return haveSkip ? PlaceResult.SKIP : PlaceResult.REJECT;
return allContinue ? PlaceResult.REJECT_CONTINUE : PlaceResult.REJECT;
}
@Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
boolean haveSkip = false;
boolean allContinue = true;
List<IChatComponent> bufferedNoise = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) {
PlaceResult result = fallback
.survivalPlaceBlock(t, world, x, y, z, trigger, env.withChatter(bufferedNoise::add));
switch (result) {
case REJECT_CONTINUE:
break;
case REJECT:
allContinue = false;
break;
case SKIP:
haveSkip = true;
break;
bufferedNoise.forEach(env.getChatter());
return PlaceResult.SKIP;
default:
return result;
}
}
// dump all that noise back into upstream
bufferedNoise.forEach(env.getChatter());
// TODO need reconsider to ensure this is the right course of action
return haveSkip ? PlaceResult.SKIP : PlaceResult.REJECT;
return allContinue ? PlaceResult.REJECT_CONTINUE : PlaceResult.REJECT;
}
}
@@ -14,6 +14,11 @@ public interface IStructureElementCheckOnly<T> extends IStructureElement<T> {
return false;
}
@Override
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
}
@Override
default boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return false;
@@ -22,12 +27,12 @@ public interface IStructureElementCheckOnly<T> extends IStructureElement<T> {
@Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s,
EntityPlayerMP actor, Consumer<IChatComponent> chatter) {
return PlaceResult.SKIP;
return PlaceResult.REJECT_CONTINUE;
}
@Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger,
AutoPlaceEnvironment env) {
return PlaceResult.SKIP;
return PlaceResult.REJECT_CONTINUE;
}
}
@@ -17,6 +17,11 @@ interface IStructureNavigate<T> extends IStructureElement<T> {
return true;
}
@Override
default boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
}
@Override
default boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger) {
return true;
@@ -2,8 +2,25 @@ package com.gtnewhorizon.structurelib.structure;
import net.minecraft.world.World;
interface IStructureWalker<T> {
/**
* A functional interface that is used to iterate over an arbitrary structure.
*/
@FunctionalInterface
public interface IStructureWalker<T> {
/**
* Called once per structure element.
*
* @param element The current element
* @param world The current world
* @param x The absolute X position of the element in world coordinates
* @param y The absolute Y position of the element in world coordinates
* @param z The absolute Z position of the element in world coordinates
* @param a The relative A position of the element in structure-local coordinates (pre transform)
* @param b The relative B position of the element in structure-local coordinates (pre transform)
* @param c The relative C position of the element in structure-local coordinates (pre transform)
* @return False to stop iterating, true to continue.
*/
boolean visit(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c);
default boolean blockNotLoaded(IStructureElement<T> element, World world, int x, int y, int z, int a, int b,
@@ -1,10 +1,13 @@
package com.gtnewhorizon.structurelib.structure;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.fluid.FluidSourceProviders;
import com.gtnewhorizon.structurelib.fluid.IFluidSource;
/*
* Architecture notes: this should never get any callback from survival build. All structure significant code belongs
@@ -22,6 +25,46 @@ public interface ISurvivalBuildEnvironment {
*/
IItemSource getSource();
/**
* Get the source of the fluid, which autoplace drains when a structure element has to place a fluid block.
* <p>
* Returning null is fine, and is what every existing implementation does. Autoplace then falls back to draining the
* fluid containers held by {@link #getActor()} when it is a server side player, and refuses to place fluid blocks
* when there is no way to pay for them at all.
* <p>
* A multiblock that wants its fluid to come from somewhere else than the player inventory, e.g. from its own tank,
* returns its own source here. A multiblock that receives an environment from its caller can wrap it with
* {@link #withFluidSource(ISurvivalBuildEnvironment, IFluidSource)}. See {@link IFluidSource} for the sources
* StructureLib can build out of the box.
*/
default IFluidSource getFluidSource() {
return null;
}
/**
* Get the fluid source autoplace will actually drain from, which is the source this environment has been given, or
* a source built from what the actor can offer when there is none and the actor is a server side player: first
* every provider registered with {@link FluidSourceProviders}, then the fluid containers the actor is carrying.
* <p>
* This is what a multiblock that wants to put a source of its own in front of the player's own ones combines it
* with, e.g. to prefer an ME network it is attached to and keep the player's buckets as a fallback:
*
* <pre>
* env = ISurvivalBuildEnvironment.withFluidSource(
* env,
* IFluidSource.composite(IFluidSource.fromHandler(myTank), env.getEffectiveFluidSource()));
* </pre>
*
* @return the source, or null when there is none, i.e. when the actor isn't a server side player and no source has
* been given
*/
default IFluidSource getEffectiveFluidSource() {
IFluidSource source = getFluidSource();
if (source != null) return source;
if (getActor() instanceof EntityPlayerMP) return FluidSourceProviders.getSourceFor((EntityPlayerMP) getActor());
return null;
}
/**
* Get the origin of action. This will be invoked at least once per
* {@link IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, ISurvivalBuildEnvironment, boolean)}
@@ -29,6 +72,40 @@ public interface ISurvivalBuildEnvironment {
*/
EntityPlayer getActor();
/**
* Replace the fluid source of an environment, keeping everything else the same.
* <p>
* This is what a multiblock uses when it wants its fluid to come from its own tank instead of from the player, as
* the environment it receives comes from its caller:
*
* <pre>
* env = ISurvivalBuildEnvironment.withFluidSource(env, IFluidSource.fromHandler(myTank));
* </pre>
*
* @param env the environment to take the item source and the actor from
* @param fluidSource the fluid source to use, or null to fall back to the player inventory
*/
static ISurvivalBuildEnvironment withFluidSource(ISurvivalBuildEnvironment env, IFluidSource fluidSource) {
if (env == null) throw new IllegalArgumentException();
return new ISurvivalBuildEnvironment() {
@Override
public IItemSource getSource() {
return env.getSource();
}
@Override
public IFluidSource getFluidSource() {
return fluidSource;
}
@Override
public EntityPlayer getActor() {
return env.getActor();
}
};
}
/**
* Create a default implementation with three parameters all being constants.
*
@@ -36,6 +113,17 @@ public interface ISurvivalBuildEnvironment {
* @param actor source of action
*/
static ISurvivalBuildEnvironment create(IItemSource source, EntityPlayer actor) {
return new DefaultSurvivalBuildEnvironment(source, actor);
return new DefaultSurvivalBuildEnvironment(source, null, actor);
}
/**
* Create a default implementation with three parameters all being constants.
*
* @param source from where to drain items
* @param fluidSource from where to drain fluid, or null to drain the fluid containers held by the actor
* @param actor source of action
*/
static ISurvivalBuildEnvironment create(IItemSource source, IFluidSource fluidSource, EntityPlayer actor) {
return new DefaultSurvivalBuildEnvironment(source, fluidSource, actor);
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizon.structurelib.structure;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -32,6 +33,11 @@ class LazyStructureElement<T> implements IStructureElementDeferred<T> {
return get(t).check(t, world, x, y, z);
}
@Override
public boolean couldBeValid(T t, World world, int x, int y, int z, ItemStack trigger) {
return get(t).couldBeValid(t, world, x, y, z, trigger);
}
@Override
public boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return get(t).placeBlock(t, world, x, y, z, trigger);
@@ -42,6 +48,12 @@ class LazyStructureElement<T> implements IStructureElementDeferred<T> {
return get(t).spawnHint(t, world, x, y, z, trigger);
}
@Override
public boolean isFluidElement(T t) {
IStructureElement<T> element = get(t);
return element != null && element.isFluidElement(t);
}
@Nullable
@Override
public BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger,
@@ -60,4 +72,10 @@ class LazyStructureElement<T> implements IStructureElementDeferred<T> {
AutoPlaceEnvironment env) {
return get(t).survivalPlaceBlock(t, world, x, y, z, trigger, env);
}
@Nullable
@Override
public List<String> getDescription(T context) {
return elem != null ? elem.getDescription(context) : null;
}
}
@@ -1,8 +1,15 @@
package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.*;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.isAir;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.notAir;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.step;
import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.stream.Collectors;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
@@ -141,15 +148,32 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
occupiedSpaces.put(name, occupiedSpace);
String built = builder.toString().replaceAll("[\\uA000\\uB000\\uC000]", "");
boolean hasPlus = false;
boolean hasMinus = false;
if (built.contains("+")) {
int write = 0;
for (int read = 0; read < builder.length(); read++) {
char ch = builder.charAt(read);
if (ch == A || ch == B || ch == C) {
continue;
}
if (ch == '+') {
hasPlus = true;
} else if (ch == '-') {
hasMinus = true;
}
if (read != write) builder.setCharAt(write, ch);
write++;
}
builder.setLength(write);
if (hasPlus) {
addElement('+', notAir());
}
if (built.contains("-")) {
if (hasMinus) {
addElement('-', isAir());
}
shapes.put(name, built);
shapes.put(name, builder.toString());
return this;
}
File diff suppressed because it is too large. Load diff
@@ -1,13 +1,19 @@
package com.gtnewhorizon.structurelib.structure;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.github.bsideup.jabel.Desugar;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.IStructureElement.PlaceResult;
class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
class SurvivalBuildStructureWalker<T> implements IStructureWalker<T>, AutoPlaceEnvironment.FluidRoundState {
final T object;
final ItemStack trigger;
@@ -16,11 +22,15 @@ class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
private final boolean check;
private int built = -1;
private Boolean fluidGateResult;
private boolean fluidDeferred;
private final List<DeferredFluid<T>> deferredFluids = new ArrayList<>();
private final AutoPlaceEnvironment env;
public SurvivalBuildStructureWalker(T object, ItemStack trigger, int elementBudget,
ISurvivalBuildEnvironment params, IStructureDefinition<?> definition, String piece, ExtendedFacing facing,
int[] baseOffsetABC, boolean check) {
int[] baseOffsetABC, int[] basePositionXYZ, boolean check) {
this.object = object;
this.trigger = trigger;
this.elementBudget = elementBudget;
@@ -33,7 +43,11 @@ class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
definition,
piece,
facing,
baseOffsetABC);
baseOffsetABC,
basePositionXYZ,
object,
params.getFluidSource(),
this);
}
@Override
@@ -43,9 +57,15 @@ class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
env.offsetABC[2] = c;
env.setSource(params.getSource());
PlaceResult placeResult = element.survivalPlaceBlock(object, world, x, y, z, trigger, env);
if (placeResult != PlaceResult.SKIP && built == -1) built = 0;
if (placeResult == PlaceResult.REJECT_CONTINUE && element.isFluidElement(object)) {
// The fluid has to wait. Remember where it is, as this round may still build what it is waiting for, and
// then it can be placed before the round is over instead of one round later.
deferredFluids.add(new DeferredFluid<>(element, x, y, z, a, b, c));
}
if (placeResult != PlaceResult.SKIP && placeResult != PlaceResult.REJECT_CONTINUE && built == -1) built = 0;
switch (placeResult) {
case SKIP:
case REJECT_CONTINUE:
return true;
case ACCEPT:
if (check) element.check(object, world, x, y, z);
@@ -64,7 +84,83 @@ class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
}
}
public int getBuilt() {
return built;
/**
* Place the fluids that had to wait during this round, now that the round has built everything it was going to.
* <p>
* A fluid position is often visited before the blocks that are meant to hold it, so a round that finishes the
* structure would otherwise leave the fluid to the next round even though there is nothing left to wait for. The
* gate is asked again, as the answer it gave was about the world as it was before this round built anything.
* <p>
* Like the walk itself, this places at most as many elements as the round still has budget left, and whatever it
* cannot reach is left to the next round.
*
* @param world the world this round was run in
*/
void finishRound(World world) {
if (deferredFluids.isEmpty()) return;
// A round that built nothing has not changed the answer of the gate either.
if (built <= 0) return;
int budget = elementBudget - built;
env.clearFluidGateResult();
for (DeferredFluid<T> deferred : deferredFluids) {
if (budget <= 0) break;
IStructureElement<T> element = deferred.element();
// The element has to see the same offsets and item source it saw during the walk, as elements may read
// channel data or take items through them.
env.offsetABC[0] = deferred.a();
env.offsetABC[1] = deferred.b();
env.offsetABC[2] = deferred.c();
env.setSource(params.getSource());
PlaceResult placeResult = element
.survivalPlaceBlock(object, world, deferred.x(), deferred.y(), deferred.z(), trigger, env);
if (placeResult != PlaceResult.ACCEPT) continue;
if (check) element.check(object, world, deferred.x(), deferred.y(), deferred.z());
built += 1;
budget -= 1;
}
deferredFluids.clear();
}
/**
* Number of elements this round has placed, or -1 when the structure is done.
* <p>
* A round that only had to wait for the structure to be built before it could place its fluid did not build
* anything, and the structure is not done either, so it reports no progress instead of reporting completion.
*/
public int getBuilt() {
return built == -1 && fluidDeferred ? 0 : built;
}
@Nullable
@Override
public Boolean getGateResult() {
return fluidGateResult;
}
@Override
public void setGateResult(boolean ready) {
fluidGateResult = ready;
}
@Override
public void clearGateResult() {
fluidGateResult = null;
}
@Override
public void markDeferred() {
fluidDeferred = true;
}
@Override
public boolean isDeferred() {
return fluidDeferred;
}
/**
* A fluid position a round had to leave alone, kept so that it can be tried once more when the round is over.
*/
@Desugar
private record DeferredFluid<T> (IStructureElement<T> element, int x, int y, int z, int a, int b, int c) {}
}
@@ -24,6 +24,16 @@ public class InventoryIterable<Inv extends IInventory> implements Iterable<ItemS
return inv;
}
/**
* The slot this iteration stops at, exclusive, or -1 when it runs to the end of the inventory.
* <p>
* Callers that have to write into the inventory instead of iterating over it, e.g. because they replace a stack
* rather than removing it, need this to respect the same range the iterator uses.
*/
public int getMaxSlot() {
return maxSlot;
}
@Override
public Iterator<ItemStack> iterator() {
return new Iterator<ItemStack>() {
@@ -1,20 +1,9 @@
/**
* Copyright (c) 2022, glee8e This file is part of StructureLib.
* <p>
* StructureLib is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any
* later version.
* <p>
* StructureLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
* <p>
* You should have received a copy of the GNU Lesser General Public License along with Foobar; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.gtnewhorizon.structurelib.util;
import java.util.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
import java.util.function.Predicate;
@@ -30,6 +19,7 @@ import net.minecraft.inventory.InventoryEnderChest;
import net.minecraft.item.ItemStack;
import com.gtnewhorizon.gtnhlib.util.map.ItemStackMap;
import com.gtnewhorizon.structurelib.SortedRegistry;
import com.gtnewhorizon.structurelib.util.InventoryUtility.ItemStackExtractor.APIType;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
@@ -38,12 +28,13 @@ import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
*/
public class InventoryUtility {
private static final SortedRegistry<ItemStackExtractor> stackExtractors = new SortedRegistry<>();
private static final SortedRegistry<ItemStackExtractor> stackExtractors = new SortedRegistry<>("stackExtractors");
private static final List<Predicate<? super EntityPlayerMP>> enableEnder = new CopyOnWriteArrayList<>();
/**
* The remove() of the Iterable returned must be implemented!
*/
private static final SortedRegistry<InventoryProvider<?>> inventoryProviders = new SortedRegistry<>();
private static final SortedRegistry<InventoryProvider<?>> inventoryProviders = new SortedRegistry<>(
"inventoryProviders");
static {
inventoryProviders.register("5000-main-inventory", new InventoryProvider<InventoryIterable<InventoryPlayer>>() {
@@ -102,8 +93,21 @@ public class InventoryUtility {
registerInventoryProvider(key, newInventoryProvider(extractor));
}
public static Iterator<? extends ItemStackExtractor> getStackExtractors() {
return stackExtractors.iterator();
public static Iterator<? extends ItemStackExtractor> getStackExtractors(EntityPlayerMP player) {
return stackExtractors.getPlayerOrdering(player).iterator();
}
/**
* Every inventory registered for the given player, in the order the player configured.
* <p>
* This is the set of inventories {@link #takeFromInventory(EntityPlayerMP, ItemStack, boolean)} walks, exposed so
* that a walk that is not item based, e.g. StructureLib taking fluid out of a container a player carries, can cover
* the same inventories without having to register anything of its own.
*
* @param player the player whose inventories to walk
*/
public static Iterable<InventoryProvider<?>> getInventoryProviders(EntityPlayerMP player) {
return inventoryProviders.getPlayerOrdering(player);
}
public static <Inv extends IInventory> InventoryProvider<InventoryIterable<Inv>> newInventoryProvider(
@@ -131,6 +135,12 @@ public class InventoryUtility {
return type == APIType.MAIN;
}
@Override
@Nullable
public IInventory getInventory(ItemStack source, @Nullable EntityPlayerMP player) {
return extractor.apply(source);
}
@Override
public int takeFromStack(Predicate<ItemStack> predicate, boolean simulate, int count,
ItemStackCounter store, ItemStack stack, ItemStack filter, EntityPlayerMP player) {
@@ -165,7 +175,7 @@ public class InventoryUtility {
boolean simulate, int count) {
ItemStackCounterImpl store = new ItemStackCounterImpl();
int sum = 0;
for (InventoryProvider<?> provider : inventoryProviders) {
for (InventoryProvider<?> provider : inventoryProviders.getPlayerOrdering(player)) {
sum += takeFromPlayer(player, predicate, simulate, count - sum, store, provider, null);
if (sum >= count) return store.getStore();
}
@@ -186,7 +196,7 @@ public class InventoryUtility {
int count = filter.stackSize;
ItemStackPredicate predicate = ItemStackPredicate.from(filter, NBTMode.EXACT);
ItemStackCounterImpl store = new ItemStackCounterImpl();
for (InventoryProvider<?> provider : inventoryProviders) {
for (InventoryProvider<?> provider : inventoryProviders.getPlayerOrdering(player)) {
sum += takeFromPlayer(player, predicate, simulate, count - sum, store, provider, filter);
if (sum >= count) return sum;
}
@@ -212,7 +222,7 @@ public class InventoryUtility {
* @param predicate item stack filter
* @param simulate whether to do removal
* @param count let's hope int size is enough...
* @param recursive do recursive lookup using {@link #getStackExtractors() stack extractors}
* @param recursive do recursive lookup using {@link #getStackExtractors(EntityPlayerMP) stack extractors}
* @return amount taken. never negative nor bigger than count...
*/
public static Map<ItemStack, Integer> takeFromInventory(Iterable<ItemStack> inv, Predicate<ItemStack> predicate,
@@ -252,7 +262,9 @@ public class InventoryUtility {
if (found == count) return count;
}
if (!recursive) continue;
for (ItemStackExtractor f : stackExtractors) {
for (ItemStackExtractor f : stackExtractors.getPlayerOrdering(player)) {
boolean end = f.isAPIImplemented(APIType.IS_VALID_SOURCE);
if (!f.isValidSource(stack, player)) continue;
if (filter != null && f.isAPIImplemented(APIType.EXTRACT_ONE_STACK)) {
copiedFilter.stackSize = count - found;
found += f.getItem(stack, copiedFilter, simulate, player);
@@ -260,11 +272,16 @@ public class InventoryUtility {
found += f.takeFromStack(predicate, simulate, count - found, store, stack, filter, player);
}
if (found >= count) return found;
if (end) break;
}
}
return found;
}
public static void init() {
// dummy method to init static final fields
}
public interface OptimizedExtractor {
/**
@@ -294,10 +311,32 @@ public class InventoryUtility {
enum APIType {
MAIN,
EXTRACT_ONE_STACK,
IS_VALID_SOURCE,
}
boolean isAPIImplemented(APIType type);
default boolean isValidSource(ItemStack is, EntityPlayerMP player) {
return true;
}
/**
* The inventory held by the given item stack, if it holds one.
* <p>
* An extractor for an item that contains an inventory is registered once for item extraction, and can hand that
* same inventory out here, so a walk that is not item based, e.g. StructureLib looking for a fluid container a
* player put in their backpack, reaches the backpack contents as well. Returning null is fine and means this
* extractor cannot hand out the inventory itself.
*
* @param source item stack that might hold an inventory
* @param player the player the stack belongs to, or null when it does not come from a player
* @return the inventory inside the given stack, or null
*/
@Nullable
default IInventory getInventory(ItemStack source, @Nullable EntityPlayerMP player) {
return null;
}
/**
* Extract a particular type of item. The extractor can choose to not return all items contained within this
* item as long as it makes sense, but the author should inform the player of this.
@@ -1,41 +0,0 @@
package com.gtnewhorizon.structurelib.util;
import java.util.Iterator;
import net.minecraft.item.ItemStack;
public class ItemStackArrayIterable implements Iterable<ItemStack> {
private final ItemStack[] stacks;
public ItemStackArrayIterable(ItemStack[] stacks) {
this.stacks = stacks;
}
public ItemStack[] getStacks() {
return stacks;
}
@Override
public Iterator<ItemStack> iterator() {
return new Iterator<ItemStack>() {
private int ptr = 0;
@Override
public boolean hasNext() {
return ptr < stacks.length;
}
@Override
public ItemStack next() {
return stacks[ptr++];
}
@Override
public void remove() {
stacks[ptr - 1] = null;
}
};
}
}
@@ -11,7 +11,6 @@ public class MiscUtils {
private MiscUtils() {}
@SuppressWarnings("unchecked")
public static Set<String> getTagKeys(NBTTagCompound tag) {
return tag.func_150296_c();
}
@@ -1,6 +1,12 @@
package com.gtnewhorizon.structurelib.util;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableMap;
import java.util.Spliterator;
import java.util.TreeMap;
import java.util.function.Consumer;
public class SortedRegistry<V> implements Iterable<V> {
@@ -141,8 +141,7 @@ public class Vec3Impl implements Comparable<Vec3Impl> {
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof Vec3Impl) {
Vec3Impl vec3i = (Vec3Impl) o;
} else if (o instanceof Vec3Impl vec3i) {
return val0 == vec3i.val0 && val1 == vec3i.val1 && val2 == vec3i.val2;
}
return false;
+113 -2
View File
@@ -1,4 +1,4 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>API Overview</TITLE>
@@ -178,6 +178,80 @@ StructureLib API documentation.
Just give me a better name and I'd do the renaming.
<h3>Channel Descriptions</h3>
<p>
Each channel can have one description associated with it per mod.
Channel description should briefly describe how a specific channel is used for inside a specific mod.
They will be displayed to player in channel editor GUI that comes with StructureLib.
The registration process can be done either via direct method call to {@link com.gtnewhorizon.structurelib.StructureLibAPI#registerChannelDescription(String, String, String)},
or by sending an IMC message.
After registration, the channel will also show up as autocomplete options when players are editing channels.
</p>
<p>
Here is an example of sending an IMC message to register two channels and their description.
In this example, we assume your modid is <code>my_mod</code> and your mod will ship with localization entries for
localization key <code>channels.my_mod.channel_1</code> and <code>channels.my_mod.channel_2</code>
</p>
<pre>
NBTTagCompound command = new NBTTagCompound();
NBTTagList tags = new NBTTagList();
String[] channels = {"channel_1", "channel_2"};
for (String channel : channels) {
NBTTagCompound tag = new NBTTagCompound();
tag.setString("Channel", channel);
tag.setString("Description", "channels.my_mod." + channel);
tags.appendTag(tag);
}
command.setTag("Channels", tags);
FMLInterModComms.sendMessage("structurelib", "register_channel", command);
</pre>
<p>
There is no strict rules over whether you should do direct API method call or send IMC messages.
You can choose whichever you prefer.
</p>
<h3>Channel Indicator Items</h3>
<p>
You can associate an ItemStack with a given (channel, value) pair.
It is usually (but not required to be) the ItemBlock for the blocks to be placed by this (channel, value) pair.
Player will be able to drag and drop this item to the builtin channel configuration GUI.
The registration process can be done either via direct method call to {@link com.gtnewhorizon.structurelib.StructureLibAPI#registerChannelItem(String, String, int, net.minecraft.item.ItemStack)},
or by sending an IMC message.
After registration, the channel will also show up as autocomplete options when players are editing channels.
</p>
<p>
Here is an example of sending an IMC message to register 3 vanilla sandstone as different indicator for channel "sandstone", with block metadata plus 1 as channel value.
In this example, we assume your modid is <code>my_mod</code>.
</p>
<pre>
NBTTagCompound command = new NBTTagCompound();
NBTTagList items = new NBTTagList();
int[] metas = {0, 1, 2};
for (int meta : metas) {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag("Item", new ItemStack(Blocks.sandstone, 1, meta).writeToNBT(new NBTTagCompound()));
NBTTagList channels = new NBTTagList();
NBTTagCompound channel = new NBTTagCompound();
channel.setString("Channel", "sandstone");
channel.setInteger("Value", meta + 1);
channels.appendTag(channel);
tag.setTag("Channels", channels);
items.appendTag(tag);
}
command.setTag("Items", items);
FMLInterModComms.sendMessage("structurelib", "register_channel_item", command);
</pre>
<p>
There is no strict rules over whether you should do direct API method call or send IMC messages.
You can choose whichever you prefer.
</p>
<h3>Examples</h3>
<h4>For Structure Definition Author</h4>
@@ -219,7 +293,7 @@ whereas all these structure elements are designed without considering channels w
<pre>
import com.gtnewhorizon.structurelib.structure.IStructureElement;
public class MyHatchElement&lt;T> implements IStructureElement&lt;T> {
public class MyHatchElement&lt;T&gt; implements IStructureElement&lt;T&gt; {
//...
{@literal @}Override
public PlaceResult survivalPlaceBlock(
@@ -251,5 +325,42 @@ The code for placeBlock() and spawnHint() will be left as an exercise for the re
<p>
Please refer to {@link com.gtnewhorizon.structurelib.StructureEvent} to see what events are available.
</p>
<h1>Extending Inventory Utility</h1>
{@link com.gtnewhorizon.structurelib.util.InventoryUtility} is how structurelib survival autoplace pulls item for autoplacing.
It has two key concepts: inventory providers and stack extractors.
<p>
Inventory Providers are classes that retrieve an Iterable of ItemStacks for examination, given an EntityPlayerMP as identifier.
They are also responsible for marking the relevant item container as dirty, so changes can be commited to disk properly when world save happens.
Examples include: main player inventory, vanilla ender chest, baubles inventory. StructureLib comes with main player inventory and vanilla ender chest built in.
</p>
<p>
Stack Extractors are classes that retrieve items from another item.
Examples include: Forestry backpacks, ME network over ME Wireless Terminals.
</p>
<p>
Both of these are managed internally by {@link com.gtnewhorizon.structurelib.SortedRegistry}.
By default, elements registered will be sorted in lexicographical order in ascending order.
However, facilities in StructureLib will allow an end user to tweak these registries as their wish.
They can disable, reorder, reenable any element within the registry, either in game, at main menu or with the game stopped,
Their changes will be synced to server as well, should they be playing on a dedicated server.
</p>
<p>
This has the following important implications
</p>
<ul>
<li>Not all inventory providers or stack extractors may be called during a survival autoplace session</li>
<li>One player could have stack extractor 001 ordered before 002, while the other having a completely reversed order</li>
</ul>
Therefore, if your stack extractor can somehow correlate with aonther one, make sure it still works if the calling order is inverted.
At the very least, inform the player about this ordering constraint.
A future StructrueLib refactor to specify this dependency info is possible, but the chance is low.
<h2>Localization</h2>
Both of these would show up in config GUI of StructureLib. Structurelib uses the following localization keys in that GUI.
<ul>
<li><code>structurelib.sortedregistry.inventoryproviders.&lt;registry_key&gt;</code>: This is the name shown on the button for inventory providers. If this is not provided, then registry_key will be used instead.</li>
<li><code>structurelib.sortedregistry.inventoryproviders.&lt;registry_key&gt;.tooltip</code>: This is the tooltip shown when user hover over the button for inventory providers. If this is not provided, then no explicit tooltip will be shown.</li>
<li><code>structurelib.sortedregistry.stackextractors.&lt;registry_key&gt;</code>: This is the name shown on the button for stack extractors. If this is not provided, then registry_key will be used instead.</li>
<li><code>structurelib.sortedregistry.stackextractors.&lt;registry_key&gt;.tooltip</code>: This is the tooltip shown when user hover over the button for stack extractors. If this is not provided, then no explicit tooltip will be shown.</li>
</ul>
</BODY>
</HTML>
@@ -1,3 +1,4 @@
tile.structurelib.blockhint.name=Hint
tile.structurelib.blockhint.0.name=Hint 1 dot
tile.structurelib.blockhint.1.name=Hint 2 dots
tile.structurelib.blockhint.2.name=Hint 3 dots
@@ -29,12 +30,21 @@ item.structurelib.constructableTrigger.desc.4=Quantity of schematics in item sta
item.structurelib.constructableTrigger.desc.5=Hold §l[LSHIFT]§r to display channel data
item.structurelib.constructableTrigger.desc.lshift.0=Contain %d sub channel.
item.structurelib.constructableTrigger.too_fast=Please wait %d milliseconds before another autoplace...
item.structurelib.constructableTrigger.gui.title=Sub Channels
item.structurelib.constructableTrigger.gui.key=Key:
item.structurelib.constructableTrigger.gui.value=Value:
item.structurelib.constructableTrigger.gui.add=Add
item.structurelib.constructableTrigger.gui.set=Set
item.structurelib.constructableTrigger.gui.unset=Unset
item.structurelib.constructableTrigger.gui.wipe=§4Wipe
item.structurelib.constructableTrigger.gui.set=Update
item.structurelib.constructableTrigger.gui.unset=Remove
item.structurelib.constructableTrigger.gui.wipe=§4Clear
item.structurelib.constructableTrigger.gui.wipe.confirm=§4Sure?
item.structurelib.constructableTrigger.gui.channels.from=§rMod: §9§o%s
item.structurelib.constructableTrigger.gui.info=Many multiblocks support some degree of variation in their structure and a sub channel allows indication of which variant to use.\n All sub channels have a sequence of lowercase characters as key and a positive integer as value. Most known sub channels should be available as typeahead completions.\n You can also drag and drop items from NEI to set the corresponding sub channel value. These items all have a tooltip of "§oIndicates§r §ovalue§r §oX§r §ofor§r §osub§r §ochannel§r §oY§r".
channels.structurelib.show_errors=When set, will highlight parts of the multiblock that is definitely wrong
structurelib.tooltip.channelvalue=§7Value §b%d§r§7 for subchannel §b%s
structurelib.tooltip.indicator_dnd=Drop into GUI to select this value for this channel
structurelib.autoplace.built_stat=Built %s blocks
structurelib.autoplace.complete=§aThis multiblock has completed!
@@ -42,6 +52,9 @@ structurelib.autoplace.error.not_enabled=§cThis multiblock does not support aut
structurelib.autoplace.error.no_simple_block=§cSuggested to place §r%s§c but none was found
structurelib.autoplace.error.no_item_stack=§cSuggested to place block by using §r%s§c but none was found
structurelib.autoplace.warning.no_explicit_channel=§6This structure depends on nonexistent sub channel §r%s§6. Using master channel instead.
structurelib.autoplace.missing_block=§cMissing block: %s
structurelib.autoplace.missing_fluid=§cMissing fluid: %s (%s)
structurelib.autoplace.requirement_fluid=%s (%s)
structurelib.blockhint.desc.0=Helps while building
structurelib.blockhint.0.name=Hint 1 dot
@@ -172,3 +185,33 @@ structurelib.config.client.hologram.maxCoexisting=Max Coexisting Holograms
structurelib.config.client.hologram.maxCoexisting.tooltip=Number of holograms that can coexist. Usually all hints generated by one right click belongs to one hologram. An attempt will be made to prune old holograms when a new hologram is about to be projected and this limit would be exceeded.
structurelib.config.client.hologram.removeColliding=Remove Colliding Holograms
structurelib.config.client.hologram.removeColliding.tooltip=Whether an attempt will be made to remove any existing hologram that collides with a new hologram.
structurelib.config.registries=Sorted Registries
structurelib.config.registries.tooltip=Sorted Registry is how StructureLib internally keep track of certain features. Each individual elements may be reordered, disabled and enabled at user's command. Changes will be synced to server if needed.\nThis gui can also be accessed in game by shift right clicking air with Multiblock Structure Hologram Projector.
structurelib.config.registries.stackextractors=Stack Extractors
structurelib.config.registries.stackextractors.tooltip=Controls which inventory-from-stack functions are enabled during survival autoplace
structurelib.config.registries.inventoryproviders=Inventory Providers
structurelib.config.registries.inventoryproviders.tooltip=Controls which inventories functions are enabled during survival autoplace
structurelib.config.registries.fluidstackextractors=Fluid Stack Extractors
structurelib.config.registries.fluidstackextractors.tooltip=Controls which ways of pulling fluid out of an item are enabled during survival autoplace
structurelib.config.registries.fluidsourceproviders=Fluid Source Providers
structurelib.config.registries.fluidsourceproviders.tooltip=Controls which additional ways of getting fluid are used during survival autoplace, e.g. an ME network the player can reach with a wireless terminal. Whatever the player is carrying is always used after these.
structurelib.configgui.enabled=Enabled Entry
structurelib.configgui.disabled=Disabled Entry
structurelib.configgui.drag.tooltip=Drag this button to reorder this element.
structurelib.sortedregistry.inventoryproviders.5000-main-inventory=5000 Main Player Inventory
structurelib.sortedregistry.inventoryproviders.5000-main-inventory.tooltip=36 slots of item in your main inventory. Armor slots excluded.
structurelib.sortedregistry.inventoryproviders.7000-ender-inventory=7000 Ender Chest Inventory
structurelib.sortedregistry.inventoryproviders.7000-ender-inventory.tooltip=Links to your vanilla ender chest inventory. Require at least one "ender backpack like" item in main inventory to work.
structurelib.sortedregistry.fluidstackextractors.3000-forge-fluid-container-item=3000 Forge fluid container item
structurelib.sortedregistry.fluidstackextractors.3000-forge-fluid-container-item.tooltip=Containers implementing Forge's IFluidContainerItem, e.g. most modded cells. They hold their fluid in their own NBT, so they are drained in place.
structurelib.sortedregistry.fluidstackextractors.5000-forge-fluid-container-registry=5000 Forge fluid container registry
structurelib.sortedregistry.fluidstackextractors.5000-forge-fluid-container-registry.tooltip=Containers registered with Forge's FluidContainerRegistry, e.g. buckets. They are consumed as a whole, and are replaced by their empty container.
structurelib.config.common.autoplace.tooltip=Configurations that control how survival autoplace places blocks.
structurelib.config.common.autoplace.fluidAutoplace.tooltip=Whether survival autoplace may place fluid blocks, e.g. the water a multiblock needs inside itself, by draining fluid from the player's fluid containers.\nA multiblock can also provide its own fluid source.\nThis only disables fluid blocks. Multiblocks keep working, they just cannot have those positions filled by autoplace.
structurelib.config.common.autoplace.fluidGateMode.tooltip=How careful autoplace is about placing a fluid into a structure that is not finished yet, as a fluid would flow out of it.\nNONE: place the fluid right away.\nLENIENT: only place the fluid when it cannot flow out of the structure.\nSTRICT: only place the fluid once every non fluid element of the structure is satisfied.
@@ -0,0 +1,200 @@
tile.structurelib.blockhint.name=Подсказка
tile.structurelib.blockhint.0.name=Подсказка 1 точка
tile.structurelib.blockhint.1.name=Подсказка 2 точки
tile.structurelib.blockhint.2.name=Подсказка 3 точки
tile.structurelib.blockhint.3.name=Подсказка 4 точки
tile.structurelib.blockhint.4.name=Подсказка 5 точек
tile.structurelib.blockhint.5.name=Подсказка 6 точек
tile.structurelib.blockhint.6.name=Подсказка 7 точек
tile.structurelib.blockhint.7.name=Подсказка 8 точек
tile.structurelib.blockhint.8.name=Подсказка 9 точек
tile.structurelib.blockhint.9.name=Подсказка 10 точек
tile.structurelib.blockhint.10.name=Подсказка 11 точек
tile.structurelib.blockhint.11.name=Подсказка 12 точек
tile.structurelib.blockhint.12.name=Общая подсказка
tile.structurelib.blockhint.13.name=Подсказка воздух
tile.structurelib.blockhint.14.name=Подсказка нет воздуха
tile.structurelib.blockhint.15.name=Подсказка ошибка
item.structurelib.frontRotationTool.name=Инструмент для поворота (Автономный)
item.structurelib.frontRotationTool.desc.0=Открывает интерфейс поворота лицевой стороны
item.structurelib.frontRotationTool.desc.1=Поворачивает только лицевую сторону,
item.structurelib.frontRotationTool.desc.2=что позволяет повернуть всю структуру.
item.structurelib.constructableTrigger.name=Голограммный проектор мультиблоковой структуры
item.structurelib.constructableTrigger.desc.0=Используется по интерфейсу контроллера
item.structurelib.constructableTrigger.desc.1=Показывает схему постройки мультиблочной структуры,
item.structurelib.constructableTrigger.desc.2=используется при нажатии по контроллеру
item.structurelib.constructableTrigger.desc.3=(Shift+ПКМ для автоматической постройки)
item.structurelib.constructableTrigger.desc.4=Количество проекторов в одном слоте влияет на тир/режим/тип постройки, если он не задан в GUI проектора
item.structurelib.constructableTrigger.desc.5=Удерживайте §l[LSHIFT]§r для отображения данных канала
item.structurelib.constructableTrigger.desc.lshift.0=Содержит %d подканал
item.structurelib.constructableTrigger.too_fast=Подождите %d миллисекунд перед очередным автозаполнением...
item.structurelib.constructableTrigger.gui.title=Подканалы
item.structurelib.constructableTrigger.gui.key=Ключ:
item.structurelib.constructableTrigger.gui.value=Значение:
item.structurelib.constructableTrigger.gui.add=Добавить
item.structurelib.constructableTrigger.gui.set=Обновить
item.structurelib.constructableTrigger.gui.unset=Удалить
item.structurelib.constructableTrigger.gui.wipe=§4Очистить
item.structurelib.constructableTrigger.gui.wipe.confirm=§4Уверен?
item.structurelib.constructableTrigger.gui.channels.from=§rМод: §9§o%s
item.structurelib.constructableTrigger.gui.info=Многие мультиблоки поддерживают различные вариации структуры. Субканал позволяет указать, какой именно вариант использовать.\nВсе субканалы в качестве ключа используют строку из строчных букв, а в качестве значения - положительное целое число. Для большинства известных субканалов доступно автодополнение при вводе.\nВы также можете перетаскивать предметы из NEI, чтобы задать значение соответствующего субканала. Все эти предметы имеют подсказку: "§oЗадаёт§r §oзначение§r §oX§r §oдля§r §oсубканала§r §oY§r"
channels.structurelib.show_errors=Если включено, подсвечивает элементы мультиблока с явными ошибками
structurelib.tooltip.channelvalue=§7Указывает значение §b%d§r§7 для подканала §b%s
structurelib.tooltip.indicator_dnd=Перейдите в GUI, чтобы выбрать это значение для этого канала.
structurelib.autoplace.built_stat=Построено %s блоков
structurelib.autoplace.complete=§aЭтот мультиблок собран!
structurelib.autoplace.error.not_enabled=§cЭтот мультиблок не поддерживает автозаполнение в выживании!
structurelib.autoplace.error.no_simple_block=§cПредлагалось разместить §r%s§c но ничего не нашлось
structurelib.autoplace.error.no_item_stack=§cПредлагалось разместить блок используя §r%s§c но ничего не нашлось
structurelib.autoplace.warning.no_explicit_channel=§6Эта структура зависит от несуществующего подканала §r%s§6. Вместо этого используйте главный канал.
structurelib.blockhint.desc.0=Помогает при постройке
structurelib.blockhint.0.name=Подсказка 1 точка
structurelib.blockhint.1.name=Подсказка 2 точки
structurelib.blockhint.2.name=Подсказка 3 точки
structurelib.blockhint.3.name=Подсказка 4 точки
structurelib.blockhint.4.name=Подсказка 5 точек
structurelib.blockhint.5.name=Подсказка 6 точек
structurelib.blockhint.6.name=Подсказка 7 точек
structurelib.blockhint.7.name=Подсказка 8 точек
structurelib.blockhint.8.name=Подсказка 9 точек
structurelib.blockhint.9.name=Подсказка 10 точек
structurelib.blockhint.10.name=Подсказка 11 точек
structurelib.blockhint.11.name=Подсказка 12 точек
structurelib.blockhint.desc.1=Заполнитель конкретной группы.
structurelib.blockhint.12.name=Общая подсказка
structurelib.blockhint.desc.2=Общий заполнитель.
structurelib.blockhint.13.name=Подсказка воздух
structurelib.blockhint.desc.3=Убедитесь, что это содержит воздух.
structurelib.blockhint.14.name=Подсказка нет воздуха
structurelib.blockhint.desc.4=Убедитесь, что это не содержит воздух.
structurelib.blockhint.15.name=Подсказка ошибка
structurelib.blockhint.desc.5=ОШИБКА (а что вы ожидали?)
itemGroup.structurelib=StructureLib
structurelib.facing.0=вниз нормальный нет
structurelib.facing.1=вниз нормальный по горизонтали
structurelib.facing.2=вниз нормальный по вертикали
structurelib.facing.3=вниз нормальный оба
structurelib.facing.4=вниз по часовой стрелке нет
structurelib.facing.5=вниз по часовой стрелке по горизонтали
structurelib.facing.6=вниз по часовой стрелке по вертикали
structurelib.facing.7=вниз по часовой стрелке оба
structurelib.facing.8=вниз перевернутый
structurelib.facing.9=вниз перевернутый
structurelib.facing.10=вниз перевернутый
structurelib.facing.11=вниз перевернутый
structurelib.facing.12=вниз против часовой стрелки
structurelib.facing.13=вниз против часовой стрелки
structurelib.facing.14=вниз против часовой стрелки
structurelib.facing.15=вниз против часовой стрелки
structurelib.facing.16=вверх нормальный нет
structurelib.facing.17=вверх нормальный по горизонтали
structurelib.facing.18=вверх нормальный по вертикали
structurelib.facing.19=вверх нормальный оба
structurelib.facing.20=вверх по часовой стрелке нет
structurelib.facing.21=вверх по часовой стрелке по горизонтали
structurelib.facing.22=вверх по часовой стрелке по вертикали
structurelib.facing.23=вверх по часовой стрелке оба
structurelib.facing.24=вверх перевернутый
structurelib.facing.25=вверх перевернутый
structurelib.facing.26=вверх перевернутый
structurelib.facing.27=вверх перевернутый
structurelib.facing.28=вверх против часовой стрелки
structurelib.facing.29=вверх против часовой стрелки
structurelib.facing.30=вверх против часовой стрелки
structurelib.facing.31=вверх против часовой стрелки
structurelib.facing.32=север нормальный нет
structurelib.facing.33=север нормальный по горизонтали
structurelib.facing.34=север нормальный по вертикали
structurelib.facing.35=север нормальный оба
structurelib.facing.36=север по часовой стрелке нет
structurelib.facing.37=север по часовой стрелке по горизонтали
structurelib.facing.38=север по часовой стрелке по вертикали
structurelib.facing.39=север по часовой стрелке оба
structurelib.facing.40=север перевернутый
structurelib.facing.41=север перевернутый
structurelib.facing.42=север перевернутый
structurelib.facing.43=север перевернутый
structurelib.facing.44=север против часовой стрелки
structurelib.facing.45=север против часовой стрелки
structurelib.facing.46=север против часовой стрелки
structurelib.facing.47=север против часовой стрелки
structurelib.facing.48=юг нормальный нет
structurelib.facing.49=юг нормальный по горизонтали
structurelib.facing.50=юг нормальный по вертикали
structurelib.facing.51=юг нормальный оба
structurelib.facing.52=юг по часовой стрелке нет
structurelib.facing.53=юг по часовой стрелке по горизонтали
structurelib.facing.54=юг по часовой стрелке по вертикали
structurelib.facing.55=юг по часовой стрелке оба
structurelib.facing.56=юг перевернутый
structurelib.facing.57=юг перевернутый
structurelib.facing.58=юг перевернутый
structurelib.facing.59=юг перевернутый
structurelib.facing.60=юг против часовой стрелки
structurelib.facing.61=юг против часовой стрелки
structurelib.facing.62=юг против часовой стрелки
structurelib.facing.63=юг против часовой стрелки
structurelib.facing.64=запад нормальный нет
structurelib.facing.65=запад нормальный по горизонтали
structurelib.facing.66=запад нормальный по вертикали
structurelib.facing.67=запад нормальный оба
structurelib.facing.68=запад по часовой стрелке нет
structurelib.facing.69=запад по часовой стрелке по горизонтали
structurelib.facing.70=запад по часовой стрелке по вертикали
structurelib.facing.71=запад по часовой стрелке оба
structurelib.facing.72=запад перевернутый
structurelib.facing.73=запад перевернутый
structurelib.facing.74=запад перевернутый
structurelib.facing.75=запад перевернутый
structurelib.facing.76=запад против часовой стрелки
structurelib.facing.77=запад против часовой стрелки
structurelib.facing.78=запад против часовой стрелки
structurelib.facing.79=запад против часовой стрелки
structurelib.facing.80=восток нормальный нет
structurelib.facing.81=восток нормальный по горизонтали
structurelib.facing.82=восток нормальный по вертикали
structurelib.facing.83=восток нормальный оба
structurelib.facing.84=восток по часовой стрелке нет
structurelib.facing.85=восток по часовой стрелке по горизонтали
structurelib.facing.86=восток по часовой стрелке по вертикали
structurelib.facing.87=восток по часовой стрелке оба
structurelib.facing.88=восток перевернутый
structurelib.facing.89=восток перевернутый
structurelib.facing.90=восток перевернутый
structurelib.facing.91=восток перевернутый
structurelib.facing.92=восток против часовой стрелки
structurelib.facing.93=восток против часовой стрелки
structurelib.facing.94=восток против часовой стрелки
structurelib.facing.95=восток против часовой стрелки
structurelib.config.client=Настройки клиента
structurelib.config.client.tooltip=Настройки, которые изменяют только внешний вид игры, но не то, как она функционирует.
structurelib.config.client.hologram=Голограммные настройки
structurelib.config.client.hologram.tooltip=Настройки, которые по умолчанию меняют способ проецирования голограммы в мир.
structurelib.config.client.hologram.maxCoexisting=Макс. сосуществующих голограмм
structurelib.config.client.hologram.maxCoexisting.tooltip=Количество голограмм, которые могут сосуществовать. Обычно все подсказки, сгенерированные одним щелчком ПКМ, принадлежат одной голограмме. Будет предпринята попытка удаления старой голограммы, когда будет проецироваться новая голограмма и этот лимит будет превышен.
structurelib.config.client.hologram.removeColliding=Удалить сталкивающиеся голограммы
structurelib.config.client.hologram.removeColliding.tooltip=Whether an attempt will be made to remove any existing hologram that collides with a new hologram.
structurelib.config.registries=Sorted Registries
structurelib.config.registries.tooltip=Sorted Registry is how StructureLib internally keep track of certain features. Each individual elements may be reordered, disabled and enabled at user's command. Changes will be synced to server if needed.\nThis gui can also be accessed in game by shift right clicking air with Multiblock Structure Hologram Projector.
structurelib.config.registries.stackextractors=Stack Extractors
structurelib.config.registries.stackextractors.tooltip=Controls which inventory-from-stack functions are enabled during survival autoplace
structurelib.config.registries.inventoryproviders=Источники инвентарей
structurelib.config.registries.inventoryproviders.tooltip=Controls which inventories functions are enabled during survival autoplace
structurelib.configgui.enabled=Включённый элемент
structurelib.configgui.disabled=Отключённый элемент
structurelib.configgui.drag.tooltip=Перетащите эту кнопку, чтобы изменить порядок этого элемента.
structurelib.sortedregistry.inventoryproviders.5000-main-inventory=Основной инвентарь игрока
structurelib.sortedregistry.inventoryproviders.5000-main-inventory.tooltip=36 ячеек для предметов в вашем основном инвентаре. Слоты для брони исключены.
structurelib.sortedregistry.inventoryproviders.7000-ender-inventory=Инвентарь сундука Эндера
structurelib.sortedregistry.inventoryproviders.7000-ender-inventory.tooltip=Соединяет на ваш инвентарь из ванильного сундука Эндера. Требуется не менее один "похожий на рюкзак Эндера" предмет в основном инвентаре для работы.
@@ -1,3 +1,4 @@
tile.structurelib.blockhint.name=提示方块
tile.structurelib.blockhint.0.name=提示方块:1号
tile.structurelib.blockhint.1.name=提示方块:2号
tile.structurelib.blockhint.2.name=提示方块:3号
@@ -29,12 +30,20 @@ item.structurelib.constructableTrigger.desc.4=此物品堆叠数量会影响显
item.structurelib.constructableTrigger.desc.5=按下 §l[左SHIFT]§r 以显示子信道
item.structurelib.constructableTrigger.desc.lshift.0=包含 %d 个子信道
item.structurelib.constructableTrigger.too_fast=请在下一次自动搭建前等待 %d 毫秒...
item.structurelib.constructableTrigger.gui.title=子信道
item.structurelib.constructableTrigger.gui.key=信道名:
item.structurelib.constructableTrigger.gui.value=值:
item.structurelib.constructableTrigger.gui.add=添加
item.structurelib.constructableTrigger.gui.set=替换
item.structurelib.constructableTrigger.gui.unset=删除
item.structurelib.constructableTrigger.gui.wipe=§4全部清空
item.structurelib.constructableTrigger.gui.channels.from=§r模组: §9§o%s
item.structurelib.constructableTrigger.gui.info=许多多方块的结构都是可变的,在自动放置时,可以使用子信道来向多方块指明该使用哪一个变体。\n子信道由一个字符串标识、并拥有一个正整数作为值。这个GUI中的信道名支持自动补全到绝大多数已知的子信道。\n你也可以将部分物品从NEI中拖拽至GUI内来设置子信道值为该物品表示的值。这些物品的物品说明中都带有§o表示子信道 X 为 Y§r。
channels.structurelib.show_errors=添加后,在投影时会高亮标出必然错误的部分
structurelib.tooltip.channelvalue=§7表示子信道 §b%2$s§r§7 为 §b%d§r
structurelib.tooltip.indicator_dnd=拖入GUI中来选择该值
structurelib.autoplace.built_stat=已放置 %s 个方块
structurelib.autoplace.complete=§a这个多方块结构已经完成自动搭建!
@@ -42,6 +51,9 @@ structurelib.autoplace.error.not_enabled=§c这个多方块结构不支持在生
structurelib.autoplace.error.no_simple_block=§c建议放置 §r%s§c ,但没有找到它
structurelib.autoplace.error.no_item_stack=§c建议使用 §r%s§c 放置方块,但没有找到它
structurelib.autoplace.warning.no_explicit_channel=§6这个结构依赖于不存在的子信道 §r%s§6 。已使用主信道值替代。
structurelib.autoplace.missing_block=§c缺少方块:%s
structurelib.autoplace.missing_fluid=§c缺少流体:%s(%s)
structurelib.autoplace.requirement_fluid=%s(%s)
structurelib.blockhint.desc.0=帮助你搭建机器
structurelib.blockhint.0.name=提示方块:1号
@@ -172,3 +184,33 @@ structurelib.config.client.hologram.maxCoexisting=最多可以同时存在的全
structurelib.config.client.hologram.maxCoexisting.tooltip=这决定最多可以同时存在多少台机器的全息投影。一般一次使用全息投影仪右键生成的所有机器结构细节被视为一个全息投影。当同时存在多个全息投影,并超过此数量时,再次使用全息投影仪会移除旧有的全息投影。
structurelib.config.client.hologram.removeColliding=移除冲突的全息投影
structurelib.config.client.hologram.removeColliding.tooltip=当新的全息投影与已存在的全息投影冲突时,开启此选项时会移除已存在的全息投影。
structurelib.config.registries=注册表
structurelib.config.registries.tooltip=StructureLib 使用注册表来管理其部分功能。每个注册表中的每一个元素都可以被单独排序、禁用。需要时,注册表的内容将被同步至服务端。
structurelib.config.registries.stackextractors=物品提取器
structurelib.config.registries.stackextractors.tooltip=该注册表控制在生存模式自动放置时,如何从物品(如林业背包)提取库存。
structurelib.config.registries.inventoryproviders=物品栏定位
structurelib.config.registries.inventoryproviders.tooltip=该注册表控制在生存模式自动放置时,可用的物品栏来源。
structurelib.config.registries.fluidstackextractors=流体提取器
structurelib.config.registries.fluidstackextractors.tooltip=该注册表控制在生存模式自动放置时,如何从物品(如林业背包)提取流体库存。
structurelib.config.registries.fluidsourceproviders=流体栏定位
structurelib.config.registries.fluidsourceproviders.tooltip=该注册表控制在生存模式自动放置时,可用的流体来源。
structurelib.configgui.enabled=已启用
structurelib.configgui.disabled=已禁用
structurelib.configgui.drag.tooltip=拖动该按钮以重排。
structurelib.sortedregistry.inventoryproviders.5000-main-inventory=5000 玩家物品栏
structurelib.sortedregistry.inventoryproviders.5000-main-inventory.tooltip=不包括护甲栏以外的36格。
structurelib.sortedregistry.inventoryproviders.7000-ender-inventory=7000 末影箱
structurelib.sortedregistry.inventoryproviders.7000-ender-inventory.tooltip=当前玩家的末影箱。需要在主物品栏中存在类似于末影背包的东西才会实际生效。
structurelib.sortedregistry.fluidstackextractors.3000-forge-fluid-container-item=3000 Forge 流体容器物品
structurelib.sortedregistry.fluidstackextractors.3000-forge-fluid-container-item.tooltip=实现 Forge 的 IFluidContainerItem 的容器,例如大多数模组流体容器。流体存于其 NBT 中,因此直接在原位抽取。
structurelib.sortedregistry.fluidstackextractors.5000-forge-fluid-container-registry=5000 Forge 流体容器注册表
structurelib.sortedregistry.fluidstackextractors.5000-forge-fluid-container-registry.tooltip=注册到 Forge 的 FluidContainerRegistry 的容器,例如桶。整体消耗,并替换为其空容器。
structurelib.config.common.autoplace.tooltip=控制生存模式自动放置如何放置方块的配置项。
structurelib.config.common.autoplace.fluidAutoplace.tooltip=是否允许生存模式自动放置流体方块(例如多方块结构内部所需的水),从玩家的流体容器中抽取流体来支付。\n多方块结构也可以自行提供流体来源。\n此选项只关闭流体方块。多方块结构依旧可用,只是这些位置无法被自动放置填满。
structurelib.config.common.autoplace.fluidGateMode.tooltip=在结构尚未完成时,自动放置放置流体的小心程度(否则流体会从结构中流出)。\nNONE:立即放置。\nLENIENT:只有当流体无法流出结构时才放置。\nSTRICT:只有当结构中所有非流体元件都满足后才放置流体。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 273 B

After

Width:  |  Height:  |  Size: 126 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 B

After

Width:  |  Height:  |  Size: 154 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 B

After

Width:  |  Height:  |  Size: 138 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 301 B

After

Width:  |  Height:  |  Size: 160 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 282 B

After

Width:  |  Height:  |  Size: 137 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 281 B

After

Width:  |  Height:  |  Size: 138 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 285 B

After

Width:  |  Height:  |  Size: 131 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 289 B

After

Width:  |  Height:  |  Size: 141 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 293 B

After

Width:  |  Height:  |  Size: 132 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 B

After

Width:  |  Height:  |  Size: 138 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 296 B

After

Width:  |  Height:  |  Size: 139 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 297 B

After

Width:  |  Height:  |  Size: 143 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 255 B

After

Width:  |  Height:  |  Size: 99 B

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