Compare commits

...
293 Commits
Author SHA1 Message Date
NotAlexNoyle 7f327bb130 Exclude CODEOWNERS from language statistics 2026-10-27 08:25:14 -04:00
NotAlexNoyle 0f4a7f10e2 Add CODEOWNERS (one staff approval) 2026-10-27 08:25:14 -04:00
NotAlexNoyle e3ced84855 Compatibility with TrueOG fork of Purpur (RocksDB playerdata) 2026-10-17 15:11:50 -04:00
NotAlexNoyle 10cb872506 Edit offline players through the server's own player data storage 2026-10-02 11:52:10 -04:00
NotAlexNoyle b0d5bb72fe Use live TrueOG Network config files 2026-05-18 12:01:43 -04:00
NotAlexNoyle 7e38775ded Maven -> Gradle 8.14.3 2026-03-30 12:20:36 -04:00
dependabot[bot] 2ed23b24e5 Bump org.apache.maven.plugins:maven-shade-plugin from 3.5.2 to 3.5.3 (#195) 2024-05-01 17:11:09 +00:00
dependabot[bot] b6d61d4cc9 Bump softprops/action-gh-release from 0.1.15 to 2.0.4 (#191)
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 0.1.15 to 2.0.4.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v0.1.15...v2.0.4)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-01 22:03:00 -04:00
dependabot[bot] c3f7eaebf4 Bump org.apache.maven.plugins:maven-compiler-plugin (#190) 2024-04-01 17:21:51 +00:00
dependabot[bot] 52c90e1cea Bump org.apache.maven.plugins:maven-assembly-plugin from 3.6.0 to 3.7.1 (#189) 2024-04-01 17:20:43 +00:00
dependabot[bot] d887ff8eae Bump hmarr/auto-approve-action from 3.2.1 to 4.0.0 (#187)
Bumps [hmarr/auto-approve-action](https://github.com/hmarr/auto-approve-action) from 3.2.1 to 4.0.0.
- [Release notes](https://github.com/hmarr/auto-approve-action/releases)
- [Commits](https://github.com/hmarr/auto-approve-action/compare/v3.2.1...v4.0.0)

---
updated-dependencies:
- dependency-name: hmarr/auto-approve-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-02 01:14:49 -05:00
dependabot[bot] 0d5fb6a0ef Bump org.apache.maven.plugins:maven-shade-plugin from 3.5.1 to 3.5.2 (#186) 2024-03-01 17:40:32 +00:00
Adam 6f8a6e868a Improve compatibility with custom NBT (#183) 2024-02-16 22:41:01 -05:00
Jikoo 70c1ecfc09 Bump version to 4.4.4-SNAPSHOT for development 2024-02-08 13:11:46 -05:00
Jikoo 176272a4b9 Bump version to 4.4.3 for release 2024-02-08 13:11:18 -05:00
Adam c102e6650e Fix game type not loading (#180) 2024-02-08 13:07:23 -05:00
dependabot[bot] c8fee82291 Bump pascalgn/automerge-action from 0.15.6 to 0.16.2 (#179)
Bumps [pascalgn/automerge-action](https://github.com/pascalgn/automerge-action) from 0.15.6 to 0.16.2.
- [Release notes](https://github.com/pascalgn/automerge-action/releases)
- [Commits](https://github.com/pascalgn/automerge-action/compare/v0.15.6...v0.16.2)

---
updated-dependencies:
- dependency-name: pascalgn/automerge-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-08 13:02:28 -05:00
dependabot[bot] 0ae9982ce5 Bump actions/download-artifact from 3 to 4 (#177)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-01 16:26:41 -05:00
dependabot[bot] 59d358d907 Bump actions/upload-artifact from 3 to 4 (#176)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-01 16:26:27 -05:00
dependabot[bot] 2621181c5d Bump org.apache.maven.plugins:maven-compiler-plugin (#178) 2024-01-01 18:07:35 +00:00
Jikoo 48d044af8c Bump version to 4.4.3-SNAPSHOT for development 2023-12-29 10:05:02 -05:00
Jikoo 9a7623c209 Bump version to 4.4.2 for release 2023-12-29 10:04:28 -05:00
Adam 78354fdf68 Add support for 1.20.4 (#173) 2023-12-29 10:01:54 -05:00
dependabot[bot] 859179d1fc Bump actions/setup-java from 3 to 4 (#168)
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 3 to 4.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-01 18:03:17 -05:00
dependabot[bot] 79f53e9086 Bump actions/github-script from 6 to 7 (#169)
Bumps [actions/github-script](https://github.com/actions/github-script) from 6 to 7.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-01 18:02:30 -05:00
dependabot[bot] c14d777519 Bump org.jetbrains:annotations from 24.0.1 to 24.1.0 (#170) 2023-12-01 17:51:58 +00:00
Jikoo 1829babe69 Bump version to 4.4.2-SNAPSHOT for development 2023-11-12 14:29:31 -05:00
Jikoo 5aa959f1ac Bump version to 4.4.1 for release 2023-11-12 14:29:11 -05:00
Adam bc7e13f245 Expand preserved old data (#166)
* Fix session timestamps being erroneously updated
* Fix vehicle possibly not being re-mounted
2023-11-12 12:34:32 -05:00
Adam 73edebff54 Fix loading world on Paper (#165)
Unify load process to reduce duplicate code and risk of missed cases
2023-11-12 12:24:19 -05:00
dependabot[bot] faf1d387e9 Bump org.apache.maven.plugins:maven-dependency-plugin (#161) 2023-11-01 17:32:32 +00:00
Jikoo deed277376 Bump version to 4.4.1-SNAPSHOT for development 2023-10-04 22:19:02 -04:00
Jikoo 28fc5aea70 Bump version to 4.4.0 for release 2023-10-04 22:18:38 -04:00
Jikoo bfcf0233fa Fix ender chests not being silent 2023-10-04 22:15:35 -04:00
dependabot[bot] 3cf1aae89b Bump actions/checkout from 3 to 4 (#158)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-04 21:52:28 -04:00
dependabot[bot] db62878681 Bump org.apache.maven.plugins:maven-shade-plugin from 3.5.0 to 3.5.1 (#159) 2023-10-01 17:45:00 +00:00
Jikoo 21cd52c166 Fix probable NPE 2023-09-22 23:46:43 -04:00
dependabot[bot] 9d715b61c0 Bump maven-shade-plugin from 3.4.1 to 3.5.0 (#153)
Bumps [maven-shade-plugin](https://github.com/apache/maven-shade-plugin) from 3.4.1 to 3.5.0.
- [Release notes](https://github.com/apache/maven-shade-plugin/releases)
- [Commits](https://github.com/apache/maven-shade-plugin/compare/maven-shade-plugin-3.4.1...maven-shade-plugin-3.5.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-shade-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-22 23:20:13 -04:00
Jikoo d636cdd839 Add support for 1.20.2 2023-09-22 23:16:22 -04:00
Jikoo 1bebdb5602 Add OpenPlayerSaveEvent
Closes #156
2023-09-22 23:06:05 -04:00
Jikoo 57caf85500 Update Spigot 2023-09-10 11:23:49 -04:00
XPYEX 922586c925 Improve support for non-UTF-8 systems (#151) 2023-06-17 07:35:21 -04:00
Jikoo 9ec7bebecb Bump version to 4.3.2-SNAPSHOT for development 2023-06-10 11:09:43 -04:00
Jikoo 5a7d1399b5 Bump version to 4.3.1 for release 2023-06-10 11:09:30 -04:00
Adam cc7481fa9a Update to Minecraft 1.20 (#148) 2023-06-10 11:06:41 -04:00
dependabot[bot] 70d20aceb6 Bump maven-dependency-plugin from 3.5.0 to 3.6.0 (#146) 2023-06-01 18:11:12 +00:00
dependabot[bot] ac52211ce4 Bump maven-assembly-plugin from 3.5.0 to 3.6.0 (#147) 2023-06-01 18:07:58 +00:00
dependabot[bot] 6f2bdccc89 Bump dsaltares/fetch-gh-release-asset from 1.1.0 to 1.1.1 (#143)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-01 15:28:40 -04:00
Adam 6f23ed2528 Remove OS declaration from workflow_call (#144) 2023-05-01 15:26:56 -04:00
Adam 2d36249dbb Fix split up actions (#141) 2023-04-25 16:51:21 -04:00
Adam 2f370ad641 Fix loading users in deleted worlds on Paper (#139) 2023-04-17 18:20:31 -04:00
dependabot[bot] 1233f587c5 Bump hmarr/auto-approve-action from 3.1.0 to 3.2.1 (#134)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-01 15:22:44 -04:00
dependabot[bot] 23ebea405e Bump annotations from 24.0.0 to 24.0.1 (#133)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-01 15:22:34 -04:00
Jikoo 1bde75f9b3 Bump version to 4.3.1-SNAPSHOT for development 2023-03-16 16:44:10 -04:00
Jikoo 6ee2546efd Bump version to 4.3.0 for release 2023-03-16 16:43:56 -04:00
Adam 0e6acdff36 Update to 1.19.4 (#130)
* Improve data load/save slightly
* Fix longstanding issue with opening players in deleted worlds on Paper
2023-03-16 16:30:43 -04:00
Adam 3d4bed04d5 Split up actions (#129)
* Refactor conditional dependent jobs into separate actions
* Fix incorrect usage of pull_request_target
* Fix Dependabot not merging due to labels being absent when issue is created
* Prettify supported version listing
2023-03-15 08:13:33 -04:00
dependabot[bot] e885bf9a65 Bump maven-assembly-plugin from 3.4.2 to 3.5.0 (#127)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-01 18:21:01 -05:00
dependabot[bot] e15c566b82 Bump maven-compiler-plugin from 3.10.1 to 3.11.0 (#128)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-01 18:20:50 -05:00
dependabot[bot] c1ffd09d50 Bump pascalgn/automerge-action from 0.15.5 to 0.15.6 (#126)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-01 18:20:31 -05:00
Adam bd5e47760e Fix duplicate closes swapping players to spectate (#125) 2023-02-18 14:10:36 -05:00
dependabot[bot] 2fe0322570 Bump maven-dependency-plugin from 3.4.0 to 3.5.0 (#123)
Bumps [maven-dependency-plugin](https://github.com/apache/maven-dependency-plugin) from 3.4.0 to 3.5.0.
- [Release notes](https://github.com/apache/maven-dependency-plugin/releases)
- [Commits](https://github.com/apache/maven-dependency-plugin/compare/maven-dependency-plugin-3.4.0...maven-dependency-plugin-3.5.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-dependency-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-02 09:01:16 -05:00
dependabot[bot] 767476a759 Bump annotations from 23.1.0 to 24.0.0 (#122)
Bumps [annotations](https://github.com/JetBrains/java-annotations) from 23.1.0 to 24.0.0.
- [Release notes](https://github.com/JetBrains/java-annotations/releases)
- [Changelog](https://github.com/JetBrains/java-annotations/blob/master/CHANGELOG.md)
- [Commits](https://github.com/JetBrains/java-annotations/compare/23.1.0...24.0.0)

---
updated-dependencies:
- dependency-name: org.jetbrains:annotations
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-02 09:01:06 -05:00
dependabot[bot] dc8e36d11f Bump annotations from 23.0.0 to 23.1.0 (#121)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-01 19:13:14 -05:00
Adam 79b2a97c9e Clamp /searchcontainer radius (#117)
Default max is 10 because that's the default server view distance.
2022-12-20 16:44:49 -05:00
Adam 81eb60f628 Improve language manager (#116)
* Clarify replacements internally to reduce the likelihood of messing up when including new ones
 * Fix missing keys not being written to disk for easy translation
 * Use a guessfile-like system where missing translation keys are inserted into a separate section for easy identification
 * Reduce verbosity of missing keys warning
2022-12-20 15:54:30 -05:00
Adam e39f092f14 Add lookup cache, option to open self with no args (#115)
Add a cache for the last 10 offline lookups done by OpenInv#matchPlayer(String) to reduce the performance hit of repeat opens
Add config option to open self with no-arg command
2022-12-20 11:54:12 -05:00
Jikoo 4816737b90 Bump version to 4.2.3-SNAPSHOT for development 2022-12-11 11:35:36 -05:00
Jikoo 86bf24e7af Bump version to 4.2.2 for release 2022-12-11 11:35:21 -05:00
Jikoo 381dbb2a78 Don't disable minimizeJar in internal modules
MSHADE-366 was fixed in maven-shade-plugin 3.4.1. This is technically unnecessary either way as the only things currently being shaded are all our own modules.
2022-12-10 16:11:00 -05:00
Jikoo 46f3396b47 Update to Minecraft 1.19.3
1.19.2 is still supported - 1.19.1 was only dropped because there was no Spigot NMS revision bump.
2022-12-10 15:58:39 -05:00
dependabot[bot] 7b16391a80 Bump hmarr/auto-approve-action from 2.4.0 to 3.1.0 (#113)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-02 09:47:23 -05:00
dependabot[bot] 801530490d Bump dsaltares/fetch-gh-release-asset from 1.0.0 to 1.1.0 (#111)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-02 09:46:55 -05:00
dependabot[bot] d7e78177e0 Bump softprops/action-gh-release from 0.1.14 to 0.1.15 (#110)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-02 09:46:26 -05:00
dependabot[bot] e5128fa8db Bump pascalgn/automerge-action from 0.15.3 to 0.15.5 (#109)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-02 09:46:12 -05:00
dependabot[bot] 1efc0d4904 Bump maven-shade-plugin from 3.4.0 to 3.4.1 (#112)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-02 09:45:59 -05:00
dependabot[bot] 961a900632 Bump maven-dependency-plugin from 3.3.0 to 3.4.0 (#108)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-12-02 09:45:43 -05:00
Adam 0120d35a9a Fix advancement-related memory leak (#104)
Fix memory leak with loaded players' advancements
Fix missing transaction transfer for player inventories
Fix incorrect transaction transfer for ender chests
Minor code health
2022-10-14 16:40:33 -04:00
Adam c443615c1d Fix cache never being used for Spigot dependencies (#105) 2022-10-14 13:45:26 -04:00
dependabot[bot] b872f94855 Bump maven-shade-plugin from 3.3.0 to 3.4.0 (#102)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-01 15:13:03 -04:00
dependabot[bot] 2679a520a5 Bump actions/checkout from 2 to 3 (#103)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-01 15:12:52 -04:00
Adam d0648cc463 Fix incorrect player's locale used in view title (#101) 2022-10-01 12:43:57 -04:00
dependabot[bot] 1ceaf296f2 Bump maven-compiler-plugin from 3.8.1 to 3.10.1 (#76)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-10-01 12:36:48 -04:00
dependabot[bot] 1e0fb7bdb1 Bump hmarr/auto-approve-action from 2.2.1 to 2.4.0 (#99)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-10 14:52:17 -04:00
Jikoo 8c7698b40e Bump version to 4.2.2-SNAPSHOT for development 2022-08-01 13:35:25 -04:00
Jikoo 6b38cb7201 Bump version to 4.2.1 for release 2022-08-01 13:35:00 -04:00
dependabot[bot] 23e2a7e534 Bump maven-assembly-plugin from 3.3.0 to 3.4.2 (#94)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-01 13:32:56 -04:00
Elioby 1093b6d911 Update to 1.19.1 (#89) 2022-07-30 21:04:40 -04:00
Jikoo 89db744113 Bump version to 4.2.1-SNAPSHOT for development 2022-06-07 19:41:52 -04:00
Jikoo fcb9ccb6e6 Bump version to 4.2.0 for release 2022-06-07 19:41:39 -04:00
Jikoo 9c934e440d Update main plugin to Java 17
All supported versions require Java 17, there's no reason the plugin should not.
Swap to Temurin for CI, Adopt is dead.
2022-06-07 19:31:23 -04:00
Jikoo c2d60642c3 Update to Minecraft 1.19
Drop support for 1.17 and outdated 1.18 builds.
2022-06-07 19:31:23 -04:00
Jikoo 0653d12e49 Code health pass for Java 16 2022-06-07 19:31:22 -04:00
Jikoo f34b342cdd Tab? The drink? 2022-06-07 19:31:22 -04:00
Jikoo 70d8999b48 Move translations to a separate package
Makes it easier to find non-language files as necessary
2022-06-07 19:31:22 -04:00
Jikoo a5b21cbbf5 Correct crossworld check 2022-06-07 19:31:22 -04:00
Jikoo 44e514d8c2 Don't close other inventories for opened player during close 2022-06-07 19:31:22 -04:00
Jikoo 6407f1d8e4 Reorganize members 2022-06-07 19:31:22 -04:00
Jikoo 0b761a6fc3 Continue migrating terminology to "container"
Clean up documentation a bit, prettify
2022-06-07 19:31:21 -04:00
Jikoo 6ad6e0c6bc Bump version to 4.2.0-SNAPSHOT 2022-06-07 19:31:21 -04:00
Jikoo fdf920062b Remove cache, add disable-offline-access config node
Fixes various permissions not being respected during login/logout with inventories already open. This will result in a performance hit for repeated open/closes - there will be significantly more disk I/O.

Closes lishid#171
Closes #56
2022-06-07 19:31:21 -04:00
Jikoo 9502b29fe3 Clean up compiler warnings
Compiler doesn't understand that api is provided by plugin during build process
2022-06-07 19:31:21 -04:00
Jikoo c9ba401a6e Don't inject player if unnecessary 2022-06-07 19:31:21 -04:00
Jikoo b6e8e2ba42 Extract some duplicate code from internal implementations 2022-06-07 19:31:20 -04:00
Jikoo ac00261afb Note Spigot requirement 2022-06-07 19:31:20 -04:00
Jikoo f21019eba8 Extract help to location of use 2022-06-07 19:31:20 -04:00
Jikoo 525982ce64 Harden event/internal access slightly 2022-06-07 19:31:20 -04:00
dependabot[bot] 65c3358b22 Bump pascalgn/automerge-action from 0.15.2 to 0.15.3 (#82)
Bumps [pascalgn/automerge-action](https://github.com/pascalgn/automerge-action) from 0.15.2 to 0.15.3.
- [Release notes](https://github.com/pascalgn/automerge-action/releases)
- [Commits](https://github.com/pascalgn/automerge-action/compare/v0.15.2...v0.15.3)

---
updated-dependencies:
- dependency-name: pascalgn/automerge-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-01 17:29:37 -04:00
dependabot[bot] d6152f2f24 Bump dsaltares/fetch-gh-release-asset from 0.0.5 to 1.0.0 (#83)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-06-01 17:28:42 -04:00
dependabot[bot] cc3d96590f Bump hmarr/auto-approve-action from 2.0.0 to 2.2.1 (#77)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-05-01 13:19:34 -04:00
Jikoo 60c1d91e25 Simplify Maven check
Apparently Dependabot actually manages language labels when multiple options are enabled. Convenient!
2022-04-29 13:50:32 -04:00
Jikoo 7903942b51 Correct Action indentation
Wish it was more clearly indicated that the action was failing anywhere but the actions tab. No notification even, kind of annoying to have actually made a PR to double-check and then still have it fail.
2022-04-29 13:40:00 -04:00
Adam 22407aa865 Update dependencies, add Dependabot (#75) 2022-04-29 13:32:48 -04:00
Max Lee 173f49680b Log error message when failing to save player data (#72) 2022-04-05 17:10:58 -04:00
Jikoo 3103e8822b Bump version to 4.1.11-SNAPSHOT for development 2022-03-11 08:31:26 -05:00
Jikoo a547ab79fb Bump version to 4.1.10 for release 2022-03-11 08:31:11 -05:00
Jikoo bb75c723a7 Actually build 1.18.2 module 2022-02-28 22:16:26 -05:00
Jikoo 9bb94be7e2 Update to 1.18.2 2022-02-28 22:08:35 -05:00
Jikoo f78a5b4fba Ignore PlayerInventory owner as a viewer
If online, owner is always a viewer. If offline, they are never a viewer. There's no reason to count them - keeps inventory permanently cached while online if opened, even if not in use.
2022-01-27 11:37:53 -05:00
Jikoo 4ca222f031 Remove deprecated API usage 2022-01-27 11:16:06 -05:00
Jikoo 4fdfe15caa Update viewers for closed silent inventories
Closes #60
2022-01-27 11:15:34 -05:00
Jikoo 3aa31391be Add trace to InstantiationException
Closes #59
2022-01-27 10:03:12 -05:00
Jikoo abd529be66 Clean up compilation instructions for Mojang mappings 2022-01-19 10:23:26 -05:00
Jikoo 027d4e5637 Bump Spigot version to 1.18.1 2022-01-19 10:21:54 -05:00
Jikoo f8fb8cd034 Reduce duplicate configuration details
Adapters must now declare a `spigot.version` property.

* Greatly simplifies and speeds up retrieval of Spigot versions
2022-01-19 10:11:16 -05:00
Jikoo 6a31015ee2 Bump version to 4.1.10-SNAPSHOT for development 2021-12-02 16:15:34 -05:00
Jikoo 3e2b601997 Bump version to 4.1.9 for release 2021-12-02 16:15:22 -05:00
Jikoo 160ae47bf5 Correct wrong item list usage 2021-12-02 16:13:37 -05:00
Jikoo 98fbcebfd9 Fix non-translatable component, wrong flag value 2021-12-02 15:44:19 -05:00
Jikoo d236dd27b3 Update to 1.18-pre5 2021-11-23 13:00:42 -05:00
Jikoo dd90b5281f Use Java 17 for CI 2021-11-17 10:41:53 -05:00
Jikoo b4601bb6c1 Fix cached Spigot dependencies never being used
Since plugins have not been downloaded, get always fails when running in offline mode.
2021-10-16 19:16:08 -04:00
Jikoo e3d9cea027 Fix spigot dependency parsing
* Re-add cache
* Work around reflection issues with mvn help:evaluate on Java 9+
2021-10-16 18:03:38 -04:00
Jikoo 556a8bcfce Drop 1.16.5 support to use Mojang mappings
Because there is no option to create a `remapped-mojang` artifact for 1.16.5 and the whole point of the scripts is to save me time, 1.16.5 support is being removed earlier than usual.

Also fixes issues with NMS-based shulker collision check.
Closes #36
2021-10-16 16:53:59 -04:00
Jikoo 8599997e03 Work towards fixing shulkers 2021-10-16 16:11:18 -04:00
Jikoo ea99bd5fd4 Extract duplicate API-only code 2021-07-28 11:28:08 -04:00
蘭蘭露 Flandre_tw 2f36a4d4dc Add Chinese Simplified translation (#35) 2021-06-28 20:05:55 -04:00
蘭蘭露 Flandre_tw e5ebf11d32 Add Chinese Traditional translation (#34) 2021-06-28 20:05:15 -04:00
Jikoo 4336b454b7 Fix potential CME closing viewers without access
Closes #33
2021-06-24 08:21:26 -04:00
Jikoo b198931f30 Bump version to 4.1.9-SNAPSHOT for development 2021-06-11 18:40:48 -04:00
Jikoo 64af4dddb0 Bump version to 4.1.8 for release 2021-06-11 18:40:39 -04:00
Jikoo f613c0a522 Remove redundant load 2021-06-11 18:39:19 -04:00
Jikoo 1cae4c7a8e Correct window id 2021-06-11 18:39:07 -04:00
Jikoo ff7243db6a Fix script issues
Temporarily explicitly declare Spigot dependencies
I don't have the time to deal with whatever the difference between remote and local bash/maven versions is right now.
2021-06-11 12:05:38 -04:00
Jikoo 07a8e3b973 Add 1.17 support 2021-06-11 10:50:50 -04:00
Jikoo 9fccea60f7 Update copyright 2021-06-11 10:50:36 -04:00
Jikoo 9a2b379a64 Escape changelog for YAML
With 1.17 releasing soon, we'll get to see if this was the issue very shortly.
Worst case scenario the yaml is still messed up, but since the changelog is now the last element, unless it's so badly malformed that the entire action can't run the file should still upload even if the changelog does not.
2021-06-08 11:38:26 -04:00
Jikoo 4d800361d8 Bump version to 4.1.8-SNAPSHOT for development 2021-05-29 09:51:39 -04:00
Jikoo 2cfc55813b Bump version to 4.1.7 for release 2021-05-29 09:51:25 -04:00
Jikoo 0f41701429 Update annotations 2021-05-26 08:17:11 -04:00
Jikoo 9e0ca479a5 Fix Bukkit data not being loaded while offline
Closes #16
2021-05-26 08:16:25 -04:00
Jikoo bd207e948a Simplify dependency management
Use dependencyManagement for versioning shared dependencies
Use pluginManagement for versioning and configuring plugins
2021-04-23 13:40:22 -04:00
Jikoo 30425d2baa Don't bother validating names
Fixes problems with players from Geyser not being obtainable when using FloodGate.
2021-04-21 14:57:46 -04:00
Jikoo e3acb5384a Deprecate API for removed notification configuration 2021-04-05 19:12:45 -04:00
Jikoo 6c4818dfd9 Add method to access owner
Makes handling ISpecialInventory ownership much more consistent with a lot less spaghetti.
2021-03-28 11:12:49 -04:00
Jikoo 5b18656485 Fix incorrect player name in title
Closes #13
2021-03-28 11:10:39 -04:00
Jikoo 7ab86f2af9 Fix build 2021-03-22 12:20:58 -04:00
Jikoo 2b563e0e1b Don't convert release notes to HTML
We'll try this in another few months when there're enough changes to be worth it.
2021-03-22 12:07:53 -04:00
Jikoo 2a0e0d33d8 Don't shade annotations 2021-03-22 11:56:39 -04:00
Jikoo 889c2ffdab Bump version to 4.1.7-SNAPSHOT for development 2021-03-22 11:52:14 -04:00
Jikoo c440f618c9 Bump version to 4.1.6 for release 2021-03-22 11:52:04 -04:00
Jikoo ccc6f4b4a6 Fix CF release 2021-03-22 11:50:56 -04:00
Jikoo ae6c3bd292 Move release location 2021-03-22 10:24:48 -04:00
Jikoo 0e3bdb8741 Convert to HTML for CF 2021-03-22 10:21:09 -04:00
Jikoo e09e7c59c7 Fix release action 2021-03-22 09:42:52 -04:00
Jikoo 18c7916d79 Include release script 2021-03-22 09:41:36 -04:00
Jikoo 15ee6ef9a5 Fix revision number 2021-03-20 13:19:33 -04:00
Jikoo 24224e4f9d Add CurseForge release workflow 2021-03-20 13:06:33 -04:00
Jikoo 6563b4f6ce Migrate API-only functions out of PlayerDataManager
With the update to 1.16 there's no need to maintain multiple copies of the same code. Additionally, in 1.16 the action bar now supports JSON text.
2021-03-18 20:31:45 -04:00
Jikoo 1d5a836fd0 Partially automate release changelog 2021-03-18 16:38:41 -04:00
Jikoo 3ba82683ec Fix double chest custom names not displaying
Closes #175
2021-03-17 00:09:10 -04:00
Jikoo 6e5c332272 Extract player implementation 2021-03-16 23:49:17 -04:00
Jikoo 1c9d133ed1 Fix item delete in own inventory
Dragging items across top and bottom inventories with own inventory open resulted in the overlapping content being deleted.
2021-03-16 23:49:10 -04:00
Jikoo dad1e16c18 Fix item dupe in own inventory
Reduce desync for other actions in own inventory

Closes #182
2021-03-16 12:14:47 -04:00
Jikoo 519dd7da33 Fix cache breaking build on Spigot version change 2021-03-16 09:45:29 -04:00
Adam 1bd7932cc5 Drop 1.8/1.15/1.16.3 support (#185)
With the recent uptick in requests for support by people running 1.12 who have recently updated past Java 9, I revisited the supported versions.

First, the "modern" versions: 1.15 is run by 2.9% of servers, 1.16.3 by 5%. Since all of these versions are supported to ease the transition of updating servers and servers have updated, there's no real reason to keep them around. It's a lot easier if you can update a plugin and just have it work on both versions rather than push all the plugin updates to master with the server update, but none of these versions have any reason for long-term support.

Regarding heavily outdated server software: As of the time of writing, 1.8 and 1.12 have market shares of 8.6% and 8.5% of servers respectively.
Regarding 1.8: 1.8 support is already a bit wonky - with the changes made to inventory names, it's not (easily) possible to bridge the gap, and future changes will make that more and more difficult. People use 1.8 because they disliked the 1.9 combat changes, but there are plugins that fully rework combat to how it used to be. I have yet to hear a compelling argument that cannot be resolved with plugins. In the interest of my own sanity (handling and backporting the inventory name change in particular was a real humdinger) I will no longer be backporting changes to 1.8.
Regarding 1.12: I am honestly not sure why people are not updating. I get it, 1.13 and the flattening was a rough transition, but pretty much every developer active at the time bridged the gap. If your server is heavily dependent on some software only available at that time, you can live with other software available at that time. At the time of 1.12's release, Java 9 was not released. Either update your server, downgrade Java, or fork OpenInv and backport Java 9 support yourself.
2021-03-16 09:34:41 -04:00
Adam dad00d2d9c build: Add action to build and automatically release files (#170)
Auto-release is gonna get a nice live test at a later date.
2020-11-26 11:05:45 -05:00
Jikoo 502f661be3 fix: Update 1.15 adapter to 1.15.2 2020-11-26 10:47:51 -05:00
Jikoo 804d30bcc7 tpyo 2020-11-15 14:33:28 -05:00
Jikoo db8b67082b Fix up .gitignore a bit 2020-11-15 13:25:50 -05:00
Jikoo b2156edcc7 Fix mistake in InventoryAccess grabbing ender chest 2020-11-15 12:59:59 -05:00
Jikoo 45de495699 Simplify command executor assignment a little more 2020-11-15 12:26:36 -05:00
Jikoo f45d332727 Clarify download locations for older versions
Hopefully this will help people figure out where they've gone wrong. Maybe I should be stating supported versions in release notes too.
2020-11-15 12:22:25 -05:00
Jikoo 9705cb156b Bump version to 4.1.6-SNAPSHOT for development 2020-11-03 18:32:43 -05:00
Jikoo 1c45ef517f Bump version to 4.1.5 for release 2020-11-03 18:32:11 -05:00
Jikoo 3fee84fc58 Add support for 1.16.4, drop 1.16.1 2020-11-03 18:19:34 -05:00
Jikoo 00113cc4d4 These are my favorite version bumps 2020-09-15 13:47:12 -04:00
Jikoo 788f022e74 Mitigate some permissions confusion
For some reason, certain permissions plugins seem to not respect our declared default false nodes. To alleviate user confusion, these nodes will not be allowed to be used via wildcard internally.
2020-09-15 13:44:50 -04:00
Jikoo da55790fd2 Allow spectators to edit inventories
Requires permission OpenInv.spectate
Closes #155
2020-09-15 13:35:04 -04:00
Jikoo 1a6d513603 Reduce technical debt
* Reduce duplicate code
* Use more specific functional interfaces where available
* Fix some potential NPEs
* Remove some unnecessary/nonfunctional code
* Merge inventory listeners - no longer need to keep separate due to event availability
* Removed TODO items that probably won't ever be implemented. Good ideas, too drastic changes or too much work to maintain.
2020-09-15 12:51:49 -04:00
Jikoo a5b02ab26a Bump version to 4.1.5-SNAPSHOT for development 2020-08-22 12:22:00 -04:00
Jikoo 0c3ce2dfb3 Bump version to 4.1.4 for release 2020-08-22 12:21:22 -04:00
Jikoo a1f4649a09 Reword invalid version message, include releases link 2020-08-22 12:00:08 -04:00
Jikoo 100d0e12cd Update to 1.16.2 2020-08-12 00:06:20 -04:00
Jikoo 3e629798e5 Bump version to 4.1.4-SNAPSHOT for development 2020-07-15 23:23:31 -04:00
Jikoo 7c1f15974c Bump version to 4.1.3 for release 2020-07-15 23:23:03 -04:00
mfnalex d992237766 Add support for 3rd party plugins firing PlayerInteractEvent (#146)
* Add support for InvUnload

* generalize 3rd party plugins' event check
2020-07-15 22:38:38 -04:00
Jikoo c93464e643 Fix double chest loot generation with AnyContainer (#142) 2020-07-08 20:44:15 -04:00
Jikoo 56afefc82b Bump version to 4.1.3-SNAPSHOT for development 2020-06-25 19:40:07 -04:00
Jikoo f0a66570d2 Bump version to 4.1.2 for release 2020-06-25 19:39:38 -04:00
Jikoo 201a3578bf Add 1.16 support, drop 1.14 (#141) 2020-06-25 19:38:38 -04:00
Nathaniel Freeman 1228fc2de2 es_ES translation 2020-06-24 07:12:20 -04:00
NotMyFault 2561e75ae5 Fix typo 2020-06-02 19:01:33 -04:00
N0tMyFaultOG 80661b9465 Add german translation 2020-06-02 17:59:31 -04:00
Jikoo 53701da34f Bump version to 4.1.2-SNAPSHOT for development 2020-05-29 10:32:32 -04:00
Jikoo 9cf4712813 Bump version to 4.1.1 for release 2020-05-29 10:32:03 -04:00
Jikoo abe8fccdb5 Document new nodes 2020-05-29 10:27:50 -04:00
Jikoo 4499bb5453 Don't break behavior on existing setups
Permission to use /openinv and /openender will grant online/offline access so that existing permissions configurations do not have to be redone. Users looking to implement the new permissions will need to deny them.
2020-05-29 10:22:40 -04:00
Phoenix616 5405b7d7b9 Add permission for online/offline opening (Resolves #129) 2020-05-29 10:08:26 -04:00
129fc5e32c631b5007cb2cd8d45d416002b42bab 34199d12a4 Add localization for Brazilian Portuguese 2020-04-30 17:42:10 -04:00
Jikoo 67131ab9f9 Save after adding new keys 2020-04-24 10:47:51 -04:00
Jikoo 723381cb2b Fix IndexOutOfBounds on no args
Closes #128
2020-04-22 12:07:19 -04:00
Jikoo 34e7252d77 Correct lang + replacement mistake with inventory names 2020-04-19 18:04:10 -04:00
Jikoo a1b2df74cc Save existing vehicles if we had to load player (#22) 2020-04-19 17:54:45 -04:00
Jikoo 7210f9153e Bump version to 4.1.1-SNAPSHOT for development 2020-04-18 08:05:09 -04:00
Jikoo dcdfac0d3b Bump version to 4.1.0 for release 2020-04-18 08:04:38 -04:00
Jikoo c7b4554a6c It's been over 3 years :)
The common module was designed to prevent the internal modules depending on the core plugin. With the introduction of localization, this overcomplication became ever more exacerbated.
Probably will play around a bit more to remove freshly introduced static abuse before release.
Closes #61
2020-03-24 21:01:59 -04:00
Jikoo c51acb4e72 Add basic /searchcontainer
May be subject to change as I (very slowly) work towards console support for commands.
Closes #113
2020-03-15 10:43:08 -04:00
Jikoo 23d41cd6c8 Simplify and expand tab completion 2020-03-15 09:50:51 -04:00
Jikoo 8bc389496b Update cache for Java 8 2020-03-15 09:49:11 -04:00
Jikoo 1cc36d08bd Modify players before other plugins access them
Closes #123
2020-03-11 09:17:17 -04:00
Jikoo c8938f451d Update copyright 2020-02-01 08:03:15 -05:00
Jikoo 4f2665fedc Improve any/silent container commands
* Merged duplicate code
* Added on/off parameters - closes #120
* Added tab completion for parameters
2020-02-01 08:00:03 -05:00
unixminecraft 7d93bb06ad Updated /sc check command to correctly display if SilentChest is active or not. 2020-01-14 22:40:01 -05:00
Jikoo 19c491411f Bump version to 4.0.9-SNAPSHOT for development 2019-12-12 14:37:03 -05:00
Jikoo 65c6eb2693 Bump version to 4.0.8 for release 2019-12-12 14:36:38 -05:00
Jikoo ab1f4ace8a Fix AnyContainer breaking modified ender chest sizes 2019-12-12 14:33:42 -05:00
Jikoo e7dc52bee4 Drop support for 1.13, latest 2 versions only. 2019-12-12 14:21:33 -05:00
Jikoo a9c5799677 Merge branch 'master' of https://github.com/lishid/OpenInv 2019-12-12 13:59:38 -05:00
Andre LeBlanc 6d6257720a add support for 1.15 2019-12-12 13:59:12 -05:00
Andre LeBlanc 3e235fa688 add support for 1.15 2019-12-12 12:49:21 -05:00
Jikoo dd02355ac2 Properly remove SilentContainer viewers
Closes #115
2019-12-03 13:50:27 -05:00
Jikoo 4d3f5d67a8 Update copyright
Practically should make it 2020 at this rate, whoops

(cherry picked from commit ff76f2b95ac5ea2a32a42b5dcd82a5e5b762b831)
2019-12-03 13:32:41 -05:00
Jikoo 7ad5faa2ce Clean up maven instructions
(cherry picked from commit b92543e0789518183cfa685302d7938932b09550)
2019-12-03 13:32:37 -05:00
Jikoo c28383ef36 Work around 1.14 tab completion issues 2019-10-01 08:30:28 -04:00
Jikoo 5fbab1ab8f Bump version to 4.0.8-SNAPSHOT for development 2019-09-29 19:43:14 -04:00
Jikoo d97b092978 Bump version to 4.0.7 for release 2019-09-29 19:42:59 -04:00
Jikoo 154bf56c2a Include api-version in plugin.yml
Closes #111, #112
2019-09-29 19:40:06 -04:00
William Blake Galbreath d65a9caeb2 Add support for varying sizes of inventories 2019-08-01 21:04:23 -04:00
Jikoo b3c4253606 Bump version to 4.0.7-SNAPSHOT for development 2019-07-21 13:30:02 -04:00
Jikoo b64000e89b Bump version to 4.0.6 for release 2019-07-21 13:29:45 -04:00
Jikoo 3faf41ef18 More clear error when loot is not generated 2019-07-19 18:16:36 -04:00
Jikoo db27d25a93 More Bukkit API, less breaking with new versions 2019-07-19 18:14:14 -04:00
Jikoo 0f02e6fe66 Right, 1.13 is a thing 2019-07-19 18:12:06 -04:00
Jikoo ec07637e9f Bump version to 4.0.6-SNAPSHOT for development 2019-07-19 16:26:24 -04:00
Jikoo b269f3509c Bump version to 4.0.5 for release 2019-07-19 16:26:03 -04:00
Jikoo f2e4c8a3ad Fix barrel triggering AnyContainer (#108) 2019-07-19 16:24:58 -04:00
Jikoo 35839f1548 Bump version to 4.0.5-SNAPSHOT for development 2019-07-19 07:21:37 -04:00
Jikoo a4a462a1fa Bump version to 4.0.4 for release 2019-07-19 07:21:16 -04:00
Jikoo b9f901af66 Add silent barrels - fixes #106 2019-07-19 07:18:23 -04:00
Jikoo 1333056613 Correct item order - fixes #107 2019-07-19 07:13:11 -04:00
Jikoo fb23df313a Bump version to 4.0.4-SNAPSHOT for development 2019-05-27 20:53:44 -04:00
Jikoo 96dc400c83 Bump version to 4.0.3 for release 2019-05-27 20:53:02 -04:00
Jikoo b801d36f12 Turns out api-version below 1.13 is unsupported.
Compiling for 1.8, no api-version.
2019-05-27 20:52:49 -04:00
Jikoo 4c27599dd9 Bump version to 4.0.3-SNAPSHOT for development 2019-05-27 20:23:16 -04:00
Jikoo 64ad0a5267 Bump version to 4.0.2 for release 2019-05-27 20:22:50 -04:00
Jikoo cba7f44192 Include api-version in plugin.yml (Closes #102) 2019-05-27 20:22:02 -04:00
Jikoo e8ace6bd06 Update to 1.14.2 2019-05-27 20:12:39 -04:00
Jikoo fd70f260ba Fix mistake in string comparison utility 2019-05-27 20:05:58 -04:00
Jikoo be9874ba1d Fix pom changes causing Spigot API to be shaded into final jar 2019-05-27 20:05:06 -04:00
Jikoo 096faef161 Bump version to 4.0.2-SNAPSHOT for development 2019-05-15 19:20:50 -04:00
Jikoo df96d5106a Bump version to 4.0.1 for release 2019-05-15 19:20:25 -04:00
Jikoo fe77a1d2e7 Drop support for 1.14, add support for 1.14.1 2019-05-15 19:19:40 -04:00
Jikoo 3096e43540 Update to Java 8 and Minecraft 1.8.8 2019-05-05 22:20:43 -04:00
Jikoo 2939551d65 Delete modules for versions no longer being supported 2019-05-05 18:03:22 -04:00
Jikoo fb74fd3ced Bump version to 4.0.1-SNAPSHOT for development 2019-05-05 16:55:36 -04:00
Jikoo 393fe1d837 Bump version to 4.0.0 for release 2019-05-05 16:55:12 -04:00
Jikoo f80df9d83b Copy pasted javadocs are super great 2019-05-05 16:49:41 -04:00
Jikoo 5c006f8ebd QOL: Warn users when plugin is running on an unsupported version 2019-05-05 15:43:41 -04:00
Jikoo 57097e626e Reduce duplicate code in core plugin 2019-05-05 15:39:54 -04:00
Jikoo 0f266c8a64 Custom inventory titles for 1.14 2019-05-05 15:15:17 -04:00
Jikoo 185f037254 Revert API changes, fix SpecialPlayerInventory implementation 2019-05-05 12:40:47 -04:00
Jikoo e4d0020296 Update to 1.14 (#101) 2019-04-28 20:37:45 -04:00
Jikoo 9e37cbbca8 Prepare for 1.14
To continue providing renamed ender chests/player inventories we can no longer just provide an Inventory, a full InventoryView is required. To avoid confusion the old method has been removed entirely, leading to a major API revision bump.
2019-04-28 20:37:05 -04:00
Jikoo adc35e9ad5 Correct players not being properly released 2019-04-28 12:11:59 -04:00
Jikoo a469c732cc Store UUID instead of name for faster re-open lookups 2019-04-28 11:03:00 -04:00
Jikoo c5c1f47167 Hacky workaround for Java 9 reflection changes (#93) 2019-04-12 20:56:05 -04:00
Jikoo dc59356f76 Bump version to 3.3.8-SNAPSHOT for development 2019-01-18 18:36:28 -05:00
Jikoo d497772ad7 Bump version to 3.3.7 for release 2019-01-18 18:35:50 -05:00
Jikoo 4f4d46974a Support 1.13.2 (#94) 2019-01-15 20:01:41 -05:00
Jikoo 96c38895e2 Bump version to 3.3.7-SNAPSHOT for development 2018-08-26 14:47:13 -04:00
Jikoo 5753648d77 Bump version to 3.3.6 for release 2018-08-26 14:46:33 -04:00
Jikoo 3725711b94 Support Spigot 1.13.1 2018-08-26 14:43:21 -04:00
Jikoo c22e18c096 Correct unnecessary AnyContainer usage 2018-08-26 14:37:29 -04:00
Jikoo 6bff759d72 Bump version to 3.3.6-SNAPSHOT for development 2018-08-13 21:31:46 -04:00
Jikoo 582c7201dd Bump version to 3.3.5 for release 2018-08-13 21:31:17 -04:00
Jikoo 59a8ed70bb Correct double chest logic for Silent/AnyContainer in 1.13 2018-08-09 18:50:24 -04:00
Jikoo 27812c133d Bump version to 3.3.5-SNAPSHOT for development 2018-07-22 09:45:01 -04:00
Jikoo 165f3fb00e Bump version to 3.3.4 for release 2018-07-22 09:44:27 -04:00
Jikoo 60dcb64558 Bump version for alpha release 2018-07-15 12:05:52 -04:00
Jikoo 077b34d304 Support 1.13-pre7 2018-07-15 12:01:45 -04:00
Jikoo 8ce6e2f8d3 Reverse order of wildcard permission check, respect explicit values (#85) 2018-05-26 06:58:56 -04:00
Jikoo f5dce23f18 Bump version to 3.3.4-SNAPSHOT for development 2018-02-07 18:36:15 -05:00
224 changed files with 10203 additions and 19347 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
.gitea/CODEOWNERS linguist-detectable=false
+3
View File
@@ -0,0 +1,3 @@
# Pull requests request review from the eligible staff team(s).
# One approval from either an Admin or Developer satisfies branch protection.
* @trueog/Admins @trueog/Developers
+9 -8
View File
@@ -1,11 +1,12 @@
**/.settings
**/.gitignore
**/.project
**/.classpath
**/.idea
**/.iml
**/target
**/bin
**/out
**dependency-reduced-pom.xml
**pom.xml.versionsBackup
**/.idea/
**.iml
**/target/
**/build/
**/bin/
**/out/
**/.gradle/
**/dependency-reduced-pom.xml
**/pom.xml.versionsBackup
+39 -62
View File
@@ -15,48 +15,7 @@ OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) whi
- **AnyContainer**: Open containers, even if blocked by ocelots or blocks.
## Commands
<table width=100%>
<tr>
<th width=175px>Command</th>
<th>Aliases</th>
<th>Description</th>
</tr>
<tr>
<td>/openinv [player]</td>
<td>oi, inv, open</td>
<td>Open a player's inventory. If unspecified, will select last player opened or own if none opened previously.</td>
</tr>
<tr>
<td>/openender [player]</td>
<td>oe</td>
<td>Open a player's ender chest. If unspecified, will select last player opened or own if none opened previously.</td>
</tr>
<tr>
<td>/searchinv &ltitem&gt [minAmount]</td>
<td>si</td>
<td>Lists all online players that have a certain item in their inventory.</td>
</tr>
<tr>
<td>/searchender &ltitem&gt [minAmount]</td>
<td>se</td>
<td>Lists all online players that have a certain item in their ender chest.</td>
</tr>
<tr>
<td>/searchenchant &lt[enchantment] [MinLevel]&gt</td>
<td>searchenchants</td>
<td>Lists all online players with a specific enchantment.</td>
</tr>
<tr>
<td>/anycontainer [check]</td>
<td>ac, anychest</td>
<td>Check or toggle the AnyContainer function, allowing opening blocked containers.</td>
</tr>
<tr>
<td>/silentcontainer [check]</td>
<td>sc, silentchest</td>
<td>Check or toggle the SilentContainer function, allowing opening containers silently.</td>
</tr>
</table>
See [the wiki](https://github.com/Jikoo/OpenInv/wiki/Commands).
## Permissions
<table>
@@ -80,6 +39,14 @@ OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) whi
<td>OpenInv.editinv</td>
<td>Required to make changes to open inventories.</td>
</tr>
<tr>
<td>OpenInv.openonline</td>
<td>Allows users to open online players' inventories. For compatibility reasons this is granted by the nodes OpenInv.openinv and OpenInv.openender.</td>
</tr>
<tr>
<td>OpenInv.openoffline</td>
<td>Allows users to open offline players' inventories. For compatibility reasons this is granted by the nodes OpenInv.openinv and OpenInv.openender.</td>
</tr>
<tr>
<td>OpenInv.openender</td>
<td>Required to use /openender.</td>
@@ -128,29 +95,39 @@ OpenInv is a [Bukkit plugin](https://dev.bukkit.org/bukkit-plugins/openinv/) whi
<td>OpenInv.silent.default</td>
<td>Cause SilentContainer to be enabled by default.</td>
</tr>
<tr>
<td>OpenInv.spectate</td>
<td>Allows users in spectate gamemode to edit inventories.</td>
</tr>
</table>
## For Developers
To compile, the relevant Craftbukkit/Spigot jars must be installed in your local repository using the install plugin.
Ex: `mvn install:install-file -Dpackaging=jar -Dfile=spigot-1.11-R0.1-SNAPSHOT.jar -DgroupId=org.spigotmc -DartifactId=spigot -Dversion=1.11-R0.1-SNAPSHOT`
To compile for a specific version or set of versions, you'll need to use a profile. Provided profiles are `latest`, `recent` (last 2 major Minecraft versions), and `all`. Select an existing profile using the `-P` argument (ex: `mvn clean package -am -P all`) or make your own. For more information, check out the [official guide](http://maven.apache.org/guides/introduction/introduction-to-profiles.html).
The final file is target/OpenInv.jar
## License
### As a Dependency
The OpenInv API is available via [JitPack](https://jitpack.io/).
```xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
```
Copyright (C) 2011-2018 lishid. All rights reserved.
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, version 3.
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 <http://www.gnu.org/licenses/>.
```xml
<dependencies>
<dependency>
<groupId>com.github.jikoo.OpenInv</groupId>
<artifactId>openinvapi</artifactId>
<version>${openinv.version}</version>
</dependency>
</dependencies>
```
### Compilation
OpenInv now builds with Gradle 8.14.3 using Paperweight userdev for Purpur `1.19.4` on Java 17 / GraalVM 17.
Build the plugin with:
`./gradlew build`
The server-ready shaded jar is written to:
`build/libs/OpenInv-${version}.jar`
-40
View File
@@ -1,40 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvparent</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvapi</artifactId>
<name>OpenInvAPI</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.5-R1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/bukkit-1.4.5-R1.0.jar</systemPath>
</dependency>
</dependencies>
</project>
+225 -185
View File
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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
@@ -16,235 +16,275 @@
package com.lishid.openinv;
import javax.annotation.Nullable;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InventoryAccess;
import java.util.UUID;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Interface defining behavior for the OpenInv plugin.
*
* @author Jikoo
*/
public interface IOpenInv {
/**
* Check the configuration value for whether or not OpenInv saves player data when unloading
* players. This is exclusively for users who do not allow editing of inventories, only viewing,
* and wish to prevent any possibility of bugs such as lishid#40. If true, OpenInv will not ever
* save any edits made to players.
*
* @return false unless configured otherwise
*/
boolean disableSaving();
/**
* Gets the active ISilentContainer implementation. May return null if the server version is
* unsupported.
*
* @return the ISilentContainer
* @throws IllegalStateException if the server version is unsupported
*/
IAnySilentContainer getAnySilentContainer();
/**
* Gets an ISpecialEnderChest for the given Player. Returns null if the ISpecialEnderChest could
* not be instantiated.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialEnderChest
* @throws IllegalStateException if the server version is unsupported
* @deprecated Use {@link IOpenInv#getSpecialEnderChest(Player, boolean)}
*/
@Deprecated
@Nullable
ISpecialEnderChest getEnderChest(Player player, boolean online);
/**
* Gets an ISpecialPlayerInventory for the given Player. Returns null if the
* ISpecialPlayerInventory could not be instantiated.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialPlayerInventory
* @throws IllegalStateException if the server version is unsupported
* @deprecated Use {@link IOpenInv#getSpecialInventory(Player, boolean)}
*/
@Deprecated
@Nullable
ISpecialPlayerInventory getInventory(Player player, boolean online);
/**
* Gets the active IInventoryAccess implementation. May return null if the server version is
* unsupported.
*
* @return the IInventoryAccess
* @throws IllegalStateException if the server version is unsupported
*/
IInventoryAccess getInventoryAccess();
/**
* Gets the provided player's AnyChest setting.
*
* @param player the OfflinePlayer
* @return true if AnyChest is enabled
* @throws IllegalStateException if the server version is unsupported
*/
boolean getPlayerAnyChestStatus(OfflinePlayer player);
/**
* Gets a unique identifier by which the OfflinePlayer can be referenced. Using the value
* returned to look up a Player will generally be much faster for later implementations.
*
* @param offline the OfflinePlayer
* @return the identifier
* @throws IllegalStateException if the server version is unsupported
*/
String getPlayerID(OfflinePlayer offline);
/**
* Gets a player's SilentChest setting.
*
* @param player the OfflinePlayer
* @return true if SilentChest is enabled
* @throws IllegalStateException if the server version is unsupported
*/
boolean getPlayerSilentChestStatus(OfflinePlayer player);
/**
* Gets an ISpecialEnderChest for the given Player.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialEnderChest
* @throws IllegalStateException if the server version is unsupported
* @throws InstantiationException if the ISpecialEnderChest could not be instantiated
*/
ISpecialEnderChest getSpecialEnderChest(Player player, boolean online) throws InstantiationException;
/**
* Gets an ISpecialPlayerInventory for the given Player.
*
* @param player the Player
* @param online true if the Player is currently online
* @return the ISpecialPlayerInventory
* @throws IllegalStateException if the server version is unsupported
* @throws InstantiationException if the ISpecialPlayerInventory could not be instantiated
*/
ISpecialPlayerInventory getSpecialInventory(Player player, boolean online) throws InstantiationException;
/**
* Checks if the server version is supported by OpenInv.
* Check if the server version is supported by OpenInv.
*
* @return true if the server version is supported
*/
boolean isSupportedVersion();
/**
* Load a Player from an OfflinePlayer. May return null under some circumstances.
* Check the configuration value for whether OpenInv saves player data when unloading players. This is exclusively
* for users who do not allow editing of inventories, only viewing, and wish to prevent any possibility of bugs such
* as lishid#40. If true, OpenInv will not ever save any edits made to players.
*
* @param offline the OfflinePlayer to load a Player for
* @return the Player, or null
* @throws IllegalStateException if the server version is unsupported
* @return false unless configured otherwise
*/
@Nullable
Player loadPlayer(final OfflinePlayer offline);
boolean disableSaving();
/**
* Get an OfflinePlayer by name.
* <p>
* Note: This method is potentially very heavily blocking. It should not ever be called on the
* Check the configuration value for whether OpenInv allows offline access. If true, OpenInv will not load or allow
* modification of players while they are not online. This does not prevent other plugins from using existing loaded
* players who have gone offline.
*
* @return false unless configured otherwise
* @since 4.2.0
*/
boolean disableOfflineAccess();
/**
* Check the configuration value for whether OpenInv uses history for opening commands. If false, OpenInv will use
* the previous parameterized search when no parameters are provided.
*
* @return false unless configured otherwise
* @since 4.3.0
*/
boolean noArgsOpensSelf();
/**
* Get the active {@link IAnySilentContainer} implementation.
*
* @return the active implementation for the server version
* @throws IllegalStateException if the server version is unsupported
*/
@NotNull IAnySilentContainer getAnySilentContainer();
/**
* @deprecated Use static {@link InventoryAccess} methods.
*/
@Deprecated(forRemoval = true)
default @NotNull IInventoryAccess getInventoryAccess() {
return new InventoryAccess();
}
/**
* @deprecated Use {@link #getAnyContainerStatus(OfflinePlayer)}. Not all containers are chests.
*/
@Deprecated(forRemoval = true, since = "4.2.0")
default boolean getPlayerAnyChestStatus(@NotNull OfflinePlayer offline) {
return getAnyContainerStatus(offline);
}
/**
* Get whether a user has AnyContainer mode enabled.
*
* @param offline the user to obtain the state of
* @return true if AnyContainer mode is enabled
*/
boolean getAnyContainerStatus(@NotNull OfflinePlayer offline);
/**
* @deprecated Use {@link #setAnyContainerStatus(OfflinePlayer, boolean)}. Not all containers are chests.
*/
@Deprecated(forRemoval = true, since = "4.2.0")
default void setPlayerAnyChestStatus(@NotNull OfflinePlayer offline, boolean status) {
setAnyContainerStatus(offline, status);
}
/**
* Set whether a user has AnyContainer mode enabled.
*
* @param offline the user to set the state of
* @param status the state of the mode
*/
void setAnyContainerStatus(@NotNull OfflinePlayer offline, boolean status);
/**
* @deprecated Use {@link #getSilentContainerStatus(OfflinePlayer)}. Not all containers are chests.
*/
@Deprecated(forRemoval = true, since = "4.2.0")
default boolean getPlayerSilentChestStatus(@NotNull OfflinePlayer offline) {
return getSilentContainerStatus(offline);
}
/**
* Get whether a user has SilentContainer mode enabled.
*
* @param offline the user to obtain the state of
* @return true if SilentContainer mode is enabled
*/
boolean getSilentContainerStatus(@NotNull OfflinePlayer offline);
/**
* @deprecated Use {@link #setSilentContainerStatus(OfflinePlayer, boolean)}. Not all containers are chests.
*/
@Deprecated(forRemoval = true, since = "4.2.0")
default void setPlayerSilentChestStatus(@NotNull OfflinePlayer offline, boolean status) {
setSilentContainerStatus(offline, status);
}
/**
* Set whether a user has SilentContainer mode enabled.
*
* @param offline the user to set the state of
* @param status the state of the mode
*/
void setSilentContainerStatus(@NotNull OfflinePlayer offline, boolean status);
/**
* Get a unique identifier by which the OfflinePlayer can be referenced.
*
* @deprecated Use {@link OfflinePlayer#getUniqueId()} and {@link UUID#toString()}. This was necessary for non-UUID
* versions of Minecraft, but support for them has been dropped for years.
* @param offline the OfflinePlayer
* @return the identifier
* @throws IllegalStateException if the server version is unsupported
*/
@Deprecated(forRemoval = true)
default @NotNull String getPlayerID(@NotNull OfflinePlayer offline) {
return offline.getUniqueId().toString();
}
/**
* Get an {@link ISpecialEnderChest} for a user.
*
* @param player the {@link Player} owning the inventory
* @param online whether the owner is currently online
* @return the created inventory
* @throws IllegalStateException if the server version is unsupported
* @throws InstantiationException if there was an issue creating the inventory
*/
@NotNull ISpecialEnderChest getSpecialEnderChest(@NotNull Player player, boolean online) throws InstantiationException;
/**
* Get an {@link ISpecialPlayerInventory} for a user.
*
* @param player the {@link Player} owning the inventory
* @param online whether the owner is currently online
* @return the created inventory
* @throws IllegalStateException if the server version is unsupported
* @throws InstantiationException if there was an issue creating the inventory
*/
@NotNull ISpecialPlayerInventory getSpecialInventory(@NotNull Player player, boolean online) throws InstantiationException;
/**
* Open an {@link ISpecialInventory} for a {@link Player}.
*
* @param player the viewer
* @param inventory the inventory to open
* @return the resulting {@link InventoryView}
*/
@Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory);
/**
* Check if a {@link Player} is currently loaded by OpenInv.
*
* @param playerUuid the {@link UUID} of the {@code Player}
* @return whether the {@code Player} is loaded
* @since 4.2.0
*/
boolean isPlayerLoaded(@NotNull UUID playerUuid);
/**
* Load a {@link Player} from an {@link OfflinePlayer}. If the user has not played before or the default world for
* the server is not loaded, this will return {@code null}.
*
* @param offline the {@code OfflinePlayer} to load a {@code Player} for
* @return the loaded {@code Player}
* @throws IllegalStateException if the server version is unsupported
*/
@Nullable Player loadPlayer(@NotNull final OfflinePlayer offline);
/**
* Match an existing {@link OfflinePlayer}. If the name is a {@link UUID#toString() UUID string}, this will only
* return the user if they have actually played on the server before, unlike {@link Bukkit#getOfflinePlayer(UUID)}.
*
* <p>This method is potentially very heavily blocking. It should not ever be called on the
* main thread, and if it is, a stack trace will be displayed alerting server owners to the
* call.
*
* @param name the name of the Player
* @return the OfflinePlayer with the closest matching name or null if no players have ever logged in
* @param name the string to match
* @return the user with the closest matching name
*/
@Nullable
OfflinePlayer matchPlayer(String name);
@Nullable OfflinePlayer matchPlayer(@NotNull String name);
/**
* Check the configuration value for whether or not OpenInv displays a notification to the user
* when a container is activated with AnyChest.
*
* @return true unless configured otherwise
* @deprecated OpenInv uses action bar chat for notifications. Whether they show is based on language settings.
*/
boolean notifyAnyChest();
@Deprecated(forRemoval = true)
default boolean notifyAnyChest() {
return true;
}
/**
* Check the configuration value for whether or not OpenInv displays a notification to the user
* when a container is activated with SilentChest.
*
* @return true unless configured otherwise
* @deprecated OpenInv uses action bar chat for notifications. Whether they show is based on language settings.
*/
boolean notifySilentChest();
@Deprecated(forRemoval = true)
default boolean notifySilentChest() {
return true;
}
/**
* Mark a Player as no longer in use by a Plugin to allow OpenInv to remove it from the cache
* when eligible.
*
* @param player the Player
* @param plugin the Plugin no longer holding a reference to the Player
* @throws IllegalStateException if the server version is unsupported
* @deprecated see {@link #retainPlayer(Player, Plugin)}
*/
void releasePlayer(Player player, Plugin plugin);
@Deprecated(forRemoval = true, since = "4.2.0")
default void releasePlayer(@NotNull Player player, @NotNull Plugin plugin) {}
/**
* Mark a Player as in use by a Plugin to prevent it from being removed from the cache. Used to
* prevent issues with multiple copies of the same Player being loaded such as lishid#49.
* Changes made to loaded copies overwrite changes to the others when saved, leading to
* duplication bugs and more.
* <p>
* When finished with the Player object, be sure to call {@link #releasePlayer(Player, Plugin)}
* to prevent the cache from keeping it stored until the plugin is disabled.
* <p>
* When using a Player object from OpenInv, you must handle the Player coming online, replacing
* your Player reference with the Player from the PlayerJoinEvent. In addition, you must change
* any values in the Player to reflect any unsaved alterations to the existing Player which do
* not affect the inventory or ender chest contents.
* <p>
* OpenInv only saves player data when unloading a Player from the cache, and then only if
* {@link #disableSaving()} returns false. If you are making changes that OpenInv does not cause
* to persist when a Player logs in as noted above, it is suggested that you manually call
* {@link Player#saveData()} when releasing your reference to ensure your changes persist.
* @deprecated OpenInv no longer uses an internal cache beyond maintaining copies of currently open inventories.
* If you wish to use/modify a player, ensure either {@link IOpenInv#isPlayerLoaded(UUID)} is false or the player
* instance is the same memory address as the one in use by OpenInv.
* <pre>
* public &#64;NotNull Player savePlayerData(&#64;NotNull Player player) {
* IOpenInv openInv = ...
* if (!openInv.disableSaving() && openInv.isPlayerLoaded(player.getUniqueId())) {
* Player openInvLoadedPlayer = openInv.loadPlayer(myInUsePlayer);
* if (openInvLoadedPlayer != player) {
* // The copy loaded by OpenInv is not the same as our loaded copy. Push our changes.
* copyPlayerModifications(player, openInvLoadedPlayer);
* }
* // OpenInv will handle saving data when the player is unloaded.
* // Optionally, to be sure our changes will persist, save now.
* // openInvLoadedPlayer.saveData();
* return openInvLoadedPlayer;
* }
*
* @param player the Player
* @param plugin the Plugin holding the reference to the Player
* @throws IllegalStateException if the server version is unsupported
* player.saveData();
* return player;
* }
* </pre>
*/
void retainPlayer(Player player, Plugin plugin);
@Deprecated(forRemoval = true, since = "4.2.0")
default void retainPlayer(@NotNull Player player, @NotNull Plugin plugin) {}
/**
* Sets a player's AnyChest setting.
* Forcibly close inventories of and unload any cached data for a user.
*
* @param player the OfflinePlayer
* @param status the status
* @throws IllegalStateException if the server version is unsupported
* @param offline the {@link OfflinePlayer} to unload
*/
void setPlayerAnyChestStatus(OfflinePlayer player, boolean status);
void unload(@NotNull OfflinePlayer offline);
/**
* Sets a player's SilentChest setting.
*
* @param player the OfflinePlayer
* @param status the status
* @throws IllegalStateException if the server version is unsupported
*/
void setPlayerSilentChestStatus(OfflinePlayer player, boolean status);
/**
* Forcibly unload a cached Player's data.
*
* @param player the OfflinePlayer to unload
* @throws IllegalStateException if the server version is unsupported
*/
void unload(OfflinePlayer player);
Logger getLogger();
}
@@ -0,0 +1,74 @@
package com.lishid.openinv.event;
import com.lishid.openinv.internal.ISpecialInventory;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* Event fired before OpenInv saves a player's data.
*/
public class OpenPlayerSaveEvent extends Event implements Cancellable {
private static final HandlerList HANDLERS = new HandlerList();
private final Player player;
private final ISpecialInventory inventory;
private boolean cancelled = false;
public OpenPlayerSaveEvent(@NotNull Player player, @NotNull ISpecialInventory inventory) {
this.player = player;
this.inventory = inventory;
}
/**
* Get the {@link Player} whose data is being saved.
*
* @return player the Player whose data is being saved
*/
public @NotNull Player getPlayer() {
return player;
}
/**
* Get the {@link ISpecialInventory} that triggered the save by being closed.
*
* @return the special inventory
*/
public @NotNull ISpecialInventory getInventory() {
return inventory;
}
/**
* Get whether the event is cancelled.
*
* @return true if the event is cancelled
*/
@Override
public boolean isCancelled() {
return cancelled;
}
/**
* Set whether the event is cancelled.
*
* @param cancel whether the event is cancelled
*/
@Override
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
@NotNull
@Override
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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
@@ -16,45 +16,164 @@
package com.lishid.openinv.internal;
import org.bukkit.block.Barrel;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.EnderChest;
import org.bukkit.block.ShulkerBox;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Chest;
import org.bukkit.entity.Cat;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.util.BoundingBox;
import org.jetbrains.annotations.NotNull;
public interface IAnySilentContainer {
/**
* Opens the container at the given coordinates for the Player. If you do not want blocked
* containers to open, be sure to check {@link #isAnyContainerNeeded(Player, Block)}
* first.
* Forcibly open the container at the given coordinates for the Player. This will open blocked containers! Be sure
* to check {@link #isAnyContainerNeeded(Block)} first if that is not desirable.
*
* @param player the Player opening the container
* @param silentchest whether the container's noise is to be silenced
* @param block the Block
* @param player the {@link Player} opening the container
* @param silent whether the container's noise is to be silenced
* @param block the {@link Block} of the container
* @return true if the container can be opened
*/
boolean activateContainer(Player player, boolean silentchest, Block block);
boolean activateContainer(@NotNull Player player, boolean silent, @NotNull Block block);
/**
* Closes the Player's currently open container silently, if necessary.
* Perform operations required to close the current container silently.
*
* @param player the Player closing a container
* @param player the {@link Player} closing a container
*/
void deactivateContainer(Player player);
void deactivateContainer(@NotNull Player player);
/**
* Checks if the container at the given coordinates is blocked.
* @param player the player opening the container
* @param block the {@link Block} of the container
* @return true if the container is blocked
* @deprecated use {@link #isAnyContainerNeeded(Block)}
*/
@Deprecated(forRemoval = true, since = "4.1.9")
default boolean isAnyContainerNeeded(@NotNull Player player, @NotNull Block block) {
return isAnyContainerNeeded(block);
}
/**
* Check if the container at the given coordinates is blocked.
*
* @param player the Player opening the container
* @param block the Block
* @param block the {@link Block} of the container
* @return true if the container is blocked
*/
boolean isAnyContainerNeeded(Player player, Block block);
default boolean isAnyContainerNeeded(@NotNull Block block) {
BlockState blockState = block.getState();
// Barrels do not require AnyContainer.
if (blockState instanceof Barrel) {
return false;
}
// Enderchests require a non-occluding block on top to open.
if (blockState instanceof EnderChest) {
return block.getRelative(0, 1, 0).getType().isOccluding();
}
// Shulker boxes require 1/2 a block clear in the direction they open.
if (blockState instanceof ShulkerBox shulker) {
if (isShulkerBlocked(shulker)) {
return true;
}
}
if (!(blockState instanceof org.bukkit.block.Chest)) {
return false;
}
if (isChestBlocked(block)) {
return true;
}
BlockData blockData = block.getBlockData();
if (!(blockData instanceof Chest chest) || ((Chest) blockData).getType() == Chest.Type.SINGLE) {
return false;
}
int ordinal = (chest.getFacing().ordinal() + 4 + (chest.getType() == Chest.Type.RIGHT ? -1 : 1)) % 4;
BlockFace relativeFace = BlockFace.values()[ordinal];
org.bukkit.block.Block relative = block.getRelative(relativeFace);
if (relative.getType() != block.getType()) {
return false;
}
BlockData relativeData = relative.getBlockData();
if (!(relativeData instanceof Chest relativeChest)) {
return false;
}
if (relativeChest.getFacing() != chest.getFacing()
|| relativeChest.getType() != (chest.getType() == Chest.Type.RIGHT ? Chest.Type.LEFT : Chest.Type.RIGHT)) {
return false;
}
return isChestBlocked(relative);
}
/**
* Checks if the given block is a container which can be unblocked or silenced.
* Check if a {@link ShulkerBox} cannot be opened under ordinary circumstances.
*
* @param block the BlockState
* @return true if the Block is a supported container
* @param shulkerBox the shulker box container
* @return whether the container is blocked
*/
boolean isAnySilentContainer(Block block);
boolean isShulkerBlocked(@NotNull ShulkerBox shulkerBox);
/**
* Check if a chest cannot be opened under ordinary circumstances.
*
* @param chest the chest block
* @return whether the container is blocked
*/
default boolean isChestBlocked(@NotNull Block chest) {
org.bukkit.block.Block relative = chest.getRelative(0, 1, 0);
return relative.getType().isOccluding()
|| chest.getWorld().getNearbyEntities(BoundingBox.of(relative), entity -> entity instanceof Cat).size() > 0;
}
/**
* Check if the given {@link Block} is a container which can be unblocked or silenced.
*
* @param block the potential container
* @return true if the type is a supported container
*/
default boolean isAnySilentContainer(@NotNull Block block) {
return isAnySilentContainer(block.getState());
}
/**
* Check if the given {@link BlockState} is a container which can be unblocked or silenced.
*
* @param blockState the potential container
* @return true if the type is a supported container
*/
default boolean isAnySilentContainer(@NotNull BlockState blockState) {
return blockState instanceof InventoryHolder holder && isAnySilentContainer(holder)
|| blockState instanceof EnderChest;
}
/**
* Check if the given {@link InventoryHolder} is a container which can be unblocked or silenced.
*
* @param holder the potential container
* @return true if the type is a supported container
*/
default boolean isAnySilentContainer(@NotNull InventoryHolder holder) {
return holder instanceof org.bukkit.block.EnderChest
|| holder instanceof org.bukkit.block.Chest
|| holder instanceof org.bukkit.block.DoubleChest
|| holder instanceof org.bukkit.block.ShulkerBox
|| holder instanceof org.bukkit.block.Barrel;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
* Copyright (C) 2011-2022 lishid. All rights reserved.
*
* 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
@@ -16,46 +16,47 @@
package com.lishid.openinv.internal;
import javax.annotation.Nullable;
import com.lishid.openinv.util.InventoryAccess;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @deprecated Use static {@link InventoryAccess} methods.
*/
@Deprecated(forRemoval = true)
public interface IInventoryAccess {
/**
* Gets an ISpecialEnderChest from an Inventory or null if the Inventory is not backed by an
* ISpecialEnderChest.
*
* @param inventory the Inventory
* @return the ISpecialEnderChest or null
* @deprecated Use static {@link InventoryAccess} methods.
*/
@Nullable
ISpecialEnderChest getSpecialEnderChest(Inventory inventory);
@Deprecated(forRemoval = true)
default @Nullable ISpecialEnderChest getSpecialEnderChest(@NotNull Inventory inventory) {
return InventoryAccess.getEnderChest(inventory);
}
/**
* Gets an ISpecialPlayerInventory from an Inventory or null if the Inventory is not backed by
* an ISpecialPlayerInventory.
*
* @param inventory the Inventory
* @return the ISpecialPlayerInventory or null
* @deprecated Use static {@link InventoryAccess} methods.
*/
@Nullable
ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory);
@Deprecated(forRemoval = true)
default @Nullable ISpecialPlayerInventory getSpecialPlayerInventory(@NotNull Inventory inventory) {
return InventoryAccess.getPlayerInventory(inventory);
}
/**
* Check if an Inventory is an ISpecialEnderChest implementation.
*
* @param inventory the Inventory
* @return true if the Inventory is backed by an ISpecialEnderChest
* @deprecated Use static {@link InventoryAccess} methods.
*/
boolean isSpecialEnderChest(Inventory inventory);
@Deprecated(forRemoval = true)
default boolean isSpecialEnderChest(@NotNull Inventory inventory) {
return InventoryAccess.isEnderChest(inventory);
}
/**
* Check if an Inventory is an ISpecialPlayerInventory implementation.
*
* @param inventory the Inventory
* @return true if the Inventory is backed by an ISpecialPlayerInventory
* @deprecated Use static {@link InventoryAccess} methods.
*/
boolean isSpecialPlayerInventory(Inventory inventory);
@Deprecated(forRemoval = true)
default boolean isSpecialPlayerInventory(@NotNull Inventory inventory) {
return InventoryAccess.isPlayerInventory(inventory);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
* Copyright (C) 2011-2022 lishid. All rights reserved.
*
* 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
@@ -16,35 +16,9 @@
package com.lishid.openinv.internal;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public interface ISpecialEnderChest {
/**
* Gets the Inventory associated with this ISpecialEnderChest.
*
* @return the Inventory
*/
Inventory getBukkitInventory();
/**
* Sets the Player associated with this ISpecialEnderChest online.
*
* @param player the Player coming online
*/
void setPlayerOnline(Player player);
/**
* Sets the Player associated with this ISpecialEnderChest offline.
*/
void setPlayerOffline();
/**
* Gets whether or not this ISpecialEnderChest is in use.
*
* @return true if the ISpecialEnderChest is in use
*/
boolean isInUse();
/**
* An {@link ISpecialInventory} representing an ender chest.
*/
public interface ISpecialEnderChest extends ISpecialInventory {
}
@@ -0,0 +1,64 @@
/*
* Copyright (C) 2011-2022 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
/**
* Interface defining behavior for special inventories backed by other inventories' content listings.
*/
public interface ISpecialInventory {
/**
* Get the {@link Inventory} associated with this {@code ISpecialInventory}.
*
* @return the Bukkit inventory
*/
@NotNull Inventory getBukkitInventory();
/**
* Set the owning {@link Player} instance to a newly-joined user.
*
* @param player the user coming online
*/
void setPlayerOnline(@NotNull Player player);
/**
* Mark the owner of the inventory offline.
*/
void setPlayerOffline();
/**
* Get whether the inventory is being viewed by any users.
*
* @return true if the inventory is being viewed
*/
default boolean isInUse() {
return !getBukkitInventory().getViewers().isEmpty();
}
/**
* Get the {@link Player} who owns the inventory.
*
* @return the {@link HumanEntity} who owns the inventory
*/
@NotNull HumanEntity getPlayer();
}
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
* Copyright (C) 2011-2022 lishid. All rights reserved.
*
* 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
@@ -16,35 +16,35 @@
package com.lishid.openinv.internal;
import org.bukkit.entity.Player;
import java.util.List;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.Inventory;
public interface ISpecialPlayerInventory {
/**
* An {@link ISpecialInventory} representing a player inventory.
*/
public interface ISpecialPlayerInventory extends ISpecialInventory {
/**
* Gets the Inventory associated with this ISpecialPlayerInventory.
*
* @return the Inventory
/*
* Player inventory usage varies from all other inventories - as the inventory is technically open at all times,
* if the player is online or has been online while the inventory is open, they are in the viewer list.
*/
Inventory getBukkitInventory();
@Override
default boolean isInUse() {
Inventory inventory = getBukkitInventory();
List<HumanEntity> viewers = inventory.getViewers();
/**
* Sets the Player associated with this ISpecialPlayerInventory online.
*
* @param player the Player coming online
*/
void setPlayerOnline(Player player);
if (viewers.size() != 1) {
return !viewers.isEmpty();
}
/**
* Sets the Player associated with this ISpecialPlayerInventory offline.
*/
void setPlayerOffline();
HumanEntity viewer = viewers.get(0);
/**
* Gets whether or not this ISpecialPlayerInventory is in use.
*
* @return true if the ISpecialPlayerInventory is in use
*/
boolean isInUse();
if (!viewer.getUniqueId().equals(getPlayer().getUniqueId())) {
return true;
}
return viewer.getOpenInventory().getTopInventory().equals(inventory);
}
}
@@ -0,0 +1,123 @@
/*
* Copyright (C) 2011-2022 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class InventoryAccess implements IInventoryAccess {
private static Class<?> craftInventory = null;
private static Method getInventory = null;
static {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
try {
craftInventory = Class.forName(packageName + ".inventory.CraftInventory");
getInventory = craftInventory.getDeclaredMethod("getInventory");
} catch (ClassNotFoundException | NoSuchMethodException ignored) {}
}
/**
* @deprecated use {@link #isUsable()}
*/
@Deprecated(forRemoval = true)
public static boolean isUseable() {
return isUsable();
}
public static boolean isUsable() {
return craftInventory != null && getInventory != null;
}
/**
* Check if an {@link Inventory} is an {@link ISpecialPlayerInventory} implementation.
*
* @param inventory the Bukkit inventory
* @return true if backed by the correct implementation
*/
public static boolean isPlayerInventory(@NotNull Inventory inventory) {
return getPlayerInventory(inventory) != null;
}
/**
* Get the {@link ISpecialPlayerInventory} backing an {@link Inventory}. Returns {@code null} if the inventory is
* not backed by the correct class.
*
* @param inventory the Bukkit inventory
* @return the backing implementation if available
*/
public static @Nullable ISpecialPlayerInventory getPlayerInventory(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialPlayerInventory.class, inventory);
}
/**
* Check if an {@link Inventory} is an {@link ISpecialEnderChest} implementation.
*
* @param inventory the Bukkit inventory
* @return true if backed by the correct implementation
*/
public static boolean isEnderChest(@NotNull Inventory inventory) {
return getEnderChest(inventory) != null;
}
/**
* Get the {@link ISpecialEnderChest} backing an {@link Inventory}. Returns {@code null} if the inventory is
* not backed by the correct class.
*
* @param inventory the Bukkit inventory
* @return the backing implementation if available
*/
public static @Nullable ISpecialEnderChest getEnderChest(@NotNull Inventory inventory) {
return getSpecialInventory(ISpecialEnderChest.class, inventory);
}
private static <T extends ISpecialInventory> @Nullable T getSpecialInventory(@NotNull Class<T> expected, @NotNull Inventory inventory) {
Object inv;
if (isUsable() && craftInventory.isAssignableFrom(inventory.getClass())) {
try {
inv = getInventory.invoke(inventory);
if (expected.isInstance(inv)) {
return expected.cast(inv);
}
} catch (ReflectiveOperationException ignored) {}
}
// Use reflection to find the IInventory
inv = ReflectionHelper.grabObjectByType(inventory, expected);
if (expected.isInstance(inv)) {
return expected.cast(inv);
}
return null;
}
/**
* @deprecated Do not create a new instance to use static methods.
*/
@Deprecated(forRemoval = true, since = "4.2.0")
public InventoryAccess() {}
}
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2011-2021 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import java.lang.reflect.Field;
import org.jetbrains.annotations.Nullable;
/**
* A utility for making reflection easier.
*/
public final class ReflectionHelper {
private ReflectionHelper() {}
/**
* Grab an {@link Object} stored in a {@link Field} of another {@code Object}.
*
* <p>This casts the field to the correct class. Any issues will result in a {@code null} return value.
*
* @param fieldType the {@link Class} of {@code Object} stored in the {@code Field}
* @param holder the containing {@code Object}
* @param <T> the type of stored {@code Object}
* @return the first matching {@code Object} or {@code null} if none match
*/
public static <T> @Nullable T grabObjectByType(final Object holder, final Class<T> fieldType) {
Field field = grabFieldByType(holder.getClass(), fieldType);
if (field != null) {
try {
return fieldType.cast(field.get(holder));
} catch (IllegalAccessException ignored) {
// Ignore issues obtaining field
}
}
return null;
}
/**
* Grab a {@link Field} of an {@link Object}
*
* @param fieldType the {@link Class} of the object
* @param holderType the containing {@code Class}
* @return the first matching object or {@code null} if none match
*/
public static @Nullable Field grabFieldByType(Class<?> holderType, Class<?> fieldType) {
for (Field field : holderType.getDeclaredFields()) {
field.setAccessible(true);
if (fieldType.isAssignableFrom(field.getType())) {
return field;
}
}
if (holderType.getSuperclass() != null) {
return grabFieldByType(fieldType, holderType.getSuperclass());
}
return null;
}
}
@@ -0,0 +1,150 @@
/*
* Copyright (C) 2011-2021 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
public class StringMetric {
public static float compareJaroWinkler(String a, String b) {
final float jaroScore = compareJaro(a, b);
if (jaroScore < (float) 0.7) {
return jaroScore;
}
String prefix = commonPrefix(a, b);
int prefixLength = Math.min(prefix.codePointCount(0, prefix.length()), 4);
return jaroScore + (prefixLength * (float) 0.1 * (1.0f - jaroScore));
}
private static float compareJaro(String a, String b) {
if (a.isEmpty() && b.isEmpty()) {
return 1.0f;
}
if (a.isEmpty() || b.isEmpty()) {
return 0.0f;
}
final int[] charsA = a.codePoints().toArray();
final int[] charsB = b.codePoints().toArray();
// Intentional integer division to round down.
final int halfLength = Math.max(0, Math.max(charsA.length, charsB.length) / 2 - 1);
final int[] commonA = getCommonCodePoints(charsA, charsB, halfLength);
final int[] commonB = getCommonCodePoints(charsB, charsA, halfLength);
// commonA and commonB will always contain the same multi-set of
// characters. Because getCommonCharacters has been optimized, commonA
// and commonB are -1-padded. So in this loop we count transposition
// and use commonCharacters to determine the length of the multi-set.
float transpositions = 0;
int commonCharacters = 0;
for (int length = commonA.length; commonCharacters < length
&& commonA[commonCharacters] > -1; commonCharacters++) {
if (commonA[commonCharacters] != commonB[commonCharacters]) {
transpositions++;
}
}
if (commonCharacters == 0) {
return 0.0f;
}
float aCommonRatio = commonCharacters / (float) charsA.length;
float bCommonRatio = commonCharacters / (float) charsB.length;
float transpositionRatio = (commonCharacters - transpositions / 2.0f) / commonCharacters;
return (aCommonRatio + bCommonRatio + transpositionRatio) / 3.0f;
}
/*
* Returns an array of code points from a within b. A character in b is
* counted as common when it is within separation distance from the position
* in a.
*/
private static int[] getCommonCodePoints(final int[] charsA, final int[] charsB, final int separation) {
final int[] common = new int[Math.min(charsA.length, charsB.length)];
final boolean[] matched = new boolean[charsB.length];
// Iterate of string a and find all characters that occur in b within
// the separation distance. Mark any matches found to avoid
// duplicate matchings.
int commonIndex = 0;
for (int i = 0, length = charsA.length; i < length; i++) {
final int character = charsA[i];
final int index = indexOf(character, charsB, i - separation, i
+ separation + 1, matched);
if (index > -1) {
common[commonIndex++] = character;
matched[index] = true;
}
}
if (commonIndex < common.length) {
common[commonIndex] = -1;
}
// Both invocations will yield the same multi-set terminated by -1, so
// they can be compared for transposition without making a copy.
return common;
}
/*
* Search for code point in buffer starting at fromIndex to toIndex - 1.
*
* Returns -1 when not found.
*/
private static int indexOf(int character, int[] buffer, int fromIndex, int toIndex, boolean[] matched) {
// compare char with range of characters to either side
for (int j = Math.max(0, fromIndex), length = Math.min(toIndex, buffer.length); j < length; j++) {
// check if found
if (buffer[j] == character && !matched[j]) {
return j;
}
}
return -1;
}
private static String commonPrefix(CharSequence a, CharSequence b) {
int maxPrefixLength = Math.min(a.length(), b.length());
int p;
p = 0;
while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
++p;
}
if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
--p;
}
return a.subSequence(0, p).toString();
}
private static boolean validSurrogatePairAt(CharSequence string, int index) {
return index >= 0 && index <= string.length() - 2 && Character.isHighSurrogate(string.charAt(index)) && Character.isLowSurrogate(string.charAt(index + 1));
}
private StringMetric(){}
}
-58
View File
@@ -1,58 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvparent</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvassembly</artifactId>
<name>OpenInvAssembly</name>
<build>
<directory>../target</directory>
<finalName>OpenInv</finalName>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>reactor-uberjar</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/reactor-uberjar.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
<id>reactor-uberjar</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<moduleSets>
<moduleSet>
<useAllReactorProjects>true</useAllReactorProjects>
<binaries>
<outputDirectory>/</outputDirectory>
<unpack>true</unpack>
<!-- unpackOptions must be present or build breaks. -->
<unpackOptions/>
</binaries>
</moduleSet>
</moduleSets>
</assembly>
+102
View File
@@ -0,0 +1,102 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import io.papermc.paperweight.userdev.ReobfArtifactConfiguration
import io.papermc.paperweight.tasks.RemapJar
plugins {
java
`java-library`
id("com.gradleup.shadow") version "8.3.9"
id("io.papermc.paperweight.userdev") version "2.0.0-beta.18"
eclipse
}
group = "com.lishid"
version = "4.4.4-SNAPSHOT"
val apiVersion = "1.19"
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
vendor.set(JvmVendorSpec.GRAAL_VM)
}
}
paperweight.reobfArtifactConfiguration = ReobfArtifactConfiguration.REOBF_PRODUCTION
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
maven("https://repo.purpurmc.org/snapshots")
}
dependencies {
paperweight.paperDevBundle("1.19.4-R0.1-SNAPSHOT")
compileOnly("org.jetbrains:annotations:24.1.0")
compileOnly("org.purpurmc.purpur:purpur-api:1.19.4-R0.1-SNAPSHOT")
}
sourceSets {
main {
java.setSrcDirs(
listOf(
"api/src/main/java",
"plugin/src/main/java",
"internal/v1_19_R3/src/main/java",
),
)
resources.setSrcDirs(listOf("plugin/src/main/resources"))
}
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release.set(17)
options.compilerArgs.add("-parameters")
}
tasks.withType<AbstractArchiveTask>().configureEach {
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
archiveBaseName.set("OpenInv")
}
tasks.processResources {
val props = mapOf("version" to project.version, "apiVersion" to apiVersion)
inputs.properties(props)
filesMatching("plugin.yml") {
expand(props)
}
from("LICENSE.txt") {
into("/")
}
}
tasks.jar {
archiveClassifier.set("dev")
}
tasks.withType<ShadowJar>().configureEach {
archiveClassifier.set("dev-all")
minimize()
}
tasks.named("assemble") {
dependsOn(tasks.named("reobfJar"))
}
tasks.named("build") {
dependsOn(tasks.named("shadowJar"))
}
tasks.named<RemapJar>("reobfJar") {
outputJar.set(layout.buildDirectory.file("libs/OpenInv-${project.version}.jar"))
}
eclipse {
project {
name = rootProject.name
}
}
-45
View File
@@ -1,45 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvparent</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvcommon</artifactId>
<name>OpenInvCommon</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.5-R1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/../lib/bukkit-1.4.5-R1.0.jar</systemPath>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvapi</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,59 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal;
import java.util.Collection;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public interface IPlayerDataManager {
/**
* Loads a Player for an OfflinePlayer.
* </p>
* This method is potentially blocking, and should not be called on the main thread.
*
* @param offline the OfflinePlayer
* @return the Player loaded
*/
Player loadPlayer(OfflinePlayer offline);
/**
* Gets a unique identifying string for an OfflinePlayer.
*
* @param offline the OfflinePlayer
* @return the unique identifier
*/
String getPlayerDataID(OfflinePlayer offline);
/**
* Gets an OfflinePlayer by the given unique identifier.
*
* @param identifier the unique identifier
* @return the OfflinePlayer, or null if no exact match was found
*/
OfflinePlayer getPlayerByID(String identifier);
/**
* Gets a Collection of all Players currently online.
*
* @return the Collection of Players
*/
Collection<? extends Player> getOnlinePlayers();
}
@@ -1,196 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
/**
* A minimal thread-safe time-based cache implementation backed by a HashMap and TreeMultimap.
*
* @author Jikoo
*/
public class Cache<K, V> {
private final Map<K, V> internal;
private final Multimap<Long, K> expiry;
private final long retention;
private final Function<V> inUseCheck, postRemoval;
/**
* Constructs a Cache with the specified retention duration, in use function, and post-removal function.
*
* @param retention duration after which keys are automatically invalidated if not in use
* @param inUseCheck Function used to check if a key is considered in use
* @param postRemoval Function used to perform any operations required when a key is invalidated
*/
public Cache(final long retention, final Function<V> inUseCheck, final Function<V> postRemoval) {
this.internal = new HashMap<K, V>();
this.expiry = TreeMultimap.create(new Comparator<Long>() {
@Override
public int compare(final Long long1, final Long long2) {
return long1.compareTo(long2);
}
},
new Comparator<K>() {
@Override
public int compare(final K k1, final K k2) {
return k1 == k2 || k1 != null && k1.equals(k2) ? 0 : 1;
}
});
this.retention = retention;
this.inUseCheck = inUseCheck;
this.postRemoval = postRemoval;
}
/**
* Set a key and value pair. Keys are unique. Using an existing key will cause the old value to
* be overwritten and the expiration timer to be reset.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
*/
public void put(final K key, final V value) {
// Invalidate key - runs lazy check and ensures value won't be cleaned up early
this.invalidate(key);
synchronized (this.internal) {
this.internal.put(key, value);
this.expiry.put(System.currentTimeMillis() + this.retention, key);
}
}
/**
* Returns the value to which the specified key is mapped, or null if no value is mapped for the key.
*
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or null if no value is mapped for the key
*/
public V get(final K key) {
// Run lazy check to clean cache
this.lazyCheck();
synchronized (this.internal) {
return this.internal.get(key);
}
}
/**
* Returns true if the specified key is mapped to a value.
*
* @param key key to check if a mapping exists for
* @return true if a mapping exists for the specified key
*/
public boolean containsKey(final K key) {
// Run lazy check to clean cache
this.lazyCheck();
synchronized (this.internal) {
return this.internal.containsKey(key);
}
}
/**
* Forcibly invalidates a key, even if it is considered to be in use.
*
* @param key key to invalidate
*/
public void invalidate(final K key) {
// Run lazy check to clean cache
this.lazyCheck();
synchronized (this.internal) {
if (!this.internal.containsKey(key)) {
// Value either not present or cleaned by lazy check. Either way, we're good
return;
}
// Remove stored object
this.internal.remove(key);
// Remove expiration entry - prevents more work later, plus prevents issues with values invalidating early
for (Iterator<Map.Entry<Long, K>> iterator = this.expiry.entries().iterator(); iterator.hasNext();) {
if (key.equals(iterator.next().getValue())) {
iterator.remove();
break;
}
}
}
}
/**
* Forcibly invalidates all keys, even if they are considered to be in use.
*/
public void invalidateAll() {
synchronized (this.internal) {
for (V value : this.internal.values()) {
this.postRemoval.run(value);
}
this.expiry.clear();
this.internal.clear();
}
}
/**
* Invalidate all expired keys that are not considered in use. If a key is expired but is
* considered in use by the provided Function, its expiration time is reset.
*/
private void lazyCheck() {
long now = System.currentTimeMillis();
synchronized (this.internal) {
List<K> inUse = new ArrayList<K>();
for (Iterator<Map.Entry<Long, K>> iterator = this.expiry.entries().iterator(); iterator
.hasNext();) {
Map.Entry<Long, K> entry = iterator.next();
if (entry.getKey() > now) {
break;
}
iterator.remove();
if (this.inUseCheck.run(this.internal.get(entry.getValue()))) {
inUse.add(entry.getValue());
continue;
}
V value = this.internal.remove(entry.getValue());
if (value == null) {
continue;
}
this.postRemoval.run(value);
}
long nextExpiry = now + this.retention;
for (K value : inUse) {
this.expiry.put(nextExpiry, value);
}
}
}
}
@@ -1,65 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.util;
import org.bukkit.permissions.Permissible;
public enum Permissions {
OPENINV("openinv"),
OVERRIDE("override"),
EXEMPT("exempt"),
CROSSWORLD("crossworld"),
SILENT("silent"),
SILENT_DEFAULT("silent", "default"),
ANYCHEST("anychest"),
ANY_DEFAULT("any", "default"),
ENDERCHEST("openender"),
ENDERCHEST_ALL("openenderall"),
SEARCH("search"),
EDITINV("editinv"),
EDITENDER("editender"),
OPENSELF("openself");
private final String[] permission;
Permissions(String... permissions) {
this.permission = new String[permissions.length + 1];
this.permission[0] = "OpenInv";
System.arraycopy(permissions, 0, this.permission, 1, permissions.length);
}
public boolean hasPermission(Permissible permissible) {
StringBuilder permissionBuilder = new StringBuilder();
// Support wildcard nodes.
for (int i = 0; i < permission.length; i++) {
if (permissible.hasPermission(permissionBuilder.toString() + "*")) {
return true;
}
permissionBuilder.append(permission[i]).append('.');
}
// Delete trailing period.
if (permissionBuilder.length() > 0) {
permissionBuilder.deleteCharAt(permissionBuilder.length() - 1);
}
return permissible.hasPermission(permissionBuilder.toString());
}
}
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/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/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# 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
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
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.
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=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# 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" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and 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" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@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 ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
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
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
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=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_4_5</artifactId>
<name>OpenInvAdapter1_4_5</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.4.5-R1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,171 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_4_5.AxisAlignedBB;
import net.minecraft.server.v1_4_5.BlockEnderChest;
import net.minecraft.server.v1_4_5.Container;
import net.minecraft.server.v1_4_5.EntityOcelot;
import net.minecraft.server.v1_4_5.EntityPlayer;
import net.minecraft.server.v1_4_5.IInventory;
import net.minecraft.server.v1_4_5.InventoryEnderChest;
import net.minecraft.server.v1_4_5.InventoryLargeChest;
import net.minecraft.server.v1_4_5.Packet100OpenWindow;
import net.minecraft.server.v1_4_5.TileEntityChest;
import net.minecraft.server.v1_4_5.TileEntityEnderChest;
import net.minecraft.server.v1_4_5.World;
import org.bukkit.craftbukkit.v1_4_5.event.CraftEventFactory;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
IInventory inventory = (IInventory) tile;
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), inventory);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), inventory);
}
// AnyChest only
if (!silentchest) {
player.openContainer(inventory);
return true;
}
// SilentChest
try {
// Call InventoryOpenEvent
Container container = new SilentContainerChest(player.inventory, inventory);
container = CraftEventFactory.callInventoryOpenEvent(player, container);
if (container == null) {
return false;
}
// Open window
int windowId = player.nextContainerCounter();
player.netServerHandler.sendPacket(new Packet100OpenWindow(windowId, 0, inventory.getName(), inventory.getSize()));
player.activeContainer = container;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
return true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent container.");
return false;
}
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_4_5.IInventory;
import org.bukkit.craftbukkit.v1_4_5.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,101 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import java.util.Arrays;
import java.util.Collection;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_4_5.EntityPlayer;
import net.minecraft.server.v1_4_5.ItemInWorldManager;
import net.minecraft.server.v1_4_5.MinecraftServer;
import org.bukkit.craftbukkit.v1_4_5.CraftServer;
import org.bukkit.craftbukkit.v1_4_5.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new ItemInWorldManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Arrays.asList(Bukkit.getOnlinePlayers());
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().f(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import net.minecraft.server.v1_4_5.ContainerChest;
import net.minecraft.server.v1_4_5.EntityHuman;
import net.minecraft.server.v1_4_5.IInventory;
import net.minecraft.server.v1_4_5.ItemStack;
import net.minecraft.server.v1_4_5.PlayerInventory;
class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.f();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}
@@ -1,130 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import net.minecraft.server.v1_4_5.EntityPlayer;
import net.minecraft.server.v1_4_5.IInventory;
import net.minecraft.server.v1_4_5.InventoryEnderChest;
import net.minecraft.server.v1_4_5.InventorySubcontainer;
import net.minecraft.server.v1_4_5.ItemStack;
import org.bukkit.craftbukkit.v1_4_5.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_4_5.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_5.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player player, Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.owner = nmsPlayer.getBukkitEntity();
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.owner = nmsPlayer.getBukkitEntity();
InventoryEnderChest playerEnderChest = nmsPlayer.getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}
@@ -1,235 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_5;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_4_5.ItemStack;
import net.minecraft.server.v1_4_5.PlayerInventory;
import org.bukkit.craftbukkit.v1_4_5.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[5];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
this.items = player.inventory.items;
this.armor = player.inventory.armor;
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = PlayerDataManager.getHandle(player);
this.player.inventory.items = this.items;
this.player.inventory.armor = this.armor;
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 5;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
}
else {
itemstack = is[i].a(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
else {
return null;
}
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
else {
return null;
}
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
// Effects
if (is == this.extra) {
player.drop(itemstack);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27)
return i - 27;
else
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0)
return 3;
if (i == 1)
return 2;
if (i == 2)
return 1;
if (i == 3)
return 0;
else
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
}
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_4_6</artifactId>
<name>OpenInvAdapter1_4_6</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.4.6-R0.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,171 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_4_6.AxisAlignedBB;
import net.minecraft.server.v1_4_6.BlockEnderChest;
import net.minecraft.server.v1_4_6.Container;
import net.minecraft.server.v1_4_6.EntityOcelot;
import net.minecraft.server.v1_4_6.EntityPlayer;
import net.minecraft.server.v1_4_6.IInventory;
import net.minecraft.server.v1_4_6.InventoryEnderChest;
import net.minecraft.server.v1_4_6.InventoryLargeChest;
import net.minecraft.server.v1_4_6.Packet100OpenWindow;
import net.minecraft.server.v1_4_6.TileEntityChest;
import net.minecraft.server.v1_4_6.TileEntityEnderChest;
import net.minecraft.server.v1_4_6.World;
import org.bukkit.craftbukkit.v1_4_6.event.CraftEventFactory;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
IInventory inventory = (IInventory) tile;
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), inventory);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), inventory);
}
// AnyChest only
if (!silentchest) {
player.openContainer(inventory);
return true;
}
// SilentChest
try {
// Call InventoryOpenEvent
Container container = new SilentContainerChest(player.inventory, inventory);
container = CraftEventFactory.callInventoryOpenEvent(player, container);
if (container == null) {
return false;
}
// Open window
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new Packet100OpenWindow(windowId, 0, inventory.getName(), inventory.getSize()));
player.activeContainer = container;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
return true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent container.");
return false;
}
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_4_6.IInventory;
import org.bukkit.craftbukkit.v1_4_6.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,101 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import java.util.Arrays;
import java.util.Collection;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_4_6.EntityPlayer;
import net.minecraft.server.v1_4_6.MinecraftServer;
import net.minecraft.server.v1_4_6.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_4_6.CraftServer;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Arrays.asList(Bukkit.getOnlinePlayers());
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().f(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import net.minecraft.server.v1_4_6.ContainerChest;
import net.minecraft.server.v1_4_6.EntityHuman;
import net.minecraft.server.v1_4_6.IInventory;
import net.minecraft.server.v1_4_6.ItemStack;
import net.minecraft.server.v1_4_6.PlayerInventory;
class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.f();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}
@@ -1,130 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import net.minecraft.server.v1_4_6.EntityPlayer;
import net.minecraft.server.v1_4_6.IInventory;
import net.minecraft.server.v1_4_6.InventoryEnderChest;
import net.minecraft.server.v1_4_6.InventorySubcontainer;
import net.minecraft.server.v1_4_6.ItemStack;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_4_6.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_6.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player player, Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.owner = nmsPlayer.getBukkitEntity();
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.owner = nmsPlayer.getBukkitEntity();
InventoryEnderChest playerEnderChest = nmsPlayer.getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}
@@ -1,227 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_6;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_4_6.ItemStack;
import net.minecraft.server.v1_4_6.PlayerInventory;
import org.bukkit.craftbukkit.v1_4_6.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[5];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
this.items = player.inventory.items;
this.armor = player.inventory.armor;
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = PlayerDataManager.getHandle(player);
this.player.inventory.items = this.items;
this.player.inventory.armor = this.armor;
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 5;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
} else {
itemstack = is[i].a(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
return null;
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
return null;
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
// Effects
if (is == this.extra) {
player.drop(itemstack);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
}
-79
View File
@@ -1,79 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvparent</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvinternal</artifactId>
<name>OpenInvInternal</name>
<packaging>pom</packaging>
<profiles>
<profile>
<id>latest</id>
<modules>
<module>v1_12_R1</module>
</modules>
</profile>
<profile>
<id>recent</id>
<!-- The recent profile is for the most recent 2 versions. -->
<modules>
<module>v1_11_R1</module>
<module>v1_12_R1</module>
</modules>
</profile>
<profile>
<id>all</id>
<modules>
<module>1_4_5</module>
<module>1_4_6</module>
<module>v1_4_R1</module>
<!-- 1_5_R1 was never released -->
<module>v1_5_R2</module>
<module>v1_5_R3</module>
<!-- 1_6_R1 also had no tagged releases, remove? -->
<module>v1_6_R1</module>
<module>v1_6_R2</module>
<module>v1_6_R3</module>
<module>v1_7_R1</module>
<module>v1_7_R2</module>
<module>v1_7_R3</module>
<module>v1_7_R4</module>
<module>v1_8_R1</module>
<module>v1_8_R2</module>
<module>v1_8_R3</module>
<module>v1_9_R1</module>
<module>v1_9_R2</module>
<module>v1_10_R1</module>
<module>v1_11_R1</module>
<module>v1_12_R1</module>
</modules>
</profile>
</profiles>
</project>
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_10_R1</artifactId>
<name>OpenInvAdapter1_10_R1</name>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.10-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,250 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import java.lang.reflect.Field;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import net.minecraft.server.v1_10_R1.AxisAlignedBB;
import net.minecraft.server.v1_10_R1.Block;
import net.minecraft.server.v1_10_R1.BlockChest;
import net.minecraft.server.v1_10_R1.BlockEnderChest;
import net.minecraft.server.v1_10_R1.BlockPosition;
import net.minecraft.server.v1_10_R1.Entity;
import net.minecraft.server.v1_10_R1.EntityOcelot;
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.EnumDirection;
import net.minecraft.server.v1_10_R1.EnumGamemode;
import net.minecraft.server.v1_10_R1.ITileInventory;
import net.minecraft.server.v1_10_R1.InventoryEnderChest;
import net.minecraft.server.v1_10_R1.InventoryLargeChest;
import net.minecraft.server.v1_10_R1.PlayerInteractManager;
import net.minecraft.server.v1_10_R1.StatisticList;
import net.minecraft.server.v1_10_R1.TileEntity;
import net.minecraft.server.v1_10_R1.TileEntityChest;
import net.minecraft.server.v1_10_R1.TileEntityEnderChest;
import net.minecraft.server.v1_10_R1.World;
public class AnySilentContainer implements IAnySilentContainer {
private Field playerInteractManagerGamemode;
public AnySilentContainer() {
try {
this.playerInteractManagerGamemode = PlayerInteractManager.class.getDeclaredField("gamemode");
this.playerInteractManagerGamemode.setAccessible(true);
} catch (Exception e) {
System.err.println("[OpenInv] Unable to directly write player gamemode! SilentChest will fail.");
e.printStackTrace();
}
}
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block b) {
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
Block block = world.getType(blockPosition).getBlock();
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.getType(blockPosition.up()).m();
}
// Check if chest is blocked or has an ocelot on top
if (isBlockedChest(world, blockPosition)) {
return true;
}
// Check for matching adjacent chests that are blocked or have an ocelot on top
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if (isBlockedChest(world, localBlockPosition)) {
return true;
}
}
return false;
}
private boolean isBlockedChest(World world, BlockPosition blockPosition) {
// For reference, loot at net.minecraft.server.BlockChest
return world.getType(blockPosition.up()).l() || hasOcelotOnTop(world, blockPosition);
}
private boolean hasOcelotOnTop(World world, BlockPosition blockPosition) {
for (Entity localEntity : world.a(EntityOcelot.class,
new AxisAlignedBB(blockPosition.getX(), blockPosition.getY() + 1,
blockPosition.getZ(), blockPosition.getX() + 1, blockPosition.getY() + 2,
blockPosition.getZ() + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block b) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is pretty much API-only
if (silentchest && b.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
player.b(StatisticList.X);
return true;
}
World world = player.world;
BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
Object tile = world.getTileEntity(blockPosition);
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
player.b(StatisticList.X);
return true;
}
if (!(tile instanceof ITileInventory)) {
return false;
}
ITileInventory tileInventory = (ITileInventory) tile;
Block block = world.getType(blockPosition).getBlock();
if (block instanceof BlockChest) {
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if ((localEnumDirection == EnumDirection.WEST) || (localEnumDirection == EnumDirection.NORTH)) {
tileInventory = new InventoryLargeChest("container.chestDouble",
(TileEntityChest) localTileEntity, tileInventory);
} else {
tileInventory = new InventoryLargeChest("container.chestDouble",
tileInventory, (TileEntityChest) localTileEntity);
}
break;
}
BlockChest blockChest = (BlockChest) block;
if (blockChest.g == BlockChest.Type.BASIC) {
player.b(StatisticList.ac);
} else if (blockChest.g == BlockChest.Type.TRAP) {
player.b(StatisticList.W);
}
}
// AnyChest only - SilentChest not active, container unsupported, or unnecessary.
if (!silentchest || player.playerInteractManager.getGameMode() == EnumGamemode.SPECTATOR) {
player.openContainer(tileInventory);
return true;
}
// SilentChest requires access to setting players' gamemode directly.
if (this.playerInteractManagerGamemode == null) {
return false;
}
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.openContainer(tileInventory);
this.forceGameMode(player, gamemode);
return true;
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {
if (this.playerInteractManagerGamemode == null) {
return;
}
InventoryView view = bukkitPlayer.getOpenInventory();
switch (view.getType()) {
case CHEST:
case ENDER_CHEST:
break;
default:
return;
}
EntityPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.activeContainer.b(player);
player.activeContainer = player.defaultContainer;
this.forceGameMode(player, gamemode);
}
private void forceGameMode(final EntityPlayer player, final EnumGamemode gameMode) {
if (this.playerInteractManagerGamemode == null) {
// No need to warn repeatedly, error on startup and lack of function should be enough.
return;
}
try {
if (!this.playerInteractManagerGamemode.isAccessible()) {
// Just in case, ensure accessible.
this.playerInteractManagerGamemode.setAccessible(true);
}
this.playerInteractManagerGamemode.set(player.playerInteractManager, gameMode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_10_R1.IInventory;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,109 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import java.util.Collection;
import java.util.UUID;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.mojang.authlib.GameProfile;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.MinecraftServer;
import net.minecraft.server.v1_10_R1.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_10_R1.CraftServer;
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
// Create a profile and entity to load the player data
GameProfile profile = new GameProfile(offline.getUniqueId(), offline.getName());
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), profile,
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getUniqueId().toString();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
try {
UUID uuid = UUID.fromString(identifier);
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
} catch (IllegalArgumentException e) {
// Not a UUID
return null;
}
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Bukkit.getOnlinePlayers();
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,105 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.IInventory;
import net.minecraft.server.v1_10_R1.InventoryEnderChest;
import net.minecraft.server.v1_10_R1.InventorySubcontainer;
import net.minecraft.server.v1_10_R1.ItemStack;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialEnderChest(Player player, Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().hasCustomName(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.bukkitOwner = nmsPlayer.getBukkitEntity();
setItemArrays(this, enderChest.getContents());
}
private void setItemArrays(InventorySubcontainer subcontainer, ItemStack[] items) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = InventorySubcontainer.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(subcontainer, items);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.bukkitOwner = nmsPlayer.getBukkitEntity();
setItemArrays(nmsPlayer.getEnderChest(), this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public void update() {
super.update();
enderChest.update();
}
}
@@ -1,299 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_10_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_10_R1.EntityHuman;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.PlayerInventory;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[4];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
setItemArrays(this, player.inventory.items, player.inventory.armor, player.inventory.extraSlots);
}
private void setItemArrays(PlayerInventory inventory, ItemStack[] items, ItemStack[] armor,
ItemStack[] extraSlots) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = PlayerInventory.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, items);
// Access and replace armor inventory array
field = PlayerInventory.class.getField("armor");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, armor);
// Access and replace offhand inventory array
field = PlayerInventory.class.getField("extraSlots");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, extraSlots);
// Access and replace array containing all inventory arrays
field = PlayerInventory.class.getDeclaredField("g");
field.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, new ItemStack[][] { items, armor, extraSlots });
} catch (NoSuchFieldException e) {
// Unable to set final fields to item arrays, we're screwed. Noisily fail.
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = PlayerDataManager.getHandle(player);
setItemArrays(this.player.inventory, items, armor, extraSlots);
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
System.arraycopy(extraSlots, 0, contents, items.length + armor.length, extraSlots.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 4;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
// extraSlots is, for now, just an array with length 1. No need for special handling.
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
} else {
itemstack = is[i].cloneAndSubtract(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
return null;
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
return null;
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extraSlots;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
// Effects
if (is == this.extra) {
player.drop(itemstack, true);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
@Override
public boolean hasCustomName() {
return true;
}
@Override
public boolean a(EntityHuman entityhuman) {
return true;
}
}
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_11_R1</artifactId>
<name>OpenInvAdapter1_11_R1</name>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.11.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,295 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import java.lang.reflect.Field;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import net.minecraft.server.v1_11_R1.AxisAlignedBB;
import net.minecraft.server.v1_11_R1.Block;
import net.minecraft.server.v1_11_R1.BlockChest;
import net.minecraft.server.v1_11_R1.BlockEnderChest;
import net.minecraft.server.v1_11_R1.BlockPosition;
import net.minecraft.server.v1_11_R1.BlockShulkerBox;
import net.minecraft.server.v1_11_R1.Entity;
import net.minecraft.server.v1_11_R1.EntityOcelot;
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.EnumDirection;
import net.minecraft.server.v1_11_R1.IBlockData;
import net.minecraft.server.v1_11_R1.ITileInventory;
import net.minecraft.server.v1_11_R1.InventoryEnderChest;
import net.minecraft.server.v1_11_R1.InventoryLargeChest;
import net.minecraft.server.v1_11_R1.StatisticList;
import net.minecraft.server.v1_11_R1.TileEntity;
import net.minecraft.server.v1_11_R1.TileEntityChest;
import net.minecraft.server.v1_11_R1.TileEntityEnderChest;
import net.minecraft.server.v1_11_R1.TileEntityShulkerBox;
import net.minecraft.server.v1_11_R1.World;
import net.minecraft.server.v1_11_R1.EnumGamemode;
import net.minecraft.server.v1_11_R1.PlayerInteractManager;
public class AnySilentContainer implements IAnySilentContainer {
private Field playerInteractManagerGamemode;
public AnySilentContainer() {
try {
this.playerInteractManagerGamemode = PlayerInteractManager.class.getDeclaredField("gamemode");
this.playerInteractManagerGamemode.setAccessible(true);
} catch (Exception e) {
System.err.println("[OpenInv] Unable to directly write player gamemode! SilentChest will fail.");
e.printStackTrace();
}
}
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
if (block.getType() == Material.ENDER_CHEST) {
return true;
}
BlockState state = block.getState();
return state instanceof org.bukkit.block.Chest || state instanceof org.bukkit.block.ShulkerBox;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block b) {
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
IBlockData blockData = world.getType(blockPosition);
Block block = blockData.getBlock();
if (block instanceof BlockShulkerBox) {
return isBlockedShulkerBox(world, blockPosition, blockData);
}
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.getType(blockPosition.up()).m();
}
// Check if chest is blocked or has an ocelot on top
if (isBlockedChest(world, blockPosition)) {
return true;
}
// Check for matching adjacent chests that are blocked or have an ocelot on top
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if (isBlockedChest(world, localBlockPosition)) {
return true;
}
}
return false;
}
private boolean isBlockedShulkerBox(World world, BlockPosition blockPosition, IBlockData blockData) {
// For reference, look at net.minecraft.server.BlockShulkerBox
TileEntity tile = world.getTileEntity(blockPosition);
if (!(tile instanceof TileEntityShulkerBox)) {
return false;
}
EnumDirection enumDirection = blockData.get(BlockShulkerBox.a);
if (((TileEntityShulkerBox) tile).p() == TileEntityShulkerBox.AnimationPhase.CLOSED) {
AxisAlignedBB axisAlignedBB = Block.j.b(0.5F * enumDirection.getAdjacentX(),
0.5F * enumDirection.getAdjacentY(), 0.5F * enumDirection.getAdjacentZ())
.a(enumDirection.getAdjacentX(), enumDirection.getAdjacentY(),
enumDirection.getAdjacentZ());
try {
// 1.11.2
return world.a(axisAlignedBB.a(blockPosition.shift(enumDirection)));
} catch (NoSuchMethodError e) {
// 1.11
return world.b(axisAlignedBB.a(blockPosition.shift(enumDirection)));
}
}
return false;
}
private boolean isBlockedChest(World world, BlockPosition blockPosition) {
// For reference, loot at net.minecraft.server.BlockChest
return world.getType(blockPosition.up()).m() || hasOcelotOnTop(world, blockPosition);
}
private boolean hasOcelotOnTop(World world, BlockPosition blockPosition) {
for (Entity localEntity : world.a(EntityOcelot.class,
new AxisAlignedBB(blockPosition.getX(), blockPosition.getY() + 1,
blockPosition.getZ(), blockPosition.getX() + 1, blockPosition.getY() + 2,
blockPosition.getZ() + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block b) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is pretty much API-only
if (silentchest && b.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
player.b(StatisticList.getStatistic("stat.enderchestOpened"));
return true;
}
final World world = player.world;
final BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
final Object tile = world.getTileEntity(blockPosition);
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
player.b(StatisticList.getStatistic("stat.enderchestOpened"));
return true;
}
if (!(tile instanceof ITileInventory)) {
return false;
}
ITileInventory tileInventory = (ITileInventory) tile;
Block block = world.getType(blockPosition).getBlock();
if (block instanceof BlockChest) {
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if ((localEnumDirection == EnumDirection.WEST) || (localEnumDirection == EnumDirection.NORTH)) {
tileInventory = new InventoryLargeChest("container.chestDouble",
(TileEntityChest) localTileEntity, tileInventory);
} else {
tileInventory = new InventoryLargeChest("container.chestDouble",
tileInventory, (TileEntityChest) localTileEntity);
}
break;
}
BlockChest blockChest = (BlockChest) block;
if (blockChest.g == BlockChest.Type.BASIC) {
player.b(StatisticList.getStatistic("stat.chestOpened"));
} else if (blockChest.g == BlockChest.Type.TRAP) {
player.b(StatisticList.getStatistic("stat.trappedChestTriggered"));
}
}
if (block instanceof BlockShulkerBox) {
player.b(StatisticList.getStatistic("stat.shulkerBoxOpened"));
}
// AnyChest only - SilentChest not active, container unsupported, or unnecessary.
if (!silentchest || player.playerInteractManager.getGameMode() == EnumGamemode.SPECTATOR) {
player.openContainer(tileInventory);
return true;
}
// SilentChest requires access to setting players' gamemode directly.
if (this.playerInteractManagerGamemode == null) {
return false;
}
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.openContainer(tileInventory);
this.forceGameMode(player, gamemode);
return true;
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {
if (this.playerInteractManagerGamemode == null) {
return;
}
InventoryView view = bukkitPlayer.getOpenInventory();
switch (view.getType()) {
case CHEST:
case ENDER_CHEST:
case SHULKER_BOX:
break;
default:
return;
}
EntityPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.activeContainer.b(player);
player.activeContainer = player.defaultContainer;
this.forceGameMode(player, gamemode);
}
private void forceGameMode(final EntityPlayer player, final EnumGamemode gameMode) {
if (this.playerInteractManagerGamemode == null) {
// No need to warn repeatedly, error on startup and lack of function should be enough.
return;
}
try {
if (!this.playerInteractManagerGamemode.isAccessible()) {
// Just in case, ensure accessible.
this.playerInteractManagerGamemode.setAccessible(true);
}
this.playerInteractManagerGamemode.set(player.playerInteractManager, gameMode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_11_R1.IInventory;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,109 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import java.util.Collection;
import java.util.UUID;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.mojang.authlib.GameProfile;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.MinecraftServer;
import net.minecraft.server.v1_11_R1.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_11_R1.CraftServer;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
// Create a profile and entity to load the player data
GameProfile profile = new GameProfile(offline.getUniqueId(), offline.getName());
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), profile,
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getUniqueId().toString();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
try {
UUID uuid = UUID.fromString(identifier);
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
} catch (IllegalArgumentException e) {
// Not a UUID
return null;
}
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Bukkit.getOnlinePlayers();
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,106 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.IInventory;
import net.minecraft.server.v1_11_R1.InventoryEnderChest;
import net.minecraft.server.v1_11_R1.InventorySubcontainer;
import net.minecraft.server.v1_11_R1.ItemStack;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialEnderChest(Player player, Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().hasCustomName(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.bukkitOwner = nmsPlayer.getBukkitEntity();
setItemLists(this, enderChest.getContents());
}
private void setItemLists(InventorySubcontainer subcontainer, List<ItemStack> list) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = InventorySubcontainer.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(subcontainer, list);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.bukkitOwner = nmsPlayer.getBukkitEntity();
setItemLists(nmsPlayer.getEnderChest(), this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public void update() {
super.update();
enderChest.update();
}
}
@@ -1,262 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_11_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_11_R1.ContainerUtil;
import net.minecraft.server.v1_11_R1.EntityHuman;
import net.minecraft.server.v1_11_R1.ItemStack;
import net.minecraft.server.v1_11_R1.NonNullList;
import net.minecraft.server.v1_11_R1.PlayerInventory;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
setItemArrays(this, player.inventory.items, player.inventory.armor, player.inventory.extraSlots);
}
private void setItemArrays(PlayerInventory inventory, NonNullList<ItemStack> items,
NonNullList<ItemStack> armor, NonNullList<ItemStack> extraSlots) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = PlayerInventory.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, items);
// Access and replace armor inventory array
field = PlayerInventory.class.getField("armor");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, armor);
// Access and replace offhand inventory array
field = PlayerInventory.class.getField("extraSlots");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, extraSlots);
// Access and replace array containing all inventory arrays
field = PlayerInventory.class.getDeclaredField("g");
field.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, Arrays.asList(items, armor, extraSlots));
} catch (NoSuchFieldException e) {
// Unable to set final fields to item arrays, we're screwed. Noisily fail.
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = PlayerDataManager.getHandle(player);
setItemArrays(this.player.inventory, items, armor, extraSlots);
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public int getSize() {
return super.getSize() + 4;
}
@Override
public ItemStack getItem(int i) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
return list.get(i);
}
@Override
public ItemStack splitStack(int i, int j) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
return list.get(i).isEmpty() ? ItemStack.a : ContainerUtil.a(list, i, j);
}
@Override
public ItemStack splitWithoutUpdate(int i) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
if (!list.get(i).isEmpty()) {
ItemStack itemstack = list.get(i);
list.set(i, ItemStack.a);
return itemstack;
}
return ItemStack.a;
}
@Override
public void setItem(int i, ItemStack itemstack) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
player.drop(itemstack, true);
return;
}
list.set(i, itemstack);
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
@Override
public boolean hasCustomName() {
return true;
}
@Override
public boolean a(EntityHuman entityhuman) {
return true;
}
}
-57
View File
@@ -1,57 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_12_R1</artifactId>
<name>OpenInvAdapter1_12_R1</name>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.12-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -1,293 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_12_R1;
import java.lang.reflect.Field;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import net.minecraft.server.v1_12_R1.AxisAlignedBB;
import net.minecraft.server.v1_12_R1.Block;
import net.minecraft.server.v1_12_R1.BlockChest;
import net.minecraft.server.v1_12_R1.BlockEnderChest;
import net.minecraft.server.v1_12_R1.BlockPosition;
import net.minecraft.server.v1_12_R1.BlockShulkerBox;
import net.minecraft.server.v1_12_R1.Entity;
import net.minecraft.server.v1_12_R1.EntityOcelot;
import net.minecraft.server.v1_12_R1.EntityPlayer;
import net.minecraft.server.v1_12_R1.EnumDirection;
import net.minecraft.server.v1_12_R1.EnumGamemode;
import net.minecraft.server.v1_12_R1.IBlockData;
import net.minecraft.server.v1_12_R1.ITileInventory;
import net.minecraft.server.v1_12_R1.InventoryEnderChest;
import net.minecraft.server.v1_12_R1.InventoryLargeChest;
import net.minecraft.server.v1_12_R1.PlayerInteractManager;
import net.minecraft.server.v1_12_R1.TileEntity;
import net.minecraft.server.v1_12_R1.TileEntityChest;
import net.minecraft.server.v1_12_R1.TileEntityEnderChest;
import net.minecraft.server.v1_12_R1.TileEntityShulkerBox;
import net.minecraft.server.v1_12_R1.World;
public class AnySilentContainer implements IAnySilentContainer {
private Field playerInteractManagerGamemode;
public AnySilentContainer() {
try {
this.playerInteractManagerGamemode = PlayerInteractManager.class.getDeclaredField("gamemode");
this.playerInteractManagerGamemode.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
System.err.println("[OpenInv] Unable to directly write player gamemode! SilentChest will fail.");
e.printStackTrace();
}
}
@Override
public boolean isAnySilentContainer(final org.bukkit.block.Block block) {
if (block.getType() == Material.ENDER_CHEST) {
return true;
}
BlockState state = block.getState();
return state instanceof org.bukkit.block.Chest
|| state instanceof org.bukkit.block.ShulkerBox;
}
@Override
public boolean isAnyContainerNeeded(final Player p, final org.bukkit.block.Block b) {
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
BlockPosition blockPosition = new BlockPosition(b.getX(), b.getY(), b.getZ());
IBlockData blockData = world.getType(blockPosition);
Block block = blockData.getBlock();
if (block instanceof BlockShulkerBox) {
return this.isBlockedShulkerBox(world, blockPosition, blockData);
}
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.getType(blockPosition.up()).m();
}
// Check if chest is blocked or has an ocelot on top
if (this.isBlockedChest(world, blockPosition)) {
return true;
}
// Check for matching adjacent chests that are blocked or have an ocelot on top
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if (this.isBlockedChest(world, localBlockPosition)) {
return true;
}
}
return false;
}
private boolean isBlockedShulkerBox(final World world, final BlockPosition blockPosition,
final IBlockData blockData) {
// For reference, look at net.minecraft.server.BlockShulkerBox
TileEntity tile = world.getTileEntity(blockPosition);
if (!(tile instanceof TileEntityShulkerBox)) {
return false;
}
EnumDirection enumDirection = blockData.get(BlockShulkerBox.a);
if (((TileEntityShulkerBox) tile).p() == TileEntityShulkerBox.AnimationPhase.CLOSED) {
AxisAlignedBB axisAlignedBB = Block.j.b(0.5F * enumDirection.getAdjacentX(),
0.5F * enumDirection.getAdjacentY(), 0.5F * enumDirection.getAdjacentZ())
.a(enumDirection.getAdjacentX(), enumDirection.getAdjacentY(),
enumDirection.getAdjacentZ());
return world.a(axisAlignedBB.a(blockPosition.shift(enumDirection)));
}
return false;
}
private boolean isBlockedChest(final World world, final BlockPosition blockPosition) {
// For reference, loot at net.minecraft.server.BlockChest
return world.getType(blockPosition.up()).l() || this.hasOcelotOnTop(world, blockPosition);
}
private boolean hasOcelotOnTop(final World world, final BlockPosition blockPosition) {
for (Entity localEntity : world.a(EntityOcelot.class,
new AxisAlignedBB(blockPosition.getX(), blockPosition.getY() + 1,
blockPosition.getZ(), blockPosition.getX() + 1, blockPosition.getY() + 2,
blockPosition.getZ() + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(final Player bukkitPlayer, final boolean silentchest,
final org.bukkit.block.Block bukkitBlock) {
// Silent ender chest is API-only
if (silentchest && bukkitBlock.getType() == Material.ENDER_CHEST) {
bukkitPlayer.openInventory(bukkitPlayer.getEnderChest());
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
EntityPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
final World world = player.world;
final BlockPosition blockPosition = new BlockPosition(bukkitBlock.getX(), bukkitBlock.getY(), bukkitBlock.getZ());
final Object tile = world.getTileEntity(blockPosition);
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
if (!(tile instanceof ITileInventory)) {
return false;
}
ITileInventory tileInventory = (ITileInventory) tile;
Block block = world.getType(blockPosition).getBlock();
if (block instanceof BlockChest) {
for (EnumDirection localEnumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) {
BlockPosition localBlockPosition = blockPosition.shift(localEnumDirection);
Block localBlock = world.getType(localBlockPosition).getBlock();
if (localBlock != block) {
continue;
}
TileEntity localTileEntity = world.getTileEntity(localBlockPosition);
if (!(localTileEntity instanceof TileEntityChest)) {
continue;
}
if (localEnumDirection == EnumDirection.WEST
|| localEnumDirection == EnumDirection.NORTH) {
tileInventory = new InventoryLargeChest("container.chestDouble",
(TileEntityChest) localTileEntity, tileInventory);
} else {
tileInventory = new InventoryLargeChest("container.chestDouble", tileInventory,
(TileEntityChest) localTileEntity);
}
break;
}
BlockChest blockChest = (BlockChest) block;
if (blockChest.g == BlockChest.Type.BASIC) {
bukkitPlayer.incrementStatistic(Statistic.CHEST_OPENED);
} else if (blockChest.g == BlockChest.Type.TRAP) {
bukkitPlayer.incrementStatistic(Statistic.TRAPPED_CHEST_TRIGGERED);
}
}
if (block instanceof BlockShulkerBox) {
bukkitPlayer.incrementStatistic(Statistic.SHULKER_BOX_OPENED);
}
// AnyChest only - SilentChest not active, container unsupported, or unnecessary.
if (!silentchest || player.playerInteractManager.getGameMode() == EnumGamemode.SPECTATOR) {
player.openContainer(tileInventory);
return true;
}
// SilentChest requires access to setting players' gamemode directly.
if (this.playerInteractManagerGamemode == null) {
return false;
}
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.openContainer(tileInventory);
this.forceGameMode(player, gamemode);
return true;
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {
if (this.playerInteractManagerGamemode == null) {
return;
}
InventoryView view = bukkitPlayer.getOpenInventory();
switch (view.getType()) {
case CHEST:
case ENDER_CHEST:
case SHULKER_BOX:
break;
default:
return;
}
EntityPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
EnumGamemode gamemode = player.playerInteractManager.getGameMode();
this.forceGameMode(player, EnumGamemode.SPECTATOR);
player.activeContainer.b(player);
player.activeContainer = player.defaultContainer;
this.forceGameMode(player, gamemode);
}
private void forceGameMode(final EntityPlayer player, final EnumGamemode gameMode) {
if (this.playerInteractManagerGamemode == null) {
// No need to warn repeatedly, error on startup and lack of function should be enough.
return;
}
try {
if (!this.playerInteractManagerGamemode.isAccessible()) {
// Just in case, ensure accessible.
this.playerInteractManagerGamemode.setAccessible(true);
}
this.playerInteractManagerGamemode.set(player.playerInteractManager, gameMode);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
@@ -1,80 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_12_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_12_R1.IInventory;
import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public ISpecialEnderChest getSpecialEnderChest(final Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(final Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(final Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class,
inventory) instanceof ISpecialEnderChest;
}
@Override
public boolean isSpecialPlayerInventory(final Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class,
inventory) instanceof ISpecialPlayerInventory;
}
}
@@ -1,110 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_12_R1;
import java.util.Collection;
import java.util.UUID;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.mojang.authlib.GameProfile;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_12_R1.EntityPlayer;
import net.minecraft.server.v1_12_R1.MinecraftServer;
import net.minecraft.server.v1_12_R1.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_12_R1.CraftServer;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
public static EntityPlayer getHandle(final Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException(
"Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Bukkit.getOnlinePlayers();
}
@Override
public OfflinePlayer getPlayerByID(final String identifier) {
try {
UUID uuid = UUID.fromString(identifier);
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
} catch (IllegalArgumentException e) {
// Not a UUID
return null;
}
}
@Override
public String getPlayerDataID(final OfflinePlayer offline) {
return offline.getUniqueId().toString();
}
@Override
public Player loadPlayer(final OfflinePlayer offline) {
// Ensure player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
// Create a profile and entity to load the player data
GameProfile profile = new GameProfile(offline.getUniqueId(), offline.getName());
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), profile,
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = entity == null ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
}
@@ -1,103 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_12_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_12_R1.EntityPlayer;
import net.minecraft.server.v1_12_R1.IInventory;
import net.minecraft.server.v1_12_R1.InventoryEnderChest;
import net.minecraft.server.v1_12_R1.InventorySubcontainer;
import net.minecraft.server.v1_12_R1.ItemStack;
import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer
implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialEnderChest(final Player player, final Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().hasCustomName(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.bukkitOwner = nmsPlayer.getBukkitEntity();
this.setItemLists(this, this.enderChest.getContents());
}
@Override
public Inventory getBukkitInventory() {
return this.inventory;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
private void setItemLists(final InventorySubcontainer subcontainer,
final List<ItemStack> list) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory array
Field field = InventorySubcontainer.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(subcontainer, list);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public void setPlayerOnline(final Player player) {
if (!this.playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.bukkitOwner = nmsPlayer.getBukkitEntity();
this.setItemLists(nmsPlayer.getEnderChest(), this.items);
} catch (Exception e) {}
this.playerOnline = true;
}
}
@Override
public void update() {
super.update();
this.enderChest.update();
}
}
@@ -1,259 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_12_R1;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_12_R1.ContainerUtil;
import net.minecraft.server.v1_12_R1.EntityHuman;
import net.minecraft.server.v1_12_R1.ItemStack;
import net.minecraft.server.v1_12_R1.NonNullList;
import net.minecraft.server.v1_12_R1.PlayerInventory;
import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(final Player bukkitPlayer, final Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
this.setItemArrays(this, this.player.inventory.items, this.player.inventory.armor,
this.player.inventory.extraSlots);
}
@Override
public boolean a(final EntityHuman entityhuman) {
return true;
}
@Override
public Inventory getBukkitInventory() {
return this.inventory;
}
@Override
public ItemStack getItem(int i) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
return list.get(i);
}
@Override
public String getName() {
if (this.player.getName().length() > 16) {
return this.player.getName().substring(0, 16);
}
return this.player.getName();
}
@Override
public boolean hasCustomName() {
return true;
}
private int getReversedArmorSlotNum(final int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
private int getReversedItemSlotNum(final int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
@Override
public int getSize() {
return super.getSize() + 4;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public void setItem(int i, final ItemStack itemstack) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
this.player.drop(itemstack, true);
return;
}
list.set(i, itemstack);
}
private void setItemArrays(final PlayerInventory inventory, final NonNullList<ItemStack> items,
final NonNullList<ItemStack> armor, final NonNullList<ItemStack> extraSlots) {
try {
// Prepare to remove final modifier
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
// Access and replace main inventory list
Field field = PlayerInventory.class.getField("items");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, items);
// Access and replace armor inventory list
field = PlayerInventory.class.getField("armor");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, armor);
// Access and replace offhand inventory list
field = PlayerInventory.class.getField("extraSlots");
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, extraSlots);
// Access and replace list containing all inventory lists
field = PlayerInventory.class.getDeclaredField("f");
field.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(inventory, Arrays.asList(items, armor, extraSlots));
} catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
// Unable to set final fields to item lists, we're screwed. Noisily fail.
e.printStackTrace();
}
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public void setPlayerOnline(final Player player) {
if (!this.playerOnline) {
this.player = PlayerDataManager.getHandle(player);
this.setItemArrays(this.player.inventory, this.items, this.armor, this.extraSlots);
this.playerOnline = true;
}
}
@Override
public ItemStack splitStack(int i, final int j) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
return list.get(i).isEmpty() ? ItemStack.a : ContainerUtil.a(list, i, j);
}
@Override
public ItemStack splitWithoutUpdate(int i) {
NonNullList<ItemStack> list = this.items;
if (i >= list.size()) {
i -= list.size();
list = this.armor;
} else {
i = this.getReversedItemSlotNum(i);
}
if (i >= list.size()) {
i -= list.size();
list = this.extraSlots;
} else if (list == this.armor) {
i = this.getReversedArmorSlotNum(i);
}
if (i >= list.size()) {
return ItemStack.a;
}
if (!list.get(i).isEmpty()) {
ItemStack itemstack = list.get(i);
list.set(i, ItemStack.a);
return itemstack;
}
return ItemStack.a;
}
}
@@ -0,0 +1,244 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_19_R3;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.util.ReflectionHelper;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.ServerPlayerGameMode;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.SimpleMenuProvider;
import net.minecraft.world.entity.monster.Shulker;
import net.minecraft.world.inventory.ChestMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.block.BarrelBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ChestBlock;
import net.minecraft.world.level.block.ShulkerBoxBlock;
import net.minecraft.world.level.block.TrappedChestBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity;
import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.block.ShulkerBox;
import org.bukkit.craftbukkit.v1_19_R3.CraftWorld;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class AnySilentContainer implements IAnySilentContainer {
private @Nullable Field serverPlayerGameModeGameType;
public AnySilentContainer() {
try {
try {
this.serverPlayerGameModeGameType = ServerPlayerGameMode.class.getDeclaredField("b");
this.serverPlayerGameModeGameType.setAccessible(true);
} catch (NoSuchFieldException e) {
Logger logger = OpenInv.getPlugin(OpenInv.class).getLogger();
logger.warning("ServerPlayerGameMode#gameModeForPlayer's obfuscated name has changed!");
logger.warning("Please report this at https://github.com/Jikoo/OpenInv/issues");
logger.warning("Attempting to fall through using reflection. Please verify that SilentContainer does not fail.");
// N.B. gameModeForPlayer is (for now) declared before previousGameModeForPlayer so silent shouldn't break.
this.serverPlayerGameModeGameType = ReflectionHelper.grabFieldByType(ServerPlayerGameMode.class, GameType.class);
}
} catch (SecurityException e) {
Logger logger = OpenInv.getPlugin(OpenInv.class).getLogger();
logger.warning("Unable to directly write player game mode! SilentContainer will fail.");
logger.log(Level.WARNING, "Error obtaining GameType field", e);
}
}
@Override
public boolean isShulkerBlocked(@NotNull ShulkerBox shulkerBox) {
org.bukkit.World bukkitWorld = shulkerBox.getWorld();
if (!(bukkitWorld instanceof CraftWorld)) {
bukkitWorld = Bukkit.getWorld(bukkitWorld.getUID());
}
if (!(bukkitWorld instanceof CraftWorld craftWorld)) {
Exception exception = new IllegalStateException("AnySilentContainer access attempted on an unknown world!");
OpenInv.getPlugin(OpenInv.class).getLogger().log(Level.WARNING, exception.getMessage(), exception);
return false;
}
final ServerLevel world = craftWorld.getHandle();
final BlockPos blockPosition = new BlockPos(shulkerBox.getX(), shulkerBox.getY(), shulkerBox.getZ());
final BlockEntity tile = world.getBlockEntity(blockPosition);
if (!(tile instanceof ShulkerBoxBlockEntity shulkerBoxBlockEntity)
|| shulkerBoxBlockEntity.getAnimationStatus() != ShulkerBoxBlockEntity.AnimationStatus.CLOSED) {
return false;
}
BlockState blockState = world.getBlockState(blockPosition);
// See net.minecraft.world.level.block.ShulkerBoxBlock#canOpen
AABB boundingBox = Shulker.getProgressDeltaAabb(blockState.getValue(ShulkerBoxBlock.FACING), 0.0F, 0.5F)
.move(blockPosition)
.deflate(1.0E-6D);
return !world.noCollision(boundingBox);
}
@Override
public boolean activateContainer(
@NotNull final Player bukkitPlayer,
final boolean silentchest,
@NotNull final org.bukkit.block.Block bukkitBlock) {
// Silent ender chest is API-only
if (silentchest && bukkitBlock.getType() == Material.ENDER_CHEST) {
bukkitPlayer.openInventory(bukkitPlayer.getEnderChest());
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
ServerPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
final ServerLevel level = player.getLevel();
final BlockPos blockPos = new BlockPos(bukkitBlock.getX(), bukkitBlock.getY(), bukkitBlock.getZ());
final BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity == null) {
return false;
}
if (blockEntity instanceof EnderChestBlockEntity enderChestTile) {
// Anychest ender chest. See net.minecraft.world.level.block.EnderChestBlock
PlayerEnderChestContainer enderChest = player.getEnderChestInventory();
enderChest.setActiveChest(enderChestTile);
player.openMenu(new SimpleMenuProvider((containerCounter, playerInventory, ignored) -> {
MenuType<?> containers = PlayerDataManager.getContainers(enderChest.getContainerSize());
int rows = enderChest.getContainerSize() / 9;
return new ChestMenu(containers, containerCounter, playerInventory, enderChest, rows);
}, Component.translatable(("container.enderchest"))));
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
if (!(blockEntity instanceof MenuProvider menuProvider)) {
return false;
}
BlockState blockState = level.getBlockState(blockPos);
Block block = blockState.getBlock();
if (block instanceof ChestBlock chestBlock) {
// boolean flag: do not check if chest is blocked
menuProvider = chestBlock.getMenuProvider(blockState, level, blockPos, true);
if (menuProvider == null) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
if (block instanceof TrappedChestBlock) {
bukkitPlayer.incrementStatistic(Statistic.TRAPPED_CHEST_TRIGGERED);
} else {
bukkitPlayer.incrementStatistic(Statistic.CHEST_OPENED);
}
}
if (block instanceof ShulkerBoxBlock) {
bukkitPlayer.incrementStatistic(Statistic.SHULKER_BOX_OPENED);
}
if (block instanceof BarrelBlock) {
bukkitPlayer.incrementStatistic(Statistic.OPEN_BARREL);
}
// AnyChest only - SilentChest not active, container unsupported, or unnecessary.
if (!silentchest || player.gameMode.getGameModeForPlayer() == GameType.SPECTATOR) {
player.openMenu(menuProvider);
return true;
}
// SilentChest requires access to setting players' game mode directly.
if (this.serverPlayerGameModeGameType == null) {
return false;
}
if (blockEntity instanceof RandomizableContainerBlockEntity lootable) {
if (lootable.lootTable != null) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
}
GameType gameType = player.gameMode.getGameModeForPlayer();
this.forceGameType(player, GameType.SPECTATOR);
player.openMenu(menuProvider);
this.forceGameType(player, gameType);
return true;
}
@Override
public void deactivateContainer(@NotNull final Player bukkitPlayer) {
if (this.serverPlayerGameModeGameType == null || bukkitPlayer.getGameMode() == GameMode.SPECTATOR) {
return;
}
ServerPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
// Force game mode change without informing plugins or players.
// Regular game mode set calls GameModeChangeEvent and is cancellable.
GameType gameType = player.gameMode.getGameModeForPlayer();
this.forceGameType(player, GameType.SPECTATOR);
// ServerPlayer#closeContainer cannot be called without entering an
// infinite loop because this method is called during inventory close.
// From ServerPlayer#closeContainer -> CraftEventFactory#handleInventoryCloseEvent
player.containerMenu.transferTo(player.inventoryMenu, player.getBukkitEntity());
// From ServerPlayer#closeContainer
player.doCloseContainer();
// Regular inventory close will handle the rest - packet sending, etc.
// Revert forced game mode.
this.forceGameType(player, gameType);
}
private void forceGameType(final ServerPlayer player, final GameType gameMode) {
if (this.serverPlayerGameModeGameType == null) {
// No need to warn repeatedly, error on startup and lack of function should be enough.
return;
}
try {
this.serverPlayerGameModeGameType.setAccessible(true);
this.serverPlayerGameModeGameType.set(player.gameMode, gameMode);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,271 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_19_R3;
import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.NumericTag;
import net.minecraft.nbt.Tag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.storage.PlayerDataStorage;
import org.apache.logging.log4j.LogManager;
import org.bukkit.craftbukkit.v1_19_R3.CraftServer;
import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
public class OpenPlayer extends CraftPlayer {
private static final Set<String> RESET_TAGS = Set.of(
// net.minecraft.world.Entity#saveWithoutId(CompoundTag)
"CustomName",
"CustomNameVisible",
"Silent",
"NoGravity",
"Glowing",
"TicksFrozen",
"HasVisualFire",
"Tags",
"Passengers",
// net.minecraft.server.level.ServerPlayer#addAdditionalSaveData(CompoundTag)
// Intentional omissions to prevent mount loss: Attach, Entity, and RootVehicle
"warden_spawn_tracker",
"enteredNetherPosition",
"SpawnX",
"SpawnY",
"SpawnZ",
"SpawnForced",
"SpawnAngle",
"SpawnDimension",
// net.minecraft.world.entity.player.Player#addAdditionalSaveData(CompoundTag)
"ShoulderEntityLeft",
"ShoulderEntityRight",
"LastDeathLocation",
// net.minecraft.world.entity.LivingEntity#addAdditionalSaveData(CompoundTag)
"ActiveEffects",
"SleepingX",
"SleepingY",
"SleepingZ",
"Brain"
);
public OpenPlayer(CraftServer server, ServerPlayer entity) {
super(server, entity);
}
@Override
public void loadData() {
// See CraftPlayer#loadData
ServerPlayer serverPlayer = getHandle();
// The server's own storage, never the hookable PlayerList.playerIo, so an offline edit always targets the main profile
CompoundTag loaded = this.server.getServer().playerDataStorage.load(serverPlayer);
if (loaded != null) {
serverPlayer.readAdditionalSaveData(loaded);
serverPlayer.loadGameTypes(loaded);
}
}
@Override
public void saveData() {
ServerPlayer player = this.getHandle();
// An offline save is a read-modify-write of the stored profile: hold the Utilities-OG player lock that MyWorlds and
// DiamondBank hold for theirs, so the two never interleave (no lock without that plugin, nothing else writes then)
boolean offline = !isOnline();
if (offline) {
UtilitiesLock.lock(player.getUUID());
}
// See net.minecraft.world.level.storage.PlayerDataStorage#save(EntityHuman)
try {
PlayerDataStorage worldNBTStorage = player.server.playerDataStorage;
// Read without applying: load(Player) would push the stored inventory back over the edit being saved
CompoundTag oldData = offline ? readStoredTag(worldNBTStorage, player) : null;
CompoundTag playerData = getWritableTag(oldData);
playerData = player.saveWithoutId(playerData);
setExtraData(playerData);
if (oldData != null) {
// Revert certain special data values when offline.
revertSpecialValues(playerData, oldData);
}
if (saveThroughStorageApi(worldNBTStorage, player.getUUID(), playerData)) {
return;
}
File file = File.createTempFile(player.getStringUUID() + "-", ".dat", worldNBTStorage.getPlayerDir());
NbtIo.writeCompressed(playerData, file);
File file1 = new File(worldNBTStorage.getPlayerDir(), player.getStringUUID() + ".dat");
File file2 = new File(worldNBTStorage.getPlayerDir(), player.getStringUUID() + ".dat_old");
Util.safeReplaceFile(file1, file, file2);
} catch (Exception e) {
LogManager.getLogger().warn("Failed to save player data for {}: {}", player.getScoreboardName(), e);
} finally {
if (offline) {
UtilitiesLock.unlock(player.getUUID());
}
}
}
// Utilities-OG's per player lock, reached by reflection so OpenInv needs no compile dependency on it
private static final class UtilitiesLock {
private static final Method LOCK;
private static final Method UNLOCK;
static {
Method lock = null;
Method unlock = null;
try {
Class<?> utilities = Class.forName("net.trueog.utilitiesog.UtilitiesOG", true, OpenPlayer.class.getClassLoader());
lock = utilities.getMethod("lockPlayerData", UUID.class);
unlock = utilities.getMethod("unlockPlayerData", UUID.class);
} catch (ReflectiveOperationException e) {
// Utilities-OG is not installed, offline edits are unsynchronized like on vanilla
}
LOCK = lock;
UNLOCK = unlock;
}
static void lock(UUID uuid) {
invoke(LOCK, uuid);
}
static void unlock(UUID uuid) {
invoke(UNLOCK, uuid);
}
private static void invoke(@Nullable Method method, UUID uuid) {
if (method == null) {
return;
}
try {
method.invoke(null, uuid);
} catch (ReflectiveOperationException e) {
LogManager.getLogger().warn("Utilities-OG player data lock failed for {}", uuid, e);
}
}
}
// A storage with saveCompoundTag(UUID, CompoundTag) keeps profiles in a database (TrueOG Purpur); its getPlayerData(UUID) never touches the entity
private static @Nullable Method storageSave(@NotNull PlayerDataStorage storage) {
try {
return storage.getClass().getMethod("saveCompoundTag", UUID.class, CompoundTag.class);
} catch (NoSuchMethodException e) {
return null;
}
}
private static @Nullable CompoundTag readStoredTag(@NotNull PlayerDataStorage storage, @NotNull ServerPlayer player) throws ReflectiveOperationException {
if (storageSave(storage) != null) {
Method get = storage.getClass().getMethod("getPlayerData", UUID.class);
return (CompoundTag) get.invoke(storage, player.getUUID());
}
// CraftBukkit's file read, which does not apply the data to the entity
Method getPlayerData = storage.getClass().getMethod("getPlayerData", String.class);
return (CompoundTag) getPlayerData.invoke(storage, player.getStringUUID());
}
// True when the storage took the profile itself (it logs a failed write); false means the caller keeps the file layout
private static boolean saveThroughStorageApi(@NotNull PlayerDataStorage storage, @NotNull UUID uuid, @NotNull CompoundTag playerData) throws ReflectiveOperationException {
Method save = storageSave(storage);
if (save == null) {
return false;
}
save.invoke(storage, uuid, playerData);
return true;
}
@Contract("null -> new")
private @NotNull CompoundTag getWritableTag(@Nullable CompoundTag oldData) {
if (oldData == null) {
return new CompoundTag();
}
// Copy old data. This is a deep clone, so operating on it should be safe.
oldData = oldData.copy();
// Remove vanilla/server data that is not written every time.
oldData.getAllKeys().removeIf(key -> RESET_TAGS.contains(key) || key.startsWith("Bukkit"));
return oldData;
}
private void revertSpecialValues(@NotNull CompoundTag newData, @NotNull CompoundTag oldData) {
// Revert automatic updates to play timestamps.
copyValue(oldData, newData, "bukkit", "lastPlayed", NumericTag.class);
copyValue(oldData, newData, "Paper", "LastSeen", NumericTag.class);
copyValue(oldData, newData, "Paper", "LastLogin", NumericTag.class);
// The persistent data container was captured when the inventory was opened; other plugins (MyWorlds nests its
// per-world profiles there) may have changed the stored one since, and this edit never touches it
Tag storedValues = oldData.get("BukkitValues");
if (storedValues != null) {
newData.put("BukkitValues", storedValues.copy());
} else {
newData.remove("BukkitValues");
}
}
private <T extends Tag> void copyValue(
@NotNull CompoundTag source,
@NotNull CompoundTag target,
@NotNull String container,
@NotNull String key,
@NotNull Class<T> tagType) {
CompoundTag oldContainer = getTag(source, container, CompoundTag.class);
CompoundTag newContainer = getTag(target, container, CompoundTag.class);
// New container being null means the server implementation doesn't store this data.
if (newContainer == null) {
return;
}
// If old tag exists, copy it to new location, removing otherwise.
setTag(newContainer, key, getTag(oldContainer, key, tagType));
}
private <T extends Tag> @Nullable T getTag(
@Nullable CompoundTag container,
@NotNull String key,
@NotNull Class<T> dataType) {
if (container == null) {
return null;
}
Tag value = container.get(key);
if (value == null || !dataType.isAssignableFrom(value.getClass())) {
return null;
}
return dataType.cast(value);
}
private <T extends Tag> void setTag(
@NotNull CompoundTag container,
@NotNull String key,
@Nullable T data) {
if (data == null) {
container.remove(key);
} else {
container.put(key, data);
}
}
}
@@ -0,0 +1,274 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_19_R3;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.OpenInventoryView;
import com.mojang.authlib.GameProfile;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.craftbukkit.v1_19_R3.CraftServer;
import org.bukkit.craftbukkit.v1_19_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_19_R3.event.CraftEventFactory;
import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftContainer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.logging.Logger;
public class PlayerDataManager implements IPlayerDataManager {
private @Nullable Field bukkitEntity;
public PlayerDataManager() {
try {
bukkitEntity = Entity.class.getDeclaredField("bukkitEntity");
} catch (NoSuchFieldException e) {
Logger logger = OpenInv.getPlugin(OpenInv.class).getLogger();
logger.warning("Unable to obtain field to inject custom save process - players' mounts may be deleted when loaded.");
logger.log(java.util.logging.Level.WARNING, e.getMessage(), e);
bukkitEntity = null;
}
}
public static @NotNull ServerPlayer getHandle(final Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
ServerPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getUniqueId());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
@Override
public @Nullable Player loadPlayer(@NotNull final OfflinePlayer offline) {
// Ensure player has data
if (!offline.hasPlayedBefore()) {
return null;
}
// Create a profile and entity to load the player data
// See net.minecraft.server.players.PlayerList#canPlayerLogin
// and net.minecraft.server.network.ServerLoginPacketListenerImpl#handleHello
GameProfile profile = new GameProfile(offline.getUniqueId(),
offline.getName() != null ? offline.getName() : offline.getUniqueId().toString());
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
ServerLevel worldServer = server.getLevel(Level.OVERWORLD);
if (worldServer == null) {
return null;
}
ServerPlayer entity = new ServerPlayer(server, worldServer, profile);
// Stop listening for advancement progression - if this is not cleaned up, loading causes a memory leak.
entity.getAdvancements().stopListening();
try {
injectPlayer(entity);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// Load data. This also reads basic data into the player.
// See CraftPlayer#loadData
// The server's own storage, not PlayerList.playerIo: a world manager may hook that field and answer with a per-world profile, and an offline edit always means the main profile.
CompoundTag loadedData = server.playerDataStorage.load(entity);
if (loadedData == null) {
// Exceptions with loading are logged by Mojang.
return null;
}
// A stored tag without a position is no profile, only data other plugins keep for a player who never joined
// (a MyWorlds inventory group, for example); editing it would turn it into a profile placed at 0,0,0.
if (!loadedData.contains("Pos", Tag.TAG_LIST)) {
return null;
}
// Also read "extra" data.
entity.readAdditionalSaveData(loadedData);
entity.loadGameTypes(loadedData);
if (entity.level == null) {
// Paper: Move player to spawn
// SPIGOT-7340: Cannot call ServerPlayer#spawnIn with a null world
ServerLevel level = null;
Vec3 position = null;
if (entity.getRespawnDimension() != null) {
level = entity.server.getLevel(entity.getRespawnDimension());
if (level != null && entity.getRespawnPosition() != null) {
position = net.minecraft.world.entity.player.Player.findRespawnPositionAndUseSpawnBlock(level, entity.getRespawnPosition(), entity.getRespawnAngle(), false, false).orElse(null);
}
}
if (level == null || position == null) {
level = ((CraftWorld) server.server.getWorlds().get(0)).getHandle();
position = Vec3.atCenterOf(level.getSharedSpawnPos());
}
entity.level = level;
entity.setPos(position);
}
// Return the Bukkit entity.
return entity.getBukkitEntity();
}
void injectPlayer(ServerPlayer player) throws IllegalAccessException {
if (bukkitEntity == null) {
return;
}
bukkitEntity.setAccessible(true);
bukkitEntity.set(player, new OpenPlayer(player.server.server, player));
}
@NotNull
@Override
public Player inject(@NotNull Player player) {
try {
ServerPlayer nmsPlayer = getHandle(player);
if (nmsPlayer.getBukkitEntity() instanceof OpenPlayer openPlayer) {
return openPlayer;
}
injectPlayer(nmsPlayer);
return nmsPlayer.getBukkitEntity();
} catch (IllegalAccessException e) {
e.printStackTrace();
return player;
}
}
@Nullable
@Override
public InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) {
ServerPlayer nmsPlayer = getHandle(player);
if (nmsPlayer.connection == null) {
return null;
}
InventoryView view = getView(player, inventory);
if (view == null) {
return player.openInventory(inventory.getBukkitInventory());
}
AbstractContainerMenu container = new CraftContainer(view, nmsPlayer, nmsPlayer.nextContainerCounter()) {
@Override
public MenuType<?> getType() {
return getContainers(inventory.getBukkitInventory().getSize());
}
};
container.setTitle(Component.literal(view.getTitle()));
container = CraftEventFactory.callInventoryOpenEvent(nmsPlayer, container);
if (container == null) {
return null;
}
nmsPlayer.connection.send(new ClientboundOpenScreenPacket(container.containerId, container.getType(),
Component.literal(container.getBukkitView().getTitle())));
nmsPlayer.containerMenu = container;
nmsPlayer.initMenu(container);
return container.getBukkitView();
}
private @Nullable InventoryView getView(Player player, ISpecialInventory inventory) {
if (inventory instanceof SpecialEnderChest) {
return new OpenInventoryView(player, inventory, "container.enderchest", "'s Ender Chest");
} else if (inventory instanceof SpecialPlayerInventory) {
return new OpenInventoryView(player, inventory, "container.player", "'s Inventory");
} else {
return null;
}
}
static @NotNull MenuType<?> getContainers(int inventorySize) {
return switch (inventorySize) {
case 9 -> MenuType.GENERIC_9x1;
case 18 -> MenuType.GENERIC_9x2;
case 36 -> MenuType.GENERIC_9x4; // PLAYER
case 41, 45 -> MenuType.GENERIC_9x5;
case 54 -> MenuType.GENERIC_9x6;
default -> MenuType.GENERIC_9x3; // Default 27-slot inventory
};
}
@Override
public int convertToPlayerSlot(InventoryView view, int rawSlot) {
int topSize = view.getTopInventory().getSize();
if (topSize <= rawSlot) {
// Slot is not inside special inventory, use Bukkit logic.
return view.convertSlot(rawSlot);
}
// Main inventory, slots 0-26 -> 9-35
if (rawSlot < 27) {
return rawSlot + 9;
}
// Hotbar, slots 27-35 -> 0-8
if (rawSlot < 36) {
return rawSlot - 27;
}
// Armor, slots 36-39 -> 39-36
if (rawSlot < 40) {
return 36 + (39 - rawSlot);
}
// Off hand
if (rawSlot == 40) {
return 40;
}
// Drop slots, "out of inventory"
return -1;
}
}
@@ -0,0 +1,350 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_19_R3;
import com.lishid.openinv.internal.ISpecialEnderChest;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.ContainerListener;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_19_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SpecialEnderChest extends PlayerEnderChestContainer implements ISpecialEnderChest {
private final CraftInventory inventory;
private ServerPlayer owner;
private NonNullList<ItemStack> items;
private boolean playerOnline;
public SpecialEnderChest(final org.bukkit.entity.Player player, final Boolean online) {
super(PlayerDataManager.getHandle(player));
this.inventory = new CraftInventory(this);
this.owner = PlayerDataManager.getHandle(player);
this.playerOnline = online;
this.items = this.owner.getEnderChestInventory().items;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public void setPlayerOnline(@NotNull final org.bukkit.entity.Player player) {
if (this.playerOnline) {
return;
}
ServerPlayer offlinePlayer = this.owner;
ServerPlayer onlinePlayer = PlayerDataManager.getHandle(player);
// Set owner to new player.
this.owner = onlinePlayer;
// Set player's ender chest contents to our modified contents.
PlayerEnderChestContainer onlineEnderChest = onlinePlayer.getEnderChestInventory();
for (int i = 0; i < onlineEnderChest.getContainerSize(); ++i) {
onlineEnderChest.setItem(i, this.items.get(i));
}
// Set our item array to the new inventory's array.
this.items = onlineEnderChest.items;
// Add viewers to new inventory.
onlineEnderChest.transaction.addAll(offlinePlayer.getEnderChestInventory().transaction);
this.playerOnline = true;
}
@Override
public @NotNull org.bukkit.entity.Player getPlayer() {
return owner.getBukkitEntity();
}
@Override
public void setChanged() {
this.owner.getEnderChestInventory().setChanged();
}
@Override
public List<ItemStack> getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.owner.getEnderChestInventory().onOpen(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.owner.getEnderChestInventory().onClose(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.owner.getEnderChestInventory().getViewers();
}
@Override
public boolean stillValid(Player player) {
return true;
}
@Override
public void setActiveChest(EnderChestBlockEntity enderChest) {
this.owner.getEnderChestInventory().setActiveChest(enderChest);
}
@Override
public boolean isActiveChest(EnderChestBlockEntity enderChest) {
return this.owner.getEnderChestInventory().isActiveChest(enderChest);
}
@Override
public int getMaxStackSize() {
return this.owner.getEnderChestInventory().getMaxStackSize();
}
@Override
public void setMaxStackSize(int i) {
this.owner.getEnderChestInventory().setMaxStackSize(i);
}
@Override
public InventoryHolder getOwner() {
return this.owner.getEnderChestInventory().getOwner();
}
@Override
public @Nullable Location getLocation() {
return null;
}
@Override
public void addListener(ContainerListener listener) {
this.owner.getEnderChestInventory().addListener(listener);
}
@Override
public void removeListener(ContainerListener listener) {
this.owner.getEnderChestInventory().removeListener(listener);
}
@Override
public ItemStack getItem(int i) {
return i >= 0 && i < this.items.size() ? this.items.get(i) : ItemStack.EMPTY;
}
@Override
public ItemStack removeItem(int i, int j) {
ItemStack itemstack = ContainerHelper.removeItem(this.items, i, j);
if (!itemstack.isEmpty()) {
this.setChanged();
}
return itemstack;
}
@Override
public ItemStack addItem(ItemStack itemstack) {
ItemStack localItem = itemstack.copy();
this.moveItemToOccupiedSlotsWithSameType(localItem);
if (localItem.isEmpty()) {
return ItemStack.EMPTY;
} else {
this.moveItemToEmptySlots(localItem);
return localItem.isEmpty() ? ItemStack.EMPTY : localItem;
}
}
@Override
public boolean canAddItem(ItemStack itemstack) {
for (ItemStack itemstack1 : this.items) {
if (itemstack1.isEmpty() || ItemStack.isSameItemSameTags(itemstack1, itemstack) && itemstack1.getCount() < itemstack1.getMaxStackSize()) {
return true;
}
}
return false;
}
private void moveItemToEmptySlots(ItemStack itemstack) {
for(int i = 0; i < this.getContainerSize(); ++i) {
ItemStack localItem = this.getItem(i);
if (localItem.isEmpty()) {
this.setItem(i, itemstack.copy());
itemstack.setCount(0);
return;
}
}
}
private void moveItemToOccupiedSlotsWithSameType(ItemStack itemstack) {
for(int i = 0; i < this.getContainerSize(); ++i) {
ItemStack localItem = this.getItem(i);
if (ItemStack.isSameItemSameTags(localItem, itemstack)) {
this.moveItemsBetweenStacks(itemstack, localItem);
if (itemstack.isEmpty()) {
return;
}
}
}
}
private void moveItemsBetweenStacks(ItemStack itemstack, ItemStack itemstack1) {
int i = Math.min(this.getMaxStackSize(), itemstack1.getMaxStackSize());
int j = Math.min(itemstack.getCount(), i - itemstack1.getCount());
if (j > 0) {
itemstack1.grow(j);
itemstack.shrink(j);
this.setChanged();
}
}
@Override
public ItemStack removeItemNoUpdate(int i) {
ItemStack itemstack = this.items.get(i);
if (itemstack.isEmpty()) {
return ItemStack.EMPTY;
} else {
this.items.set(i, ItemStack.EMPTY);
return itemstack;
}
}
@Override
public void setItem(int i, ItemStack itemstack) {
this.items.set(i, itemstack);
if (!itemstack.isEmpty() && itemstack.getCount() > this.getMaxStackSize()) {
itemstack.setCount(this.getMaxStackSize());
}
this.setChanged();
}
@Override
public int getContainerSize() {
return this.owner.getEnderChestInventory().getContainerSize();
}
@Override
public boolean isEmpty() {
return this.items.stream().allMatch(ItemStack::isEmpty);
}
@Override
public void startOpen(Player player) {
}
@Override
public void stopOpen(Player player) {
}
@Override
public boolean canPlaceItem(int i, ItemStack itemstack) {
return true;
}
@Override
public void clearContent() {
this.items.clear();
this.setChanged();
}
@Override
public void fillStackedContents(StackedContents stackedContents) {
for (ItemStack itemstack : this.items) {
stackedContents.accountStack(itemstack);
}
}
@Override
public List<ItemStack> removeAllItems() {
List<ItemStack> list = this.items.stream().filter(Predicate.not(ItemStack::isEmpty)).collect(Collectors.toList());
this.clearContent();
return list;
}
@Override
public ItemStack removeItemType(Item item, int i) {
ItemStack itemstack = new ItemStack(item, 0);
for(int j = this.getContainerSize() - 1; j >= 0; --j) {
ItemStack localItem = this.getItem(j);
if (localItem.getItem().equals(item)) {
int k = i - itemstack.getCount();
ItemStack splitItem = localItem.split(k);
itemstack.grow(splitItem.getCount());
if (itemstack.getCount() == i) {
break;
}
}
}
if (!itemstack.isEmpty()) {
this.setChanged();
}
return itemstack;
}
@Override
public String toString() {
return this.items.stream().filter((itemStack) -> !itemStack.isEmpty()).toList().toString();
}
@Override
public void fromTag(ListTag listTag) {
for (int i = 0; i < this.getContainerSize(); ++i) {
this.setItem(i, ItemStack.EMPTY);
}
for (int i = 0; i < listTag.size(); ++i) {
CompoundTag compoundTag = listTag.getCompound(i);
int j = compoundTag.getByte("Slot") & 255;
if (j < this.getContainerSize()) {
this.setItem(j, ItemStack.of(compoundTag));
}
}
}
}
@@ -0,0 +1,806 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_19_R3;
import com.google.common.collect.ImmutableList;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.minecraft.CrashReport;
import net.minecraft.CrashReportCategory;
import net.minecraft.ReportedException;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.DamageTypeTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.Container;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_19_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SpecialPlayerInventory extends Inventory implements ISpecialPlayerInventory {
private final CraftInventory inventory;
private boolean playerOnline;
private Player player;
private NonNullList<ItemStack> items;
private NonNullList<ItemStack> armor;
private NonNullList<ItemStack> offhand;
private List<NonNullList<ItemStack>> compartments;
public SpecialPlayerInventory(@NotNull org.bukkit.entity.Player bukkitPlayer, @NotNull Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.inventory = new CraftInventory(this);
this.playerOnline = online;
this.player = super.player;
this.selected = player.getInventory().selected;
this.items = this.player.getInventory().items;
this.armor = this.player.getInventory().armor;
this.offhand = this.player.getInventory().offhand;
this.compartments = ImmutableList.of(this.items, this.armor, this.offhand);
}
@Override
public void setPlayerOnline(@NotNull org.bukkit.entity.Player player) {
if (this.playerOnline) {
return;
}
Player offlinePlayer = this.player;
Player onlinePlayer = PlayerDataManager.getHandle(player);
onlinePlayer.getInventory().transaction.addAll(this.transaction);
// Set owner to new player.
this.player = onlinePlayer;
// Set player's inventory contents to our modified contents.
Inventory onlineInventory = onlinePlayer.getInventory();
for (int i = 0; i < getContainerSize(); ++i) {
onlineInventory.setItem(i, getRawItem(i));
}
onlineInventory.selected = this.selected;
// Set our item arrays to the new inventory's arrays.
this.items = onlineInventory.items;
this.armor = onlineInventory.armor;
this.offhand = onlineInventory.offhand;
this.compartments = ImmutableList.of(this.items, this.armor, this.offhand);
// Add existing viewers to new viewer list.
Inventory offlineInventory = offlinePlayer.getInventory();
// Remove self from listing - player is always a viewer of their own inventory, prevent duplicates.
offlineInventory.transaction.remove(offlinePlayer.getBukkitEntity());
onlineInventory.transaction.addAll(offlineInventory.transaction);
this.playerOnline = true;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return this.inventory;
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public @NotNull HumanEntity getPlayer() {
return this.player.getBukkitEntity();
}
private @NotNull ItemStack getRawItem(int i) {
if (i < 0) {
return ItemStack.EMPTY;
}
NonNullList<ItemStack> list;
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
list = iterator.next();
if (i < list.size()) {
return list.get(i);
}
}
return ItemStack.EMPTY;
}
private void setRawItem(int i, @NotNull ItemStack itemStack) {
if (i < 0) {
return;
}
NonNullList<ItemStack> list;
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
list = iterator.next();
if (i < list.size()) {
list.set(i, itemStack);
}
}
}
private record IndexedCompartment(@Nullable NonNullList<ItemStack> compartment, int index) {}
private @NotNull SpecialPlayerInventory.IndexedCompartment getIndexedContent(int index) {
if (index < items.size()) {
return new IndexedCompartment(items, getReversedItemSlotNum(index));
}
index -= items.size();
if (index < armor.size()) {
return new IndexedCompartment(armor, getReversedArmorSlotNum(index));
}
index -= armor.size();
if (index < offhand.size()) {
return new IndexedCompartment(offhand, index);
}
index -= offhand.size();
return new IndexedCompartment(null, index);
}
private int getReversedArmorSlotNum(final int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
private int getReversedItemSlotNum(final int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private boolean contains(Predicate<ItemStack> predicate) {
return this.compartments.stream().flatMap(NonNullList::stream).anyMatch(predicate);
}
@Override
public List<ItemStack> getArmorContents() {
return this.armor;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.player.getInventory().onOpen(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.player.getInventory().onClose(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.player.getInventory().getViewers();
}
@Override
public InventoryHolder getOwner() {
return this.player.getBukkitEntity();
}
@Override
public int getMaxStackSize() {
return this.player.getInventory().getMaxStackSize();
}
@Override
public void setMaxStackSize(int size) {
this.player.getInventory().setMaxStackSize(size);
}
@Override
public Location getLocation() {
return this.player.getBukkitEntity().getLocation();
}
@Override
public boolean hasCustomName() {
return false;
}
@Override
public List<ItemStack> getContents() {
return this.compartments.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
@Override
public ItemStack getSelected() {
return isHotbarSlot(this.selected) ? this.items.get(this.selected) : ItemStack.EMPTY;
}
private boolean hasRemainingSpaceForItem(ItemStack itemstack, ItemStack itemstack1) {
return !itemstack.isEmpty() && ItemStack.isSameItemSameTags(itemstack, itemstack1) && itemstack.isStackable() && itemstack.getCount() < itemstack.getMaxStackSize() && itemstack.getCount() < this.getMaxStackSize();
}
@Override
public int canHold(ItemStack itemstack) {
int remains = itemstack.getCount();
for (int i = 0; i < this.items.size(); ++i) {
ItemStack itemstack1 = this.getRawItem(i);
if (itemstack1.isEmpty()) {
return itemstack.getCount();
}
if (this.hasRemainingSpaceForItem(itemstack1, itemstack)) {
remains -= (itemstack1.getMaxStackSize() < this.getMaxStackSize() ? itemstack1.getMaxStackSize() : this.getMaxStackSize()) - itemstack1.getCount();
}
if (remains <= 0) {
return itemstack.getCount();
}
}
ItemStack offhandItemStack = this.getRawItem(this.items.size() + this.armor.size());
if (this.hasRemainingSpaceForItem(offhandItemStack, itemstack)) {
remains -= (offhandItemStack.getMaxStackSize() < this.getMaxStackSize() ? offhandItemStack.getMaxStackSize() : this.getMaxStackSize()) - offhandItemStack.getCount();
}
return remains <= 0 ? itemstack.getCount() : itemstack.getCount() - remains;
}
@Override
public int getFreeSlot() {
for(int i = 0; i < this.items.size(); ++i) {
if (this.items.get(i).isEmpty()) {
return i;
}
}
return -1;
}
@Override
public void setPickedItem(ItemStack itemstack) {
int i = this.findSlotMatchingItem(itemstack);
if (isHotbarSlot(i)) {
this.selected = i;
} else if (i == -1) {
this.selected = this.getSuitableHotbarSlot();
if (!this.items.get(this.selected).isEmpty()) {
int j = this.getFreeSlot();
if (j != -1) {
this.items.set(j, this.items.get(this.selected));
}
}
this.items.set(this.selected, itemstack);
} else {
this.pickSlot(i);
}
}
@Override
public void pickSlot(int i) {
this.selected = this.getSuitableHotbarSlot();
ItemStack itemstack = this.items.get(this.selected);
this.items.set(this.selected, this.items.get(i));
this.items.set(i, itemstack);
}
@Override
public int findSlotMatchingItem(ItemStack itemstack) {
for(int i = 0; i < this.items.size(); ++i) {
if (!this.items.get(i).isEmpty() && ItemStack.isSameItemSameTags(itemstack, this.items.get(i))) {
return i;
}
}
return -1;
}
@Override
public int findSlotMatchingUnusedItem(ItemStack itemStack) {
for(int i = 0; i < this.items.size(); ++i) {
ItemStack localItem = this.items.get(i);
if (!this.items.get(i).isEmpty() && ItemStack.isSameItemSameTags(itemStack, this.items.get(i)) && !this.items.get(i).isDamaged() && !localItem.isEnchanted() && !localItem.hasCustomHoverName()) {
return i;
}
}
return -1;
}
@Override
public int getSuitableHotbarSlot() {
int i;
int j;
for(j = 0; j < 9; ++j) {
i = (this.selected + j) % 9;
if (this.items.get(i).isEmpty()) {
return i;
}
}
for(j = 0; j < 9; ++j) {
i = (this.selected + j) % 9;
if (!this.items.get(i).isEnchanted()) {
return i;
}
}
return this.selected;
}
@Override
public void swapPaint(double d0) {
if (d0 > 0.0D) {
d0 = 1.0D;
}
if (d0 < 0.0D) {
d0 = -1.0D;
}
this.selected = (int) (this.selected - d0);
while (this.selected < 0) {
this.selected += 9;
}
while(this.selected >= 9) {
this.selected -= 9;
}
}
@Override
public int clearOrCountMatchingItems(Predicate<ItemStack> predicate, int i, Container container) {
byte b0 = 0;
boolean flag = i == 0;
int j = b0 + ContainerHelper.clearOrCountMatchingItems(this, predicate, i - b0, flag);
j += ContainerHelper.clearOrCountMatchingItems(container, predicate, i - j, flag);
ItemStack itemstack = this.player.containerMenu.getCarried();
j += ContainerHelper.clearOrCountMatchingItems(itemstack, predicate, i - j, flag);
if (itemstack.isEmpty()) {
this.player.containerMenu.setCarried(ItemStack.EMPTY);
}
return j;
}
private int addResource(ItemStack itemstack) {
int i = this.getSlotWithRemainingSpace(itemstack);
if (i == -1) {
i = this.getFreeSlot();
}
return i == -1 ? itemstack.getCount() : this.addResource(i, itemstack);
}
private int addResource(int i, ItemStack itemstack) {
Item item = itemstack.getItem();
int j = itemstack.getCount();
ItemStack localItemStack = this.getRawItem(i);
if (localItemStack.isEmpty()) {
localItemStack = new ItemStack(item, 0);
if (itemstack.hasTag()) {
// hasTag ensures tag not null
//noinspection ConstantConditions
localItemStack.setTag(itemstack.getTag().copy());
}
this.setRawItem(i, localItemStack);
}
int k = Math.min(j, localItemStack.getMaxStackSize() - localItemStack.getCount());
if (k > this.getMaxStackSize() - localItemStack.getCount()) {
k = this.getMaxStackSize() - localItemStack.getCount();
}
if (k != 0) {
j -= k;
localItemStack.grow(k);
localItemStack.setPopTime(5);
}
return j;
}
@Override
public int getSlotWithRemainingSpace(ItemStack itemstack) {
if (this.hasRemainingSpaceForItem(this.getRawItem(this.selected), itemstack)) {
return this.selected;
} else if (this.hasRemainingSpaceForItem(this.getRawItem(40), itemstack)) {
return 40;
} else {
for(int i = 0; i < this.items.size(); ++i) {
if (this.hasRemainingSpaceForItem(this.items.get(i), itemstack)) {
return i;
}
}
return -1;
}
}
@Override
public void tick() {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
if (!compartment.get(i).isEmpty()) {
compartment.get(i).inventoryTick(this.player.level, this.player, i, this.selected == i);
}
}
}
}
@Override
public boolean add(ItemStack itemStack) {
return this.add(-1, itemStack);
}
@Override
public boolean add(int i, ItemStack itemStack) {
if (itemStack.isEmpty()) {
return false;
} else {
try {
if (itemStack.isDamaged()) {
if (i == -1) {
i = this.getFreeSlot();
}
if (i >= 0) {
this.items.set(i, itemStack.copy());
this.items.get(i).setPopTime(5);
itemStack.setCount(0);
return true;
} else if (this.player.getAbilities().instabuild) {
itemStack.setCount(0);
return true;
} else {
return false;
}
} else {
int j;
do {
j = itemStack.getCount();
if (i == -1) {
itemStack.setCount(this.addResource(itemStack));
} else {
itemStack.setCount(this.addResource(i, itemStack));
}
} while(!itemStack.isEmpty() && itemStack.getCount() < j);
if (itemStack.getCount() == j && this.player.getAbilities().instabuild) {
itemStack.setCount(0);
return true;
} else {
return itemStack.getCount() < j;
}
}
} catch (Throwable var6) {
CrashReport crashReport = CrashReport.forThrowable(var6, "Adding item to inventory");
CrashReportCategory crashReportCategory = crashReport.addCategory("Item being added");
crashReportCategory.setDetail("Item ID", Item.getId(itemStack.getItem()));
crashReportCategory.setDetail("Item data", itemStack.getDamageValue());
crashReportCategory.setDetail("Item name", () -> itemStack.getHoverName().getString());
throw new ReportedException(crashReport);
}
}
}
@Override
public void placeItemBackInInventory(ItemStack itemStack) {
this.placeItemBackInInventory(itemStack, true);
}
@Override
public void placeItemBackInInventory(ItemStack itemStack, boolean flag) {
while(true) {
if (!itemStack.isEmpty()) {
int i = this.getSlotWithRemainingSpace(itemStack);
if (i == -1) {
i = this.getFreeSlot();
}
if (i != -1) {
int j = itemStack.getMaxStackSize() - this.getRawItem(i).getCount();
if (this.add(i, itemStack.split(j)) && flag && this.player instanceof ServerPlayer) {
((ServerPlayer)this.player).connection.send(new ClientboundContainerSetSlotPacket(-2, 0, i, this.getRawItem(i)));
}
continue;
}
this.player.drop(itemStack, false);
}
return;
}
}
@Override
public ItemStack removeItem(int rawIndex, final int j) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null
|| indexedCompartment.compartment().get(indexedCompartment.index()).isEmpty()) {
return ItemStack.EMPTY;
}
return ContainerHelper.removeItem(indexedCompartment.compartment(), indexedCompartment.index(), j);
}
@Override
public void removeItem(ItemStack itemStack) {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
if (compartment.get(i) == itemStack) {
compartment.set(i, ItemStack.EMPTY);
break;
}
}
}
}
@Override
public ItemStack removeItemNoUpdate(int rawIndex) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
return ItemStack.EMPTY;
}
ItemStack removed = indexedCompartment.compartment().set(indexedCompartment.index(), ItemStack.EMPTY);
if (removed.isEmpty()) {
return ItemStack.EMPTY;
}
return removed;
}
@Override
public void setItem(int rawIndex, final ItemStack itemStack) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
this.player.drop(itemStack, true);
return;
}
indexedCompartment.compartment().set(indexedCompartment.index(), itemStack);
}
@Override
public float getDestroySpeed(BlockState blockState) {
return this.items.get(this.selected).getDestroySpeed(blockState);
}
@Override
public ListTag save(ListTag listTag) {
for (int i = 0; i < this.items.size(); ++i) {
if (!this.items.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)i);
this.items.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
for (int i = 0; i < this.armor.size(); ++i) {
if (!this.armor.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)(i + 100));
this.armor.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
for (int i = 0; i < this.offhand.size(); ++i) {
if (!this.offhand.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)(i + 150));
this.offhand.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
return listTag;
}
@Override
public void load(ListTag listTag) {
this.items.clear();
this.armor.clear();
this.offhand.clear();
for(int i = 0; i < listTag.size(); ++i) {
CompoundTag compoundTag = listTag.getCompound(i);
int j = compoundTag.getByte("Slot") & 255;
ItemStack itemstack = ItemStack.of(compoundTag);
if (!itemstack.isEmpty()) {
if (j < this.items.size()) {
this.items.set(j, itemstack);
} else if (j >= 100 && j < this.armor.size() + 100) {
this.armor.set(j - 100, itemstack);
} else if (j >= 150 && j < this.offhand.size() + 150) {
this.offhand.set(j - 150, itemstack);
}
}
}
}
@Override
public int getContainerSize() {
return 45;
}
@Override
public boolean isEmpty() {
return !contains(itemStack -> !itemStack.isEmpty());
}
@Override
public ItemStack getItem(int rawIndex) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
return ItemStack.EMPTY;
}
return indexedCompartment.compartment().get(indexedCompartment.index());
}
@Override
public Component getName() {
return this.player.getName();
}
@Override
public ItemStack getArmor(int index) {
return this.armor.get(index);
}
@Override
public void hurtArmor(DamageSource damagesource, float damage, int[] armorIndices) {
if (damage > 0.0F) {
damage /= 4.0F;
if (damage < 1.0F) {
damage = 1.0F;
}
for (int index : armorIndices) {
ItemStack itemstack = this.armor.get(index);
if ((!damagesource.is(DamageTypeTags.IS_FIRE) || !itemstack.getItem().isFireResistant()) && itemstack.getItem() instanceof ArmorItem) {
itemstack.hurtAndBreak((int) damage, this.player, localPlayer -> localPlayer.broadcastBreakEvent(EquipmentSlot.byTypeAndIndex(EquipmentSlot.Type.ARMOR, index)));
}
}
}
}
@Override
public void dropAll() {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
ItemStack itemstack = compartment.get(i);
if (!itemstack.isEmpty()) {
this.player.drop(itemstack, true, false);
compartment.set(i, ItemStack.EMPTY);
}
}
}
}
@Override
public void setChanged() {
super.setChanged();
}
@Override
public int getTimesChanged() {
return super.getTimesChanged();
}
@Override
public boolean stillValid(Player player) {
return true;
}
@Override
public boolean contains(ItemStack itemstack) {
return contains(itemStack -> itemStack.isEmpty() && itemStack.sameItem(itemstack));
}
@Override
public boolean contains(TagKey<Item> tagKey) {
return contains(itemStack -> !itemStack.isEmpty() && itemStack.is(tagKey));
}
@Override
public void replaceWith(Inventory inventory) {
Function<Integer, ItemStack> getter;
if (inventory instanceof SpecialPlayerInventory specialPlayerInventory) {
getter = specialPlayerInventory::getRawItem;
} else {
getter = inventory::getItem;
}
for(int i = 0; i < this.getContainerSize(); ++i) {
this.setRawItem(i, getter.apply(i));
}
this.selected = inventory.selected;
}
@Override
public void clearContent() {
for (NonNullList<ItemStack> compartment : this.compartments) {
compartment.clear();
}
}
@Override
public void fillStackedContents(StackedContents stackedContents) {
for (ItemStack itemstack : this.items) {
stackedContents.accountSimpleStack(itemstack);
}
}
@Override
public ItemStack removeFromSelected(boolean dropWholeStack) {
ItemStack itemstack = this.getSelected();
return itemstack.isEmpty() ? ItemStack.EMPTY : this.removeItem(this.selected, dropWholeStack ? itemstack.getCount() : 1);
}
}
@@ -0,0 +1,243 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R2;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.util.ReflectionHelper;
import java.lang.reflect.Field;
import java.util.logging.Logger;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.ServerPlayerGameMode;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.SimpleMenuProvider;
import net.minecraft.world.entity.monster.Shulker;
import net.minecraft.world.inventory.ChestMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.block.BarrelBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ChestBlock;
import net.minecraft.world.level.block.ShulkerBoxBlock;
import net.minecraft.world.level.block.TrappedChestBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity;
import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.block.ShulkerBox;
import org.bukkit.craftbukkit.v1_20_R2.CraftWorld;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class AnySilentContainer implements IAnySilentContainer {
private @Nullable Field serverPlayerGameModeGameType;
public AnySilentContainer() {
try {
try {
this.serverPlayerGameModeGameType = ServerPlayerGameMode.class.getDeclaredField("b");
this.serverPlayerGameModeGameType.setAccessible(true);
} catch (NoSuchFieldException e) {
Logger logger = OpenInv.getPlugin(OpenInv.class).getLogger();
logger.warning("ServerPlayerGameMode#gameModeForPlayer's obfuscated name has changed!");
logger.warning("Please report this at https://github.com/Jikoo/OpenInv/issues");
logger.warning("Attempting to fall through using reflection. Please verify that SilentContainer does not fail.");
// N.B. gameModeForPlayer is (for now) declared before previousGameModeForPlayer so silent shouldn't break.
this.serverPlayerGameModeGameType = ReflectionHelper.grabFieldByType(ServerPlayerGameMode.class, GameType.class);
}
} catch (SecurityException e) {
Logger logger = OpenInv.getPlugin(OpenInv.class).getLogger();
logger.warning("Unable to directly write player game mode! SilentContainer will fail.");
logger.log(java.util.logging.Level.WARNING, "Error obtaining GameType field", e);
}
}
@Override
public boolean isShulkerBlocked(@NotNull ShulkerBox shulkerBox) {
org.bukkit.World bukkitWorld = shulkerBox.getWorld();
if (!(bukkitWorld instanceof CraftWorld)) {
bukkitWorld = Bukkit.getWorld(bukkitWorld.getUID());
}
if (!(bukkitWorld instanceof CraftWorld craftWorld)) {
Exception exception = new IllegalStateException("AnySilentContainer access attempted on an unknown world!");
OpenInv.getPlugin(OpenInv.class).getLogger().log(java.util.logging.Level.WARNING, exception.getMessage(), exception);
return false;
}
final ServerLevel world = craftWorld.getHandle();
final BlockPos blockPosition = new BlockPos(shulkerBox.getX(), shulkerBox.getY(), shulkerBox.getZ());
final BlockEntity tile = world.getBlockEntity(blockPosition);
if (!(tile instanceof ShulkerBoxBlockEntity shulkerBoxBlockEntity)
|| shulkerBoxBlockEntity.getAnimationStatus() != ShulkerBoxBlockEntity.AnimationStatus.CLOSED) {
return false;
}
BlockState blockState = world.getBlockState(blockPosition);
// See net.minecraft.world.level.block.ShulkerBoxBlock#canOpen
AABB boundingBox = Shulker.getProgressDeltaAabb(blockState.getValue(ShulkerBoxBlock.FACING), 0.0F, 0.5F)
.move(blockPosition)
.deflate(1.0E-6D);
return !world.noCollision(boundingBox);
}
@Override
public boolean activateContainer(
@NotNull final Player bukkitPlayer,
final boolean silentchest,
@NotNull final org.bukkit.block.Block bukkitBlock) {
// Silent ender chest is API-only
if (silentchest && bukkitBlock.getType() == Material.ENDER_CHEST) {
bukkitPlayer.openInventory(bukkitPlayer.getEnderChest());
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
ServerPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
final net.minecraft.world.level.Level level = player.level();
final BlockPos blockPos = new BlockPos(bukkitBlock.getX(), bukkitBlock.getY(), bukkitBlock.getZ());
final BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity == null) {
return false;
}
if (blockEntity instanceof EnderChestBlockEntity enderChestTile) {
// Anychest ender chest. See net.minecraft.world.level.block.EnderChestBlock
PlayerEnderChestContainer enderChest = player.getEnderChestInventory();
enderChest.setActiveChest(enderChestTile);
player.openMenu(new SimpleMenuProvider((containerCounter, playerInventory, ignored) -> {
MenuType<?> containers = PlayerDataManager.getContainers(enderChest.getContainerSize());
int rows = enderChest.getContainerSize() / 9;
return new ChestMenu(containers, containerCounter, playerInventory, enderChest, rows);
}, Component.translatable(("container.enderchest"))));
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
if (!(blockEntity instanceof MenuProvider menuProvider)) {
return false;
}
BlockState blockState = level.getBlockState(blockPos);
Block block = blockState.getBlock();
if (block instanceof ChestBlock chestBlock) {
// boolean flag: do not check if chest is blocked
menuProvider = chestBlock.getMenuProvider(blockState, level, blockPos, true);
if (menuProvider == null) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
if (block instanceof TrappedChestBlock) {
bukkitPlayer.incrementStatistic(Statistic.TRAPPED_CHEST_TRIGGERED);
} else {
bukkitPlayer.incrementStatistic(Statistic.CHEST_OPENED);
}
}
if (block instanceof ShulkerBoxBlock) {
bukkitPlayer.incrementStatistic(Statistic.SHULKER_BOX_OPENED);
}
if (block instanceof BarrelBlock) {
bukkitPlayer.incrementStatistic(Statistic.OPEN_BARREL);
}
// AnyChest only - SilentChest not active, container unsupported, or unnecessary.
if (!silentchest || player.gameMode.getGameModeForPlayer() == GameType.SPECTATOR) {
player.openMenu(menuProvider);
return true;
}
// SilentChest requires access to setting players' game mode directly.
if (this.serverPlayerGameModeGameType == null) {
return false;
}
if (blockEntity instanceof RandomizableContainerBlockEntity lootable) {
if (lootable.lootTable != null) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
}
GameType gameType = player.gameMode.getGameModeForPlayer();
this.forceGameType(player, GameType.SPECTATOR);
player.openMenu(menuProvider);
this.forceGameType(player, gameType);
return true;
}
@Override
public void deactivateContainer(@NotNull final Player bukkitPlayer) {
if (this.serverPlayerGameModeGameType == null || bukkitPlayer.getGameMode() == GameMode.SPECTATOR) {
return;
}
ServerPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
// Force game mode change without informing plugins or players.
// Regular game mode set calls GameModeChangeEvent and is cancellable.
GameType gameType = player.gameMode.getGameModeForPlayer();
this.forceGameType(player, GameType.SPECTATOR);
// ServerPlayer#closeContainer cannot be called without entering an
// infinite loop because this method is called during inventory close.
// From ServerPlayer#closeContainer -> CraftEventFactory#handleInventoryCloseEvent
player.containerMenu.transferTo(player.inventoryMenu, player.getBukkitEntity());
// From ServerPlayer#closeContainer
player.doCloseContainer();
// Regular inventory close will handle the rest - packet sending, etc.
// Revert forced game mode.
this.forceGameType(player, gameType);
}
private void forceGameType(final ServerPlayer player, final GameType gameMode) {
if (this.serverPlayerGameModeGameType == null) {
// No need to warn repeatedly, error on startup and lack of function should be enough.
return;
}
try {
this.serverPlayerGameModeGameType.setAccessible(true);
this.serverPlayerGameModeGameType.set(player.gameMode, gameMode);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,173 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R2;
import com.mojang.logging.LogUtils;
import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.NumericTag;
import net.minecraft.nbt.Tag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.storage.PlayerDataStorage;
import org.bukkit.craftbukkit.v1_20_R2.CraftServer;
import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Set;
public class OpenPlayer extends CraftPlayer {
private static final Set<String> RESET_TAGS = Set.of(
// net.minecraft.world.Entity#saveWithoutId(CompoundTag)
"CustomName",
"CustomNameVisible",
"Silent",
"NoGravity",
"Glowing",
"TicksFrozen",
"HasVisualFire",
"Tags",
"Passengers",
// net.minecraft.server.level.ServerPlayer#addAdditionalSaveData(CompoundTag)
// Intentional omissions to prevent mount loss: Attach, Entity, and RootVehicle
"warden_spawn_tracker",
"enteredNetherPosition",
"SpawnX",
"SpawnY",
"SpawnZ",
"SpawnForced",
"SpawnAngle",
"SpawnDimension",
// net.minecraft.world.entity.player.Player#addAdditionalSaveData(CompoundTag)
"ShoulderEntityLeft",
"ShoulderEntityRight",
"LastDeathLocation",
// net.minecraft.world.entity.LivingEntity#addAdditionalSaveData(CompoundTag)
"ActiveEffects", // Backwards compat: Renamed from 1.19
"active_effects",
"SleepingX",
"SleepingY",
"SleepingZ",
"Brain"
);
public OpenPlayer(CraftServer server, ServerPlayer entity) {
super(server, entity);
}
@Override
public void loadData() {
PlayerDataManager.loadData(getHandle());
}
@Override
public void saveData() {
ServerPlayer player = this.getHandle();
// See net.minecraft.world.level.storage.PlayerDataStorage#save(EntityHuman)
try {
PlayerDataStorage worldNBTStorage = player.server.getPlayerList().playerIo;
CompoundTag oldData = isOnline() ? null : worldNBTStorage.load(player);
CompoundTag playerData = getWritableTag(oldData);
playerData = player.saveWithoutId(playerData);
setExtraData(playerData);
if (oldData != null) {
// Revert certain special data values when offline.
revertSpecialValues(playerData, oldData);
}
File file = File.createTempFile(player.getStringUUID() + "-", ".dat", worldNBTStorage.getPlayerDir());
NbtIo.writeCompressed(playerData, file);
File file1 = new File(worldNBTStorage.getPlayerDir(), player.getStringUUID() + ".dat");
File file2 = new File(worldNBTStorage.getPlayerDir(), player.getStringUUID() + ".dat_old");
Util.safeReplaceFile(file1, file, file2);
} catch (Exception e) {
LogUtils.getLogger().warn("Failed to save player data for {}: {}", player.getScoreboardName(), e);
}
}
@Contract("null -> new")
private @NotNull CompoundTag getWritableTag(@Nullable CompoundTag oldData) {
if (oldData == null) {
return new CompoundTag();
}
// Copy old data. This is a deep clone, so operating on it should be safe.
oldData = oldData.copy();
// Remove vanilla/server data that is not written every time.
oldData.getAllKeys().removeIf(key -> RESET_TAGS.contains(key) || key.startsWith("Bukkit"));
return oldData;
}
private void revertSpecialValues(@NotNull CompoundTag newData, @NotNull CompoundTag oldData) {
// Revert automatic updates to play timestamps.
copyValue(oldData, newData, "bukkit", "lastPlayed", NumericTag.class);
copyValue(oldData, newData, "Paper", "LastSeen", NumericTag.class);
copyValue(oldData, newData, "Paper", "LastLogin", NumericTag.class);
}
private <T extends Tag> void copyValue(
@NotNull CompoundTag source,
@NotNull CompoundTag target,
@NotNull String container,
@NotNull String key,
@NotNull Class<T> tagType) {
CompoundTag oldContainer = getTag(source, container, CompoundTag.class);
CompoundTag newContainer = getTag(target, container, CompoundTag.class);
// New container being null means the server implementation doesn't store this data.
if (newContainer == null) {
return;
}
// If old tag exists, copy it to new location, removing otherwise.
setTag(newContainer, key, getTag(oldContainer, key, tagType));
}
private <T extends Tag> @Nullable T getTag(
@Nullable CompoundTag container,
@NotNull String key,
@NotNull Class<T> dataType) {
if (container == null) {
return null;
}
Tag value = container.get(key);
if (value == null || !dataType.isAssignableFrom(value.getClass())) {
return null;
}
return dataType.cast(value);
}
private <T extends Tag> void setTag(
@NotNull CompoundTag container,
@NotNull String key,
@Nullable T data) {
if (data == null) {
container.remove(key);
} else {
container.put(key, data);
}
}
}
@@ -0,0 +1,332 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R2;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.OpenInventoryView;
import com.mojang.authlib.GameProfile;
import com.mojang.serialization.Dynamic;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.ChatVisiblity;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_20_R2.CraftServer;
import org.bukkit.craftbukkit.v1_20_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_20_R2.event.CraftEventFactory;
import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftContainer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.UUID;
import java.util.logging.Logger;
public class PlayerDataManager implements IPlayerDataManager {
private static boolean paper;
static {
try {
Class.forName("io.papermc.paper.configuration.Configuration");
paper = true;
} catch (ClassNotFoundException ignored) {
paper = false;
}
}
private @Nullable Field bukkitEntity;
public PlayerDataManager() {
try {
bukkitEntity = Entity.class.getDeclaredField("bukkitEntity");
} catch (NoSuchFieldException e) {
Logger logger = JavaPlugin.getPlugin(OpenInv.class).getLogger();
logger.warning("Unable to obtain field to inject custom save process - certain player data may be lost when saving!");
logger.log(java.util.logging.Level.WARNING, e.getMessage(), e);
bukkitEntity = null;
}
}
public static @NotNull ServerPlayer getHandle(final Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
ServerPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getUniqueId());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from Player implementation " + player.getClass().getName());
}
return nmsPlayer;
}
@Override
public @Nullable Player loadPlayer(@NotNull final OfflinePlayer offline) {
// Ensure player has data
if (!offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
ServerLevel worldServer = server.getLevel(Level.OVERWORLD);
if (worldServer == null) {
return null;
}
// Create a new ServerPlayer.
ServerPlayer entity = createNewPlayer(server, worldServer, offline);
// Stop listening for advancement progression - if this is not cleaned up, loading causes a memory leak.
entity.getAdvancements().stopListening();
// Try to load the player's data.
if (loadData(entity)) {
// If data is loaded successfully, return the Bukkit entity.
return entity.getBukkitEntity();
}
return null;
}
private @NotNull ServerPlayer createNewPlayer(
@NotNull MinecraftServer server,
@NotNull ServerLevel worldServer,
@NotNull final OfflinePlayer offline) {
// See net.minecraft.server.players.PlayerList#canPlayerLogin(ServerLoginPacketListenerImpl, GameProfile)
// See net.minecraft.server.network.ServerLoginPacketListenerImpl#handleHello(ServerboundHelloPacket)
GameProfile profile = new GameProfile(offline.getUniqueId(),
offline.getName() != null ? offline.getName() : offline.getUniqueId().toString());
ClientInformation dummyInfo = new ClientInformation(
"en_us",
1, // Reduce distance just in case.
ChatVisiblity.HIDDEN, // Don't accept chat.
false,
ServerPlayer.DEFAULT_MODEL_CUSTOMIZATION,
ServerPlayer.DEFAULT_MAIN_HAND,
true,
false // Don't list in player list (not that this player is in the list anyway).
);
ServerPlayer entity = new ServerPlayer(server, worldServer, profile, dummyInfo);
try {
injectPlayer(entity);
} catch (IllegalAccessException e) {
JavaPlugin.getPlugin(OpenInv.class).getLogger().log(
java.util.logging.Level.WARNING,
e,
() -> "Unable to inject ServerPlayer, certain player data may be lost when saving!");
}
return entity;
}
static boolean loadData(@NotNull ServerPlayer player) {
// See CraftPlayer#loadData
CompoundTag loadedData = player.server.getPlayerList().playerIo.load(player);
if (loadedData == null) {
// Exceptions with loading are logged by Mojang.
return false;
}
// Read basic data into the player.
player.load(loadedData);
// Also read "extra" data.
player.readAdditionalSaveData(loadedData);
// Game type settings are also loaded separately.
player.loadGameTypes(loadedData);
if (paper) {
// Paper: world is not loaded by ServerPlayer#load(CompoundTag).
parseWorld(player, loadedData);
}
return true;
}
private static void parseWorld(@NotNull ServerPlayer player, @NotNull CompoundTag loadedData) {
// See PlayerList#placeNewPlayer
World bukkitWorld;
if (loadedData.contains("WorldUUIDMost") && loadedData.contains("WorldUUIDLeast")) {
// Modern Bukkit world.
bukkitWorld = org.bukkit.Bukkit.getServer().getWorld(new UUID(loadedData.getLong("WorldUUIDMost"), loadedData.getLong("WorldUUIDLeast")));
} else if (loadedData.contains("world", net.minecraft.nbt.Tag.TAG_STRING)) {
// Legacy Bukkit world.
bukkitWorld = org.bukkit.Bukkit.getServer().getWorld(loadedData.getString("world"));
} else {
// Vanilla player data.
DimensionType.parseLegacy(new Dynamic<>(NbtOps.INSTANCE, loadedData.get("Dimension")))
.resultOrPartial(JavaPlugin.getPlugin(OpenInv.class).getLogger()::warning)
.map(player.server::getLevel)
// If ServerLevel exists, set, otherwise move to spawn.
.ifPresentOrElse(player::setServerLevel, () -> player.spawnIn(null));
return;
}
if (bukkitWorld == null) {
player.spawnIn(null);
return;
}
player.setServerLevel(((CraftWorld) bukkitWorld).getHandle());
}
private void injectPlayer(ServerPlayer player) throws IllegalAccessException {
if (bukkitEntity == null) {
return;
}
bukkitEntity.setAccessible(true);
bukkitEntity.set(player, new OpenPlayer(player.server.server, player));
}
@Override
public @NotNull Player inject(@NotNull Player player) {
try {
ServerPlayer nmsPlayer = getHandle(player);
if (nmsPlayer.getBukkitEntity() instanceof OpenPlayer openPlayer) {
return openPlayer;
}
injectPlayer(nmsPlayer);
return nmsPlayer.getBukkitEntity();
} catch (IllegalAccessException e) {
JavaPlugin.getPlugin(OpenInv.class).getLogger().log(
java.util.logging.Level.WARNING,
e,
() -> "Unable to inject ServerPlayer, certain player data may be lost when saving!");
return player;
}
}
@Override
public @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) {
ServerPlayer nmsPlayer = getHandle(player);
if (nmsPlayer.connection == null) {
return null;
}
InventoryView view = getView(player, inventory);
if (view == null) {
return player.openInventory(inventory.getBukkitInventory());
}
AbstractContainerMenu container = new CraftContainer(view, nmsPlayer, nmsPlayer.nextContainerCounter()) {
@Override
public MenuType<?> getType() {
return getContainers(inventory.getBukkitInventory().getSize());
}
};
container.setTitle(Component.literal(view.getTitle()));
container = CraftEventFactory.callInventoryOpenEvent(nmsPlayer, container);
if (container == null) {
return null;
}
nmsPlayer.connection.send(new ClientboundOpenScreenPacket(container.containerId, container.getType(),
Component.literal(container.getBukkitView().getTitle())));
nmsPlayer.containerMenu = container;
nmsPlayer.initMenu(container);
return container.getBukkitView();
}
private @Nullable InventoryView getView(Player player, ISpecialInventory inventory) {
if (inventory instanceof SpecialEnderChest) {
return new OpenInventoryView(player, inventory, "container.enderchest", "'s Ender Chest");
} else if (inventory instanceof SpecialPlayerInventory) {
return new OpenInventoryView(player, inventory, "container.player", "'s Inventory");
} else {
return null;
}
}
static @NotNull MenuType<?> getContainers(int inventorySize) {
return switch (inventorySize) {
case 9 -> MenuType.GENERIC_9x1;
case 18 -> MenuType.GENERIC_9x2;
case 36 -> MenuType.GENERIC_9x4; // PLAYER
case 41, 45 -> MenuType.GENERIC_9x5;
case 54 -> MenuType.GENERIC_9x6;
default -> MenuType.GENERIC_9x3; // Default 27-slot inventory
};
}
@Override
public int convertToPlayerSlot(InventoryView view, int rawSlot) {
int topSize = view.getTopInventory().getSize();
if (topSize <= rawSlot) {
// Slot is not inside special inventory, use Bukkit logic.
return view.convertSlot(rawSlot);
}
// Main inventory, slots 0-26 -> 9-35
if (rawSlot < 27) {
return rawSlot + 9;
}
// Hotbar, slots 27-35 -> 0-8
if (rawSlot < 36) {
return rawSlot - 27;
}
// Armor, slots 36-39 -> 39-36
if (rawSlot < 40) {
return 36 + (39 - rawSlot);
}
// Off hand
if (rawSlot == 40) {
return 40;
}
// Drop slots, "out of inventory"
return -1;
}
}
@@ -0,0 +1,350 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R2;
import com.lishid.openinv.internal.ISpecialEnderChest;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.ContainerListener;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_20_R2.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SpecialEnderChest extends PlayerEnderChestContainer implements ISpecialEnderChest {
private final CraftInventory inventory;
private ServerPlayer owner;
private NonNullList<ItemStack> items;
private boolean playerOnline;
public SpecialEnderChest(final org.bukkit.entity.Player player, final Boolean online) {
super(PlayerDataManager.getHandle(player));
this.inventory = new CraftInventory(this);
this.owner = PlayerDataManager.getHandle(player);
this.playerOnline = online;
this.items = this.owner.getEnderChestInventory().items;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public void setPlayerOnline(@NotNull final org.bukkit.entity.Player player) {
if (this.playerOnline) {
return;
}
ServerPlayer offlinePlayer = this.owner;
ServerPlayer onlinePlayer = PlayerDataManager.getHandle(player);
// Set owner to new player.
this.owner = onlinePlayer;
// Set player's ender chest contents to our modified contents.
PlayerEnderChestContainer onlineEnderChest = onlinePlayer.getEnderChestInventory();
for (int i = 0; i < onlineEnderChest.getContainerSize(); ++i) {
onlineEnderChest.setItem(i, this.items.get(i));
}
// Set our item array to the new inventory's array.
this.items = onlineEnderChest.items;
// Add viewers to new inventory.
onlineEnderChest.transaction.addAll(offlinePlayer.getEnderChestInventory().transaction);
this.playerOnline = true;
}
@Override
public @NotNull org.bukkit.entity.Player getPlayer() {
return owner.getBukkitEntity();
}
@Override
public void setChanged() {
this.owner.getEnderChestInventory().setChanged();
}
@Override
public List<ItemStack> getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.owner.getEnderChestInventory().onOpen(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.owner.getEnderChestInventory().onClose(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.owner.getEnderChestInventory().getViewers();
}
@Override
public boolean stillValid(Player player) {
return true;
}
@Override
public void setActiveChest(EnderChestBlockEntity enderChest) {
this.owner.getEnderChestInventory().setActiveChest(enderChest);
}
@Override
public boolean isActiveChest(EnderChestBlockEntity enderChest) {
return this.owner.getEnderChestInventory().isActiveChest(enderChest);
}
@Override
public int getMaxStackSize() {
return this.owner.getEnderChestInventory().getMaxStackSize();
}
@Override
public void setMaxStackSize(int i) {
this.owner.getEnderChestInventory().setMaxStackSize(i);
}
@Override
public InventoryHolder getOwner() {
return this.owner.getEnderChestInventory().getOwner();
}
@Override
public @Nullable Location getLocation() {
return null;
}
@Override
public void addListener(ContainerListener listener) {
this.owner.getEnderChestInventory().addListener(listener);
}
@Override
public void removeListener(ContainerListener listener) {
this.owner.getEnderChestInventory().removeListener(listener);
}
@Override
public ItemStack getItem(int i) {
return i >= 0 && i < this.items.size() ? this.items.get(i) : ItemStack.EMPTY;
}
@Override
public ItemStack removeItem(int i, int j) {
ItemStack itemstack = ContainerHelper.removeItem(this.items, i, j);
if (!itemstack.isEmpty()) {
this.setChanged();
}
return itemstack;
}
@Override
public ItemStack addItem(ItemStack itemstack) {
ItemStack localItem = itemstack.copy();
this.moveItemToOccupiedSlotsWithSameType(localItem);
if (localItem.isEmpty()) {
return ItemStack.EMPTY;
} else {
this.moveItemToEmptySlots(localItem);
return localItem.isEmpty() ? ItemStack.EMPTY : localItem;
}
}
@Override
public boolean canAddItem(ItemStack itemstack) {
for (ItemStack itemstack1 : this.items) {
if (itemstack1.isEmpty() || ItemStack.isSameItemSameTags(itemstack1, itemstack) && itemstack1.getCount() < itemstack1.getMaxStackSize()) {
return true;
}
}
return false;
}
private void moveItemToEmptySlots(ItemStack itemstack) {
for(int i = 0; i < this.getContainerSize(); ++i) {
ItemStack localItem = this.getItem(i);
if (localItem.isEmpty()) {
this.setItem(i, itemstack.copy());
itemstack.setCount(0);
return;
}
}
}
private void moveItemToOccupiedSlotsWithSameType(ItemStack itemstack) {
for(int i = 0; i < this.getContainerSize(); ++i) {
ItemStack localItem = this.getItem(i);
if (ItemStack.isSameItemSameTags(localItem, itemstack)) {
this.moveItemsBetweenStacks(itemstack, localItem);
if (itemstack.isEmpty()) {
return;
}
}
}
}
private void moveItemsBetweenStacks(ItemStack itemstack, ItemStack itemstack1) {
int i = Math.min(this.getMaxStackSize(), itemstack1.getMaxStackSize());
int j = Math.min(itemstack.getCount(), i - itemstack1.getCount());
if (j > 0) {
itemstack1.grow(j);
itemstack.shrink(j);
this.setChanged();
}
}
@Override
public ItemStack removeItemNoUpdate(int i) {
ItemStack itemstack = this.items.get(i);
if (itemstack.isEmpty()) {
return ItemStack.EMPTY;
} else {
this.items.set(i, ItemStack.EMPTY);
return itemstack;
}
}
@Override
public void setItem(int i, ItemStack itemstack) {
this.items.set(i, itemstack);
if (!itemstack.isEmpty() && itemstack.getCount() > this.getMaxStackSize()) {
itemstack.setCount(this.getMaxStackSize());
}
this.setChanged();
}
@Override
public int getContainerSize() {
return this.owner.getEnderChestInventory().getContainerSize();
}
@Override
public boolean isEmpty() {
return this.items.stream().allMatch(ItemStack::isEmpty);
}
@Override
public void startOpen(Player player) {
}
@Override
public void stopOpen(Player player) {
}
@Override
public boolean canPlaceItem(int i, ItemStack itemstack) {
return true;
}
@Override
public void clearContent() {
this.items.clear();
this.setChanged();
}
@Override
public void fillStackedContents(StackedContents stackedContents) {
for (ItemStack itemstack : this.items) {
stackedContents.accountStack(itemstack);
}
}
@Override
public List<ItemStack> removeAllItems() {
List<ItemStack> list = this.items.stream().filter(Predicate.not(ItemStack::isEmpty)).collect(Collectors.toList());
this.clearContent();
return list;
}
@Override
public ItemStack removeItemType(Item item, int i) {
ItemStack itemstack = new ItemStack(item, 0);
for(int j = this.getContainerSize() - 1; j >= 0; --j) {
ItemStack localItem = this.getItem(j);
if (localItem.getItem().equals(item)) {
int k = i - itemstack.getCount();
ItemStack splitItem = localItem.split(k);
itemstack.grow(splitItem.getCount());
if (itemstack.getCount() == i) {
break;
}
}
}
if (!itemstack.isEmpty()) {
this.setChanged();
}
return itemstack;
}
@Override
public String toString() {
return this.items.stream().filter((itemStack) -> !itemStack.isEmpty()).toList().toString();
}
@Override
public void fromTag(ListTag listTag) {
for (int i = 0; i < this.getContainerSize(); ++i) {
this.setItem(i, ItemStack.EMPTY);
}
for (int i = 0; i < listTag.size(); ++i) {
CompoundTag compoundTag = listTag.getCompound(i);
int j = compoundTag.getByte("Slot") & 255;
if (j < this.getContainerSize()) {
this.setItem(j, ItemStack.of(compoundTag));
}
}
}
}
@@ -0,0 +1,806 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R2;
import com.google.common.collect.ImmutableList;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.minecraft.CrashReport;
import net.minecraft.CrashReportCategory;
import net.minecraft.ReportedException;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.DamageTypeTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.Container;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_20_R2.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_20_R2.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SpecialPlayerInventory extends Inventory implements ISpecialPlayerInventory {
private final CraftInventory inventory;
private boolean playerOnline;
private Player player;
private NonNullList<ItemStack> items;
private NonNullList<ItemStack> armor;
private NonNullList<ItemStack> offhand;
private List<NonNullList<ItemStack>> compartments;
public SpecialPlayerInventory(@NotNull org.bukkit.entity.Player bukkitPlayer, @NotNull Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.inventory = new CraftInventory(this);
this.playerOnline = online;
this.player = super.player;
this.selected = player.getInventory().selected;
this.items = this.player.getInventory().items;
this.armor = this.player.getInventory().armor;
this.offhand = this.player.getInventory().offhand;
this.compartments = ImmutableList.of(this.items, this.armor, this.offhand);
}
@Override
public void setPlayerOnline(@NotNull org.bukkit.entity.Player player) {
if (this.playerOnline) {
return;
}
Player offlinePlayer = this.player;
Player onlinePlayer = PlayerDataManager.getHandle(player);
onlinePlayer.getInventory().transaction.addAll(this.transaction);
// Set owner to new player.
this.player = onlinePlayer;
// Set player's inventory contents to our modified contents.
Inventory onlineInventory = onlinePlayer.getInventory();
for (int i = 0; i < getContainerSize(); ++i) {
onlineInventory.setItem(i, getRawItem(i));
}
onlineInventory.selected = this.selected;
// Set our item arrays to the new inventory's arrays.
this.items = onlineInventory.items;
this.armor = onlineInventory.armor;
this.offhand = onlineInventory.offhand;
this.compartments = ImmutableList.of(this.items, this.armor, this.offhand);
// Add existing viewers to new viewer list.
Inventory offlineInventory = offlinePlayer.getInventory();
// Remove self from listing - player is always a viewer of their own inventory, prevent duplicates.
offlineInventory.transaction.remove(offlinePlayer.getBukkitEntity());
onlineInventory.transaction.addAll(offlineInventory.transaction);
this.playerOnline = true;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return this.inventory;
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public @NotNull HumanEntity getPlayer() {
return this.player.getBukkitEntity();
}
private @NotNull ItemStack getRawItem(int i) {
if (i < 0) {
return ItemStack.EMPTY;
}
NonNullList<ItemStack> list;
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
list = iterator.next();
if (i < list.size()) {
return list.get(i);
}
}
return ItemStack.EMPTY;
}
private void setRawItem(int i, @NotNull ItemStack itemStack) {
if (i < 0) {
return;
}
NonNullList<ItemStack> list;
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
list = iterator.next();
if (i < list.size()) {
list.set(i, itemStack);
}
}
}
private record IndexedCompartment(@Nullable NonNullList<ItemStack> compartment, int index) {}
private @NotNull SpecialPlayerInventory.IndexedCompartment getIndexedContent(int index) {
if (index < items.size()) {
return new IndexedCompartment(items, getReversedItemSlotNum(index));
}
index -= items.size();
if (index < armor.size()) {
return new IndexedCompartment(armor, getReversedArmorSlotNum(index));
}
index -= armor.size();
if (index < offhand.size()) {
return new IndexedCompartment(offhand, index);
}
index -= offhand.size();
return new IndexedCompartment(null, index);
}
private int getReversedArmorSlotNum(final int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
private int getReversedItemSlotNum(final int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private boolean contains(Predicate<ItemStack> predicate) {
return this.compartments.stream().flatMap(NonNullList::stream).anyMatch(predicate);
}
@Override
public List<ItemStack> getArmorContents() {
return this.armor;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.player.getInventory().onOpen(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.player.getInventory().onClose(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.player.getInventory().getViewers();
}
@Override
public InventoryHolder getOwner() {
return this.player.getBukkitEntity();
}
@Override
public int getMaxStackSize() {
return this.player.getInventory().getMaxStackSize();
}
@Override
public void setMaxStackSize(int size) {
this.player.getInventory().setMaxStackSize(size);
}
@Override
public Location getLocation() {
return this.player.getBukkitEntity().getLocation();
}
@Override
public boolean hasCustomName() {
return false;
}
@Override
public List<ItemStack> getContents() {
return this.compartments.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
@Override
public ItemStack getSelected() {
return isHotbarSlot(this.selected) ? this.items.get(this.selected) : ItemStack.EMPTY;
}
private boolean hasRemainingSpaceForItem(ItemStack itemstack, ItemStack itemstack1) {
return !itemstack.isEmpty() && ItemStack.isSameItemSameTags(itemstack, itemstack1) && itemstack.isStackable() && itemstack.getCount() < itemstack.getMaxStackSize() && itemstack.getCount() < this.getMaxStackSize();
}
@Override
public int canHold(ItemStack itemstack) {
int remains = itemstack.getCount();
for (int i = 0; i < this.items.size(); ++i) {
ItemStack itemstack1 = this.getRawItem(i);
if (itemstack1.isEmpty()) {
return itemstack.getCount();
}
if (this.hasRemainingSpaceForItem(itemstack1, itemstack)) {
remains -= (itemstack1.getMaxStackSize() < this.getMaxStackSize() ? itemstack1.getMaxStackSize() : this.getMaxStackSize()) - itemstack1.getCount();
}
if (remains <= 0) {
return itemstack.getCount();
}
}
ItemStack offhandItemStack = this.getRawItem(this.items.size() + this.armor.size());
if (this.hasRemainingSpaceForItem(offhandItemStack, itemstack)) {
remains -= (offhandItemStack.getMaxStackSize() < this.getMaxStackSize() ? offhandItemStack.getMaxStackSize() : this.getMaxStackSize()) - offhandItemStack.getCount();
}
return remains <= 0 ? itemstack.getCount() : itemstack.getCount() - remains;
}
@Override
public int getFreeSlot() {
for(int i = 0; i < this.items.size(); ++i) {
if (this.items.get(i).isEmpty()) {
return i;
}
}
return -1;
}
@Override
public void setPickedItem(ItemStack itemstack) {
int i = this.findSlotMatchingItem(itemstack);
if (isHotbarSlot(i)) {
this.selected = i;
} else if (i == -1) {
this.selected = this.getSuitableHotbarSlot();
if (!this.items.get(this.selected).isEmpty()) {
int j = this.getFreeSlot();
if (j != -1) {
this.items.set(j, this.items.get(this.selected));
}
}
this.items.set(this.selected, itemstack);
} else {
this.pickSlot(i);
}
}
@Override
public void pickSlot(int i) {
this.selected = this.getSuitableHotbarSlot();
ItemStack itemstack = this.items.get(this.selected);
this.items.set(this.selected, this.items.get(i));
this.items.set(i, itemstack);
}
@Override
public int findSlotMatchingItem(ItemStack itemstack) {
for(int i = 0; i < this.items.size(); ++i) {
if (!this.items.get(i).isEmpty() && ItemStack.isSameItemSameTags(itemstack, this.items.get(i))) {
return i;
}
}
return -1;
}
@Override
public int findSlotMatchingUnusedItem(ItemStack itemStack) {
for(int i = 0; i < this.items.size(); ++i) {
ItemStack localItem = this.items.get(i);
if (!this.items.get(i).isEmpty() && ItemStack.isSameItemSameTags(itemStack, this.items.get(i)) && !this.items.get(i).isDamaged() && !localItem.isEnchanted() && !localItem.hasCustomHoverName()) {
return i;
}
}
return -1;
}
@Override
public int getSuitableHotbarSlot() {
int i;
int j;
for(j = 0; j < 9; ++j) {
i = (this.selected + j) % 9;
if (this.items.get(i).isEmpty()) {
return i;
}
}
for(j = 0; j < 9; ++j) {
i = (this.selected + j) % 9;
if (!this.items.get(i).isEnchanted()) {
return i;
}
}
return this.selected;
}
@Override
public void swapPaint(double d0) {
if (d0 > 0.0D) {
d0 = 1.0D;
}
if (d0 < 0.0D) {
d0 = -1.0D;
}
this.selected = (int) (this.selected - d0);
while (this.selected < 0) {
this.selected += 9;
}
while(this.selected >= 9) {
this.selected -= 9;
}
}
@Override
public int clearOrCountMatchingItems(Predicate<ItemStack> predicate, int i, Container container) {
byte b0 = 0;
boolean flag = i == 0;
int j = b0 + ContainerHelper.clearOrCountMatchingItems(this, predicate, i - b0, flag);
j += ContainerHelper.clearOrCountMatchingItems(container, predicate, i - j, flag);
ItemStack itemstack = this.player.containerMenu.getCarried();
j += ContainerHelper.clearOrCountMatchingItems(itemstack, predicate, i - j, flag);
if (itemstack.isEmpty()) {
this.player.containerMenu.setCarried(ItemStack.EMPTY);
}
return j;
}
private int addResource(ItemStack itemstack) {
int i = this.getSlotWithRemainingSpace(itemstack);
if (i == -1) {
i = this.getFreeSlot();
}
return i == -1 ? itemstack.getCount() : this.addResource(i, itemstack);
}
private int addResource(int i, ItemStack itemstack) {
Item item = itemstack.getItem();
int j = itemstack.getCount();
ItemStack localItemStack = this.getRawItem(i);
if (localItemStack.isEmpty()) {
localItemStack = new ItemStack(item, 0);
if (itemstack.hasTag()) {
// hasTag ensures tag not null
//noinspection ConstantConditions
localItemStack.setTag(itemstack.getTag().copy());
}
this.setRawItem(i, localItemStack);
}
int k = Math.min(j, localItemStack.getMaxStackSize() - localItemStack.getCount());
if (k > this.getMaxStackSize() - localItemStack.getCount()) {
k = this.getMaxStackSize() - localItemStack.getCount();
}
if (k != 0) {
j -= k;
localItemStack.grow(k);
localItemStack.setPopTime(5);
}
return j;
}
@Override
public int getSlotWithRemainingSpace(ItemStack itemstack) {
if (this.hasRemainingSpaceForItem(this.getRawItem(this.selected), itemstack)) {
return this.selected;
} else if (this.hasRemainingSpaceForItem(this.getRawItem(40), itemstack)) {
return 40;
} else {
for(int i = 0; i < this.items.size(); ++i) {
if (this.hasRemainingSpaceForItem(this.items.get(i), itemstack)) {
return i;
}
}
return -1;
}
}
@Override
public void tick() {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
if (!compartment.get(i).isEmpty()) {
compartment.get(i).inventoryTick(this.player.level(), this.player, i, this.selected == i);
}
}
}
}
@Override
public boolean add(ItemStack itemStack) {
return this.add(-1, itemStack);
}
@Override
public boolean add(int i, ItemStack itemStack) {
if (itemStack.isEmpty()) {
return false;
} else {
try {
if (itemStack.isDamaged()) {
if (i == -1) {
i = this.getFreeSlot();
}
if (i >= 0) {
this.items.set(i, itemStack.copy());
this.items.get(i).setPopTime(5);
itemStack.setCount(0);
return true;
} else if (this.player.getAbilities().instabuild) {
itemStack.setCount(0);
return true;
} else {
return false;
}
} else {
int j;
do {
j = itemStack.getCount();
if (i == -1) {
itemStack.setCount(this.addResource(itemStack));
} else {
itemStack.setCount(this.addResource(i, itemStack));
}
} while(!itemStack.isEmpty() && itemStack.getCount() < j);
if (itemStack.getCount() == j && this.player.getAbilities().instabuild) {
itemStack.setCount(0);
return true;
} else {
return itemStack.getCount() < j;
}
}
} catch (Throwable var6) {
CrashReport crashReport = CrashReport.forThrowable(var6, "Adding item to inventory");
CrashReportCategory crashReportCategory = crashReport.addCategory("Item being added");
crashReportCategory.setDetail("Item ID", Item.getId(itemStack.getItem()));
crashReportCategory.setDetail("Item data", itemStack.getDamageValue());
crashReportCategory.setDetail("Item name", () -> itemStack.getHoverName().getString());
throw new ReportedException(crashReport);
}
}
}
@Override
public void placeItemBackInInventory(ItemStack itemStack) {
this.placeItemBackInInventory(itemStack, true);
}
@Override
public void placeItemBackInInventory(ItemStack itemStack, boolean flag) {
while(true) {
if (!itemStack.isEmpty()) {
int i = this.getSlotWithRemainingSpace(itemStack);
if (i == -1) {
i = this.getFreeSlot();
}
if (i != -1) {
int j = itemStack.getMaxStackSize() - this.getRawItem(i).getCount();
if (this.add(i, itemStack.split(j)) && flag && this.player instanceof ServerPlayer) {
((ServerPlayer)this.player).connection.send(new ClientboundContainerSetSlotPacket(-2, 0, i, this.getRawItem(i)));
}
continue;
}
this.player.drop(itemStack, false);
}
return;
}
}
@Override
public ItemStack removeItem(int rawIndex, final int j) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null
|| indexedCompartment.compartment().get(indexedCompartment.index()).isEmpty()) {
return ItemStack.EMPTY;
}
return ContainerHelper.removeItem(indexedCompartment.compartment(), indexedCompartment.index(), j);
}
@Override
public void removeItem(ItemStack itemStack) {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
if (compartment.get(i) == itemStack) {
compartment.set(i, ItemStack.EMPTY);
break;
}
}
}
}
@Override
public ItemStack removeItemNoUpdate(int rawIndex) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
return ItemStack.EMPTY;
}
ItemStack removed = indexedCompartment.compartment().set(indexedCompartment.index(), ItemStack.EMPTY);
if (removed.isEmpty()) {
return ItemStack.EMPTY;
}
return removed;
}
@Override
public void setItem(int rawIndex, final ItemStack itemStack) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
this.player.drop(itemStack, true);
return;
}
indexedCompartment.compartment().set(indexedCompartment.index(), itemStack);
}
@Override
public float getDestroySpeed(BlockState blockState) {
return this.items.get(this.selected).getDestroySpeed(blockState);
}
@Override
public ListTag save(ListTag listTag) {
for (int i = 0; i < this.items.size(); ++i) {
if (!this.items.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)i);
this.items.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
for (int i = 0; i < this.armor.size(); ++i) {
if (!this.armor.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)(i + 100));
this.armor.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
for (int i = 0; i < this.offhand.size(); ++i) {
if (!this.offhand.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)(i + 150));
this.offhand.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
return listTag;
}
@Override
public void load(ListTag listTag) {
this.items.clear();
this.armor.clear();
this.offhand.clear();
for(int i = 0; i < listTag.size(); ++i) {
CompoundTag compoundTag = listTag.getCompound(i);
int j = compoundTag.getByte("Slot") & 255;
ItemStack itemstack = ItemStack.of(compoundTag);
if (!itemstack.isEmpty()) {
if (j < this.items.size()) {
this.items.set(j, itemstack);
} else if (j >= 100 && j < this.armor.size() + 100) {
this.armor.set(j - 100, itemstack);
} else if (j >= 150 && j < this.offhand.size() + 150) {
this.offhand.set(j - 150, itemstack);
}
}
}
}
@Override
public int getContainerSize() {
return 45;
}
@Override
public boolean isEmpty() {
return !contains(itemStack -> !itemStack.isEmpty());
}
@Override
public ItemStack getItem(int rawIndex) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
return ItemStack.EMPTY;
}
return indexedCompartment.compartment().get(indexedCompartment.index());
}
@Override
public Component getName() {
return this.player.getName();
}
@Override
public ItemStack getArmor(int index) {
return this.armor.get(index);
}
@Override
public void hurtArmor(DamageSource damagesource, float damage, int[] armorIndices) {
if (damage > 0.0F) {
damage /= 4.0F;
if (damage < 1.0F) {
damage = 1.0F;
}
for (int index : armorIndices) {
ItemStack itemstack = this.armor.get(index);
if ((!damagesource.is(DamageTypeTags.IS_FIRE) || !itemstack.getItem().isFireResistant()) && itemstack.getItem() instanceof ArmorItem) {
itemstack.hurtAndBreak((int) damage, this.player, localPlayer -> localPlayer.broadcastBreakEvent(EquipmentSlot.byTypeAndIndex(EquipmentSlot.Type.ARMOR, index)));
}
}
}
}
@Override
public void dropAll() {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
ItemStack itemstack = compartment.get(i);
if (!itemstack.isEmpty()) {
this.player.drop(itemstack, true, false);
compartment.set(i, ItemStack.EMPTY);
}
}
}
}
@Override
public void setChanged() {
super.setChanged();
}
@Override
public int getTimesChanged() {
return super.getTimesChanged();
}
@Override
public boolean stillValid(Player player) {
return true;
}
@Override
public boolean contains(ItemStack itemstack) {
return contains(itemStack -> itemStack.isEmpty() && itemStack.is(itemstack.getItem()));
}
@Override
public boolean contains(TagKey<Item> tagKey) {
return contains(itemStack -> !itemStack.isEmpty() && itemStack.is(tagKey));
}
@Override
public void replaceWith(Inventory inventory) {
Function<Integer, ItemStack> getter;
if (inventory instanceof SpecialPlayerInventory specialPlayerInventory) {
getter = specialPlayerInventory::getRawItem;
} else {
getter = inventory::getItem;
}
for(int i = 0; i < this.getContainerSize(); ++i) {
this.setRawItem(i, getter.apply(i));
}
this.selected = inventory.selected;
}
@Override
public void clearContent() {
for (NonNullList<ItemStack> compartment : this.compartments) {
compartment.clear();
}
}
@Override
public void fillStackedContents(StackedContents stackedContents) {
for (ItemStack itemstack : this.items) {
stackedContents.accountSimpleStack(itemstack);
}
}
@Override
public ItemStack removeFromSelected(boolean dropWholeStack) {
ItemStack itemstack = this.getSelected();
return itemstack.isEmpty() ? ItemStack.EMPTY : this.removeItem(this.selected, dropWholeStack ? itemstack.getCount() : 1);
}
}
@@ -0,0 +1,244 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R3;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.IAnySilentContainer;
import com.lishid.openinv.util.ReflectionHelper;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.ServerPlayerGameMode;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.SimpleMenuProvider;
import net.minecraft.world.entity.monster.Shulker;
import net.minecraft.world.inventory.ChestMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.block.BarrelBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.ChestBlock;
import net.minecraft.world.level.block.ShulkerBoxBlock;
import net.minecraft.world.level.block.TrappedChestBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity;
import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.block.ShulkerBox;
import org.bukkit.craftbukkit.v1_20_R3.CraftWorld;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.logging.Logger;
public class AnySilentContainer implements IAnySilentContainer {
private @Nullable Field serverPlayerGameModeGameType;
public AnySilentContainer() {
try {
try {
this.serverPlayerGameModeGameType = ServerPlayerGameMode.class.getDeclaredField("b");
this.serverPlayerGameModeGameType.setAccessible(true);
} catch (NoSuchFieldException e) {
Logger logger = OpenInv.getPlugin(OpenInv.class).getLogger();
logger.warning("ServerPlayerGameMode#gameModeForPlayer's obfuscated name has changed!");
logger.warning("Please report this at https://github.com/Jikoo/OpenInv/issues");
logger.warning("Attempting to fall through using reflection. Please verify that SilentContainer does not fail.");
// N.B. gameModeForPlayer is (for now) declared before previousGameModeForPlayer so silent shouldn't break.
this.serverPlayerGameModeGameType = ReflectionHelper.grabFieldByType(ServerPlayerGameMode.class, GameType.class);
}
} catch (SecurityException e) {
Logger logger = OpenInv.getPlugin(OpenInv.class).getLogger();
logger.warning("Unable to directly write player game mode! SilentContainer will fail.");
logger.log(java.util.logging.Level.WARNING, "Error obtaining GameType field", e);
}
}
@Override
public boolean isShulkerBlocked(@NotNull ShulkerBox shulkerBox) {
org.bukkit.World bukkitWorld = shulkerBox.getWorld();
if (!(bukkitWorld instanceof CraftWorld)) {
bukkitWorld = Bukkit.getWorld(bukkitWorld.getUID());
}
if (!(bukkitWorld instanceof CraftWorld craftWorld)) {
Exception exception = new IllegalStateException("AnySilentContainer access attempted on an unknown world!");
OpenInv.getPlugin(OpenInv.class).getLogger().log(java.util.logging.Level.WARNING, exception.getMessage(), exception);
return false;
}
final ServerLevel world = craftWorld.getHandle();
final BlockPos blockPosition = new BlockPos(shulkerBox.getX(), shulkerBox.getY(), shulkerBox.getZ());
final BlockEntity tile = world.getBlockEntity(blockPosition);
if (!(tile instanceof ShulkerBoxBlockEntity shulkerBoxBlockEntity)
|| shulkerBoxBlockEntity.getAnimationStatus() != ShulkerBoxBlockEntity.AnimationStatus.CLOSED) {
return false;
}
BlockState blockState = world.getBlockState(blockPosition);
// See net.minecraft.world.level.block.ShulkerBoxBlock#canOpen
AABB boundingBox = Shulker.getProgressDeltaAabb(blockState.getValue(ShulkerBoxBlock.FACING), 0.0F, 0.5F)
.move(blockPosition)
.deflate(1.0E-6D);
return !world.noCollision(boundingBox);
}
@Override
public boolean activateContainer(
@NotNull final Player bukkitPlayer,
final boolean silentchest,
@NotNull final org.bukkit.block.Block bukkitBlock) {
// Silent ender chest is API-only
if (silentchest && bukkitBlock.getType() == Material.ENDER_CHEST) {
bukkitPlayer.openInventory(bukkitPlayer.getEnderChest());
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
ServerPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
final net.minecraft.world.level.Level level = player.level();
final BlockPos blockPos = new BlockPos(bukkitBlock.getX(), bukkitBlock.getY(), bukkitBlock.getZ());
final BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity == null) {
return false;
}
if (blockEntity instanceof EnderChestBlockEntity enderChestTile) {
// Anychest ender chest. See net.minecraft.world.level.block.EnderChestBlock
PlayerEnderChestContainer enderChest = player.getEnderChestInventory();
enderChest.setActiveChest(enderChestTile);
player.openMenu(new SimpleMenuProvider((containerCounter, playerInventory, ignored) -> {
MenuType<?> containers = PlayerDataManager.getContainers(enderChest.getContainerSize());
int rows = enderChest.getContainerSize() / 9;
return new ChestMenu(containers, containerCounter, playerInventory, enderChest, rows);
}, Component.translatable(("container.enderchest"))));
bukkitPlayer.incrementStatistic(Statistic.ENDERCHEST_OPENED);
return true;
}
if (!(blockEntity instanceof MenuProvider menuProvider)) {
return false;
}
BlockState blockState = level.getBlockState(blockPos);
Block block = blockState.getBlock();
if (block instanceof ChestBlock chestBlock) {
// boolean flag: do not check if chest is blocked
menuProvider = chestBlock.getMenuProvider(blockState, level, blockPos, true);
if (menuProvider == null) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
if (block instanceof TrappedChestBlock) {
bukkitPlayer.incrementStatistic(Statistic.TRAPPED_CHEST_TRIGGERED);
} else {
bukkitPlayer.incrementStatistic(Statistic.CHEST_OPENED);
}
}
if (block instanceof ShulkerBoxBlock) {
bukkitPlayer.incrementStatistic(Statistic.SHULKER_BOX_OPENED);
}
if (block instanceof BarrelBlock) {
bukkitPlayer.incrementStatistic(Statistic.OPEN_BARREL);
}
// AnyChest only - SilentChest not active, container unsupported, or unnecessary.
if (!silentchest || player.gameMode.getGameModeForPlayer() == GameType.SPECTATOR) {
player.openMenu(menuProvider);
return true;
}
// SilentChest requires access to setting players' game mode directly.
if (this.serverPlayerGameModeGameType == null) {
return false;
}
if (blockEntity instanceof RandomizableContainerBlockEntity lootable) {
if (lootable.lootTable != null) {
OpenInv.getPlugin(OpenInv.class).sendSystemMessage(bukkitPlayer, "messages.error.lootNotGenerated");
return false;
}
}
GameType gameType = player.gameMode.getGameModeForPlayer();
this.forceGameType(player, GameType.SPECTATOR);
player.openMenu(menuProvider);
this.forceGameType(player, gameType);
return true;
}
@Override
public void deactivateContainer(@NotNull final Player bukkitPlayer) {
if (this.serverPlayerGameModeGameType == null || bukkitPlayer.getGameMode() == GameMode.SPECTATOR) {
return;
}
ServerPlayer player = PlayerDataManager.getHandle(bukkitPlayer);
// Force game mode change without informing plugins or players.
// Regular game mode set calls GameModeChangeEvent and is cancellable.
GameType gameType = player.gameMode.getGameModeForPlayer();
this.forceGameType(player, GameType.SPECTATOR);
// ServerPlayer#closeContainer cannot be called without entering an
// infinite loop because this method is called during inventory close.
// From ServerPlayer#closeContainer -> CraftEventFactory#handleInventoryCloseEvent
player.containerMenu.transferTo(player.inventoryMenu, player.getBukkitEntity());
// From ServerPlayer#closeContainer
player.doCloseContainer();
// Regular inventory close will handle the rest - packet sending, etc.
// Revert forced game mode.
this.forceGameType(player, gameType);
}
private void forceGameType(final ServerPlayer player, final GameType gameMode) {
if (this.serverPlayerGameModeGameType == null) {
// No need to warn repeatedly, error on startup and lack of function should be enough.
return;
}
try {
this.serverPlayerGameModeGameType.setAccessible(true);
this.serverPlayerGameModeGameType.set(player.gameMode, gameMode);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,176 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R3;
import com.mojang.logging.LogUtils;
import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.NumericTag;
import net.minecraft.nbt.Tag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.storage.PlayerDataStorage;
import org.bukkit.craftbukkit.v1_20_R3.CraftServer;
import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
public class OpenPlayer extends CraftPlayer {
private static final Set<String> RESET_TAGS = Set.of(
// net.minecraft.world.Entity#saveWithoutId(CompoundTag)
"CustomName",
"CustomNameVisible",
"Silent",
"NoGravity",
"Glowing",
"TicksFrozen",
"HasVisualFire",
"Tags",
"Passengers",
// net.minecraft.server.level.ServerPlayer#addAdditionalSaveData(CompoundTag)
// Intentional omissions to prevent mount loss: Attach, Entity, and RootVehicle
"warden_spawn_tracker",
"enteredNetherPosition",
"SpawnX",
"SpawnY",
"SpawnZ",
"SpawnForced",
"SpawnAngle",
"SpawnDimension",
// net.minecraft.world.entity.player.Player#addAdditionalSaveData(CompoundTag)
"ShoulderEntityLeft",
"ShoulderEntityRight",
"LastDeathLocation",
// net.minecraft.world.entity.LivingEntity#addAdditionalSaveData(CompoundTag)
"ActiveEffects", // Backwards compat: Renamed from 1.19
"active_effects",
"SleepingX",
"SleepingY",
"SleepingZ",
"Brain"
);
public OpenPlayer(CraftServer server, ServerPlayer entity) {
super(server, entity);
}
@Override
public void loadData() {
PlayerDataManager.loadData(getHandle());
}
@Override
public void saveData() {
ServerPlayer player = this.getHandle();
// See net.minecraft.world.level.storage.PlayerDataStorage#save(EntityHuman)
try {
PlayerDataStorage worldNBTStorage = player.server.getPlayerList().playerIo;
CompoundTag oldData = isOnline() ? null : worldNBTStorage.load(player);
CompoundTag playerData = getWritableTag(oldData);
playerData = player.saveWithoutId(playerData);
setExtraData(playerData);
if (oldData != null) {
// Revert certain special data values when offline.
revertSpecialValues(playerData, oldData);
}
Path playerDataDir = worldNBTStorage.getPlayerDir().toPath();
Path file = Files.createTempFile(playerDataDir, player.getStringUUID() + "-", ".dat");
NbtIo.writeCompressed(playerData, file);
Path dataFile = playerDataDir.resolve(player.getStringUUID() + ".dat");
Path backupFile = playerDataDir.resolve(player.getStringUUID() + ".dat_old");
Util.safeReplaceFile(dataFile, file, backupFile);
} catch (Exception e) {
LogUtils.getLogger().warn("Failed to save player data for {}: {}", player.getScoreboardName(), e);
}
}
@Contract("null -> new")
private @NotNull CompoundTag getWritableTag(@Nullable CompoundTag oldData) {
if (oldData == null) {
return new CompoundTag();
}
// Copy old data. This is a deep clone, so operating on it should be safe.
oldData = oldData.copy();
// Remove vanilla/server data that is not written every time.
oldData.getAllKeys()
.removeIf(key -> RESET_TAGS.contains(key) || key.startsWith("Bukkit"));
return oldData;
}
private void revertSpecialValues(@NotNull CompoundTag newData, @NotNull CompoundTag oldData) {
// Revert automatic updates to play timestamps.
copyValue(oldData, newData, "bukkit", "lastPlayed", NumericTag.class);
copyValue(oldData, newData, "Paper", "LastSeen", NumericTag.class);
copyValue(oldData, newData, "Paper", "LastLogin", NumericTag.class);
}
private <T extends Tag> void copyValue(
@NotNull CompoundTag source,
@NotNull CompoundTag target,
@NotNull String container,
@NotNull String key,
@NotNull Class<T> tagType) {
CompoundTag oldContainer = getTag(source, container, CompoundTag.class);
CompoundTag newContainer = getTag(target, container, CompoundTag.class);
// New container being null means the server implementation doesn't store this data.
if (newContainer == null) {
return;
}
// If old tag exists, copy it to new location, removing otherwise.
setTag(newContainer, key, getTag(oldContainer, key, tagType));
}
private <T extends Tag> @Nullable T getTag(
@Nullable CompoundTag container,
@NotNull String key,
@NotNull Class<T> dataType) {
if (container == null) {
return null;
}
Tag value = container.get(key);
if (value == null || !dataType.isAssignableFrom(value.getClass())) {
return null;
}
return dataType.cast(value);
}
private <T extends Tag> void setTag(
@NotNull CompoundTag container,
@NotNull String key,
@Nullable T data) {
if (data == null) {
container.remove(key);
} else {
container.put(key, data);
}
}
}
@@ -0,0 +1,332 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R3;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.internal.IPlayerDataManager;
import com.lishid.openinv.internal.ISpecialInventory;
import com.lishid.openinv.internal.OpenInventoryView;
import com.mojang.authlib.GameProfile;
import com.mojang.serialization.Dynamic;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.ChatVisiblity;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_20_R3.CraftServer;
import org.bukkit.craftbukkit.v1_20_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_20_R3.event.CraftEventFactory;
import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftContainer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryView;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.UUID;
import java.util.logging.Logger;
public class PlayerDataManager implements IPlayerDataManager {
private static boolean paper;
static {
try {
Class.forName("io.papermc.paper.configuration.Configuration");
paper = true;
} catch (ClassNotFoundException ignored) {
paper = false;
}
}
private @Nullable Field bukkitEntity;
public PlayerDataManager() {
try {
bukkitEntity = Entity.class.getDeclaredField("bukkitEntity");
} catch (NoSuchFieldException e) {
Logger logger = JavaPlugin.getPlugin(OpenInv.class).getLogger();
logger.warning("Unable to obtain field to inject custom save process - certain player data may be lost when saving!");
logger.log(java.util.logging.Level.WARNING, e.getMessage(), e);
bukkitEntity = null;
}
}
public static @NotNull ServerPlayer getHandle(final Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
ServerPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getUniqueId());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from Player implementation " + player.getClass().getName());
}
return nmsPlayer;
}
@Override
public @Nullable Player loadPlayer(@NotNull final OfflinePlayer offline) {
// Ensure player has data
if (!offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
ServerLevel worldServer = server.getLevel(Level.OVERWORLD);
if (worldServer == null) {
return null;
}
// Create a new ServerPlayer.
ServerPlayer entity = createNewPlayer(server, worldServer, offline);
// Stop listening for advancement progression - if this is not cleaned up, loading causes a memory leak.
entity.getAdvancements().stopListening();
// Try to load the player's data.
if (loadData(entity)) {
// If data is loaded successfully, return the Bukkit entity.
return entity.getBukkitEntity();
}
return null;
}
private @NotNull ServerPlayer createNewPlayer(
@NotNull MinecraftServer server,
@NotNull ServerLevel worldServer,
@NotNull final OfflinePlayer offline) {
// See net.minecraft.server.players.PlayerList#canPlayerLogin(ServerLoginPacketListenerImpl, GameProfile)
// See net.minecraft.server.network.ServerLoginPacketListenerImpl#handleHello(ServerboundHelloPacket)
GameProfile profile = new GameProfile(offline.getUniqueId(),
offline.getName() != null ? offline.getName() : offline.getUniqueId().toString());
ClientInformation dummyInfo = new ClientInformation(
"en_us",
1, // Reduce distance just in case.
ChatVisiblity.HIDDEN, // Don't accept chat.
false,
ServerPlayer.DEFAULT_MODEL_CUSTOMIZATION,
ServerPlayer.DEFAULT_MAIN_HAND,
true,
false // Don't list in player list (not that this player is in the list anyway).
);
ServerPlayer entity = new ServerPlayer(server, worldServer, profile, dummyInfo);
try {
injectPlayer(entity);
} catch (IllegalAccessException e) {
JavaPlugin.getPlugin(OpenInv.class).getLogger().log(
java.util.logging.Level.WARNING,
e,
() -> "Unable to inject ServerPlayer, certain player data may be lost when saving!");
}
return entity;
}
static boolean loadData(@NotNull ServerPlayer player) {
// See CraftPlayer#loadData
CompoundTag loadedData = player.server.getPlayerList().playerIo.load(player);
if (loadedData == null) {
// Exceptions with loading are logged by Mojang.
return false;
}
// Read basic data into the player.
player.load(loadedData);
// Also read "extra" data.
player.readAdditionalSaveData(loadedData);
// Game type settings are also loaded separately.
player.loadGameTypes(loadedData);
if (paper) {
// Paper: world is not loaded by ServerPlayer#load(CompoundTag).
parseWorld(player, loadedData);
}
return true;
}
private static void parseWorld(@NotNull ServerPlayer player, @NotNull CompoundTag loadedData) {
// See PlayerList#placeNewPlayer
World bukkitWorld;
if (loadedData.contains("WorldUUIDMost") && loadedData.contains("WorldUUIDLeast")) {
// Modern Bukkit world.
bukkitWorld = Bukkit.getServer().getWorld(new UUID(loadedData.getLong("WorldUUIDMost"), loadedData.getLong("WorldUUIDLeast")));
} else if (loadedData.contains("world", net.minecraft.nbt.Tag.TAG_STRING)) {
// Legacy Bukkit world.
bukkitWorld = Bukkit.getServer().getWorld(loadedData.getString("world"));
} else {
// Vanilla player data.
DimensionType.parseLegacy(new Dynamic<>(NbtOps.INSTANCE, loadedData.get("Dimension")))
.resultOrPartial(JavaPlugin.getPlugin(OpenInv.class).getLogger()::warning)
.map(player.server::getLevel)
// If ServerLevel exists, set, otherwise move to spawn.
.ifPresentOrElse(player::setServerLevel, () -> player.spawnIn(null));
return;
}
if (bukkitWorld == null) {
player.spawnIn(null);
return;
}
player.setServerLevel(((CraftWorld) bukkitWorld).getHandle());
}
private void injectPlayer(ServerPlayer player) throws IllegalAccessException {
if (bukkitEntity == null) {
return;
}
bukkitEntity.setAccessible(true);
bukkitEntity.set(player, new OpenPlayer(player.server.server, player));
}
@Override
public @NotNull Player inject(@NotNull Player player) {
try {
ServerPlayer nmsPlayer = getHandle(player);
if (nmsPlayer.getBukkitEntity() instanceof OpenPlayer openPlayer) {
return openPlayer;
}
injectPlayer(nmsPlayer);
return nmsPlayer.getBukkitEntity();
} catch (IllegalAccessException e) {
JavaPlugin.getPlugin(OpenInv.class).getLogger().log(
java.util.logging.Level.WARNING,
e,
() -> "Unable to inject ServerPlayer, certain player data may be lost when saving!");
return player;
}
}
@Override
public @Nullable InventoryView openInventory(@NotNull Player player, @NotNull ISpecialInventory inventory) {
ServerPlayer nmsPlayer = getHandle(player);
if (nmsPlayer.connection == null) {
return null;
}
InventoryView view = getView(player, inventory);
if (view == null) {
return player.openInventory(inventory.getBukkitInventory());
}
AbstractContainerMenu container = new CraftContainer(view, nmsPlayer, nmsPlayer.nextContainerCounter()) {
@Override
public MenuType<?> getType() {
return getContainers(inventory.getBukkitInventory().getSize());
}
};
container.setTitle(Component.literal(view.getTitle()));
container = CraftEventFactory.callInventoryOpenEvent(nmsPlayer, container);
if (container == null) {
return null;
}
nmsPlayer.connection.send(new ClientboundOpenScreenPacket(container.containerId, container.getType(),
Component.literal(container.getBukkitView().getTitle())));
nmsPlayer.containerMenu = container;
nmsPlayer.initMenu(container);
return container.getBukkitView();
}
private @Nullable InventoryView getView(Player player, ISpecialInventory inventory) {
if (inventory instanceof SpecialEnderChest) {
return new OpenInventoryView(player, inventory, "container.enderchest", "'s Ender Chest");
} else if (inventory instanceof SpecialPlayerInventory) {
return new OpenInventoryView(player, inventory, "container.player", "'s Inventory");
} else {
return null;
}
}
static @NotNull MenuType<?> getContainers(int inventorySize) {
return switch (inventorySize) {
case 9 -> MenuType.GENERIC_9x1;
case 18 -> MenuType.GENERIC_9x2;
case 36 -> MenuType.GENERIC_9x4; // PLAYER
case 41, 45 -> MenuType.GENERIC_9x5;
case 54 -> MenuType.GENERIC_9x6;
default -> MenuType.GENERIC_9x3; // Default 27-slot inventory
};
}
@Override
public int convertToPlayerSlot(InventoryView view, int rawSlot) {
int topSize = view.getTopInventory().getSize();
if (topSize <= rawSlot) {
// Slot is not inside special inventory, use Bukkit logic.
return view.convertSlot(rawSlot);
}
// Main inventory, slots 0-26 -> 9-35
if (rawSlot < 27) {
return rawSlot + 9;
}
// Hotbar, slots 27-35 -> 0-8
if (rawSlot < 36) {
return rawSlot - 27;
}
// Armor, slots 36-39 -> 39-36
if (rawSlot < 40) {
return 36 + (39 - rawSlot);
}
// Off hand
if (rawSlot == 40) {
return 40;
}
// Drop slots, "out of inventory"
return -1;
}
}
@@ -0,0 +1,351 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R3;
import com.lishid.openinv.internal.ISpecialEnderChest;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.ContainerListener;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.inventory.PlayerEnderChestContainer;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_20_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class SpecialEnderChest extends PlayerEnderChestContainer implements ISpecialEnderChest {
private final CraftInventory inventory;
private ServerPlayer owner;
private NonNullList<ItemStack> items;
private boolean playerOnline;
public SpecialEnderChest(final org.bukkit.entity.Player player, final Boolean online) {
super(PlayerDataManager.getHandle(player));
this.inventory = new CraftInventory(this);
this.owner = PlayerDataManager.getHandle(player);
this.playerOnline = online;
this.items = this.owner.getEnderChestInventory().items;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public void setPlayerOnline(@NotNull final org.bukkit.entity.Player player) {
if (this.playerOnline) {
return;
}
ServerPlayer offlinePlayer = this.owner;
ServerPlayer onlinePlayer = PlayerDataManager.getHandle(player);
// Set owner to new player.
this.owner = onlinePlayer;
// Set player's ender chest contents to our modified contents.
PlayerEnderChestContainer onlineEnderChest = onlinePlayer.getEnderChestInventory();
for (int i = 0; i < onlineEnderChest.getContainerSize(); ++i) {
onlineEnderChest.setItem(i, this.items.get(i));
}
// Set our item array to the new inventory's array.
this.items = onlineEnderChest.items;
// Add viewers to new inventory.
onlineEnderChest.transaction.addAll(offlinePlayer.getEnderChestInventory().transaction);
this.playerOnline = true;
}
@Override
public @NotNull org.bukkit.entity.Player getPlayer() {
return owner.getBukkitEntity();
}
@Override
public void setChanged() {
this.owner.getEnderChestInventory().setChanged();
}
@Override
public List<ItemStack> getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.owner.getEnderChestInventory().onOpen(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.owner.getEnderChestInventory().onClose(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.owner.getEnderChestInventory().getViewers();
}
@Override
public boolean stillValid(Player player) {
return true;
}
@Override
public void setActiveChest(EnderChestBlockEntity enderChest) {
this.owner.getEnderChestInventory().setActiveChest(enderChest);
}
@Override
public boolean isActiveChest(EnderChestBlockEntity enderChest) {
return this.owner.getEnderChestInventory().isActiveChest(enderChest);
}
@Override
public int getMaxStackSize() {
return this.owner.getEnderChestInventory().getMaxStackSize();
}
@Override
public void setMaxStackSize(int i) {
this.owner.getEnderChestInventory().setMaxStackSize(i);
}
@Override
public InventoryHolder getOwner() {
return this.owner.getEnderChestInventory().getOwner();
}
@Override
public @Nullable Location getLocation() {
return null;
}
@Override
public void addListener(ContainerListener listener) {
this.owner.getEnderChestInventory().addListener(listener);
}
@Override
public void removeListener(ContainerListener listener) {
this.owner.getEnderChestInventory().removeListener(listener);
}
@Override
public ItemStack getItem(int i) {
return i >= 0 && i < this.items.size() ? this.items.get(i) : ItemStack.EMPTY;
}
@Override
public ItemStack removeItem(int i, int j) {
ItemStack itemstack = ContainerHelper.removeItem(this.items, i, j);
if (!itemstack.isEmpty()) {
this.setChanged();
}
return itemstack;
}
@Override
public ItemStack addItem(ItemStack itemstack) {
ItemStack localItem = itemstack.copy();
this.moveItemToOccupiedSlotsWithSameType(localItem);
if (localItem.isEmpty()) {
return ItemStack.EMPTY;
} else {
this.moveItemToEmptySlots(localItem);
return localItem.isEmpty() ? ItemStack.EMPTY : localItem;
}
}
@Override
public boolean canAddItem(ItemStack itemstack) {
for (ItemStack itemstack1 : this.items) {
if (itemstack1.isEmpty() || ItemStack.isSameItemSameTags(itemstack1, itemstack) && itemstack1.getCount() < itemstack1.getMaxStackSize()) {
return true;
}
}
return false;
}
private void moveItemToEmptySlots(ItemStack itemstack) {
for(int i = 0; i < this.getContainerSize(); ++i) {
ItemStack localItem = this.getItem(i);
if (localItem.isEmpty()) {
this.setItem(i, itemstack.copy());
itemstack.setCount(0);
return;
}
}
}
private void moveItemToOccupiedSlotsWithSameType(ItemStack itemstack) {
for(int i = 0; i < this.getContainerSize(); ++i) {
ItemStack localItem = this.getItem(i);
if (ItemStack.isSameItemSameTags(localItem, itemstack)) {
this.moveItemsBetweenStacks(itemstack, localItem);
if (itemstack.isEmpty()) {
return;
}
}
}
}
private void moveItemsBetweenStacks(ItemStack itemstack, ItemStack itemstack1) {
int i = Math.min(this.getMaxStackSize(), itemstack1.getMaxStackSize());
int j = Math.min(itemstack.getCount(), i - itemstack1.getCount());
if (j > 0) {
itemstack1.grow(j);
itemstack.shrink(j);
this.setChanged();
}
}
@Override
public ItemStack removeItemNoUpdate(int i) {
ItemStack itemstack = this.items.get(i);
if (itemstack.isEmpty()) {
return ItemStack.EMPTY;
} else {
this.items.set(i, ItemStack.EMPTY);
return itemstack;
}
}
@Override
public void setItem(int i, ItemStack itemstack) {
this.items.set(i, itemstack);
if (!itemstack.isEmpty() && itemstack.getCount() > this.getMaxStackSize()) {
itemstack.setCount(this.getMaxStackSize());
}
this.setChanged();
}
@Override
public int getContainerSize() {
return this.owner.getEnderChestInventory().getContainerSize();
}
@Override
public boolean isEmpty() {
return this.items.stream().allMatch(ItemStack::isEmpty);
}
@Override
public void startOpen(Player player) {
}
@Override
public void stopOpen(Player player) {
}
@Override
public boolean canPlaceItem(int i, ItemStack itemstack) {
return true;
}
@Override
public void clearContent() {
this.items.clear();
this.setChanged();
}
@Override
public void fillStackedContents(StackedContents stackedContents) {
for (ItemStack itemstack : this.items) {
stackedContents.accountStack(itemstack);
}
}
@Override
public List<ItemStack> removeAllItems() {
List<ItemStack> list = this.items.stream().filter(Predicate.not(ItemStack::isEmpty)).collect(Collectors.toList());
this.clearContent();
return list;
}
@Override
public ItemStack removeItemType(Item item, int i) {
ItemStack itemstack = new ItemStack(item, 0);
for(int j = this.getContainerSize() - 1; j >= 0; --j) {
ItemStack localItem = this.getItem(j);
if (localItem.getItem().equals(item)) {
int k = i - itemstack.getCount();
ItemStack splitItem = localItem.split(k);
itemstack.grow(splitItem.getCount());
if (itemstack.getCount() == i) {
break;
}
}
}
if (!itemstack.isEmpty()) {
this.setChanged();
}
return itemstack;
}
@Override
public String toString() {
return this.items.stream().filter((itemStack) -> !itemStack.isEmpty()).toList().toString();
}
@Override
public void fromTag(ListTag listTag) {
for (int i = 0; i < this.getContainerSize(); ++i) {
this.setItem(i, ItemStack.EMPTY);
}
for (int i = 0; i < listTag.size(); ++i) {
CompoundTag compoundTag = listTag.getCompound(i);
int j = compoundTag.getByte("Slot") & 255;
if (j < this.getContainerSize()) {
this.setItem(j, ItemStack.of(compoundTag));
}
}
}
}
@@ -0,0 +1,807 @@
/*
* Copyright (C) 2011-2023 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_20_R3;
import com.google.common.collect.ImmutableList;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import net.minecraft.CrashReport;
import net.minecraft.CrashReportCategory;
import net.minecraft.ReportedException;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.DamageTypeTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.Container;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_20_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_20_R3.inventory.CraftInventory;
import org.bukkit.entity.HumanEntity;
import org.bukkit.inventory.InventoryHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class SpecialPlayerInventory extends Inventory implements ISpecialPlayerInventory {
private final CraftInventory inventory;
private boolean playerOnline;
private Player player;
private NonNullList<ItemStack> items;
private NonNullList<ItemStack> armor;
private NonNullList<ItemStack> offhand;
private List<NonNullList<ItemStack>> compartments;
public SpecialPlayerInventory(@NotNull org.bukkit.entity.Player bukkitPlayer, @NotNull Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.inventory = new CraftInventory(this);
this.playerOnline = online;
this.player = super.player;
this.selected = player.getInventory().selected;
this.items = this.player.getInventory().items;
this.armor = this.player.getInventory().armor;
this.offhand = this.player.getInventory().offhand;
this.compartments = ImmutableList.of(this.items, this.armor, this.offhand);
}
@Override
public void setPlayerOnline(@NotNull org.bukkit.entity.Player player) {
if (this.playerOnline) {
return;
}
Player offlinePlayer = this.player;
Player onlinePlayer = PlayerDataManager.getHandle(player);
onlinePlayer.getInventory().transaction.addAll(this.transaction);
// Set owner to new player.
this.player = onlinePlayer;
// Set player's inventory contents to our modified contents.
Inventory onlineInventory = onlinePlayer.getInventory();
for (int i = 0; i < getContainerSize(); ++i) {
onlineInventory.setItem(i, getRawItem(i));
}
onlineInventory.selected = this.selected;
// Set our item arrays to the new inventory's arrays.
this.items = onlineInventory.items;
this.armor = onlineInventory.armor;
this.offhand = onlineInventory.offhand;
this.compartments = ImmutableList.of(this.items, this.armor, this.offhand);
// Add existing viewers to new viewer list.
Inventory offlineInventory = offlinePlayer.getInventory();
// Remove self from listing - player is always a viewer of their own inventory, prevent duplicates.
offlineInventory.transaction.remove(offlinePlayer.getBukkitEntity());
onlineInventory.transaction.addAll(offlineInventory.transaction);
this.playerOnline = true;
}
@Override
public @NotNull CraftInventory getBukkitInventory() {
return this.inventory;
}
@Override
public void setPlayerOffline() {
this.playerOnline = false;
}
@Override
public @NotNull HumanEntity getPlayer() {
return this.player.getBukkitEntity();
}
private @NotNull ItemStack getRawItem(int i) {
if (i < 0) {
return ItemStack.EMPTY;
}
NonNullList<ItemStack> list;
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
list = iterator.next();
if (i < list.size()) {
return list.get(i);
}
}
return ItemStack.EMPTY;
}
private void setRawItem(int i, @NotNull ItemStack itemStack) {
if (i < 0) {
return;
}
NonNullList<ItemStack> list;
for (Iterator<NonNullList<ItemStack>> iterator = this.compartments.iterator(); iterator.hasNext(); i -= list.size()) {
list = iterator.next();
if (i < list.size()) {
list.set(i, itemStack);
}
}
}
private record IndexedCompartment(@Nullable NonNullList<ItemStack> compartment, int index) {}
private @NotNull SpecialPlayerInventory.IndexedCompartment getIndexedContent(int index) {
if (index < items.size()) {
return new IndexedCompartment(items, getReversedItemSlotNum(index));
}
index -= items.size();
if (index < armor.size()) {
return new IndexedCompartment(armor, getReversedArmorSlotNum(index));
}
index -= armor.size();
if (index < offhand.size()) {
return new IndexedCompartment(offhand, index);
}
index -= offhand.size();
return new IndexedCompartment(null, index);
}
private int getReversedArmorSlotNum(final int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
private int getReversedItemSlotNum(final int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private boolean contains(Predicate<ItemStack> predicate) {
return this.compartments.stream().flatMap(NonNullList::stream).anyMatch(predicate);
}
@Override
public List<ItemStack> getArmorContents() {
return this.armor;
}
@Override
public void onOpen(CraftHumanEntity who) {
this.player.getInventory().onOpen(who);
}
@Override
public void onClose(CraftHumanEntity who) {
this.player.getInventory().onClose(who);
}
@Override
public List<HumanEntity> getViewers() {
return this.player.getInventory().getViewers();
}
@Override
public InventoryHolder getOwner() {
return this.player.getBukkitEntity();
}
@Override
public int getMaxStackSize() {
return this.player.getInventory().getMaxStackSize();
}
@Override
public void setMaxStackSize(int size) {
this.player.getInventory().setMaxStackSize(size);
}
@Override
public Location getLocation() {
return this.player.getBukkitEntity().getLocation();
}
@Override
public boolean hasCustomName() {
return false;
}
@Override
public List<ItemStack> getContents() {
return this.compartments.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
@Override
public ItemStack getSelected() {
return isHotbarSlot(this.selected) ? this.items.get(this.selected) : ItemStack.EMPTY;
}
private boolean hasRemainingSpaceForItem(ItemStack itemstack, ItemStack itemstack1) {
return !itemstack.isEmpty() && ItemStack.isSameItemSameTags(itemstack, itemstack1) && itemstack.isStackable() && itemstack.getCount() < itemstack.getMaxStackSize() && itemstack.getCount() < this.getMaxStackSize();
}
@Override
public int canHold(ItemStack itemstack) {
int remains = itemstack.getCount();
for (int i = 0; i < this.items.size(); ++i) {
ItemStack itemstack1 = this.getRawItem(i);
if (itemstack1.isEmpty()) {
return itemstack.getCount();
}
if (this.hasRemainingSpaceForItem(itemstack1, itemstack)) {
remains -= (itemstack1.getMaxStackSize() < this.getMaxStackSize() ? itemstack1.getMaxStackSize() : this.getMaxStackSize()) - itemstack1.getCount();
}
if (remains <= 0) {
return itemstack.getCount();
}
}
ItemStack offhandItemStack = this.getRawItem(this.items.size() + this.armor.size());
if (this.hasRemainingSpaceForItem(offhandItemStack, itemstack)) {
remains -= (offhandItemStack.getMaxStackSize() < this.getMaxStackSize() ? offhandItemStack.getMaxStackSize() : this.getMaxStackSize()) - offhandItemStack.getCount();
}
return remains <= 0 ? itemstack.getCount() : itemstack.getCount() - remains;
}
@Override
public int getFreeSlot() {
for(int i = 0; i < this.items.size(); ++i) {
if (this.items.get(i).isEmpty()) {
return i;
}
}
return -1;
}
@Override
public void setPickedItem(ItemStack itemstack) {
int i = this.findSlotMatchingItem(itemstack);
if (isHotbarSlot(i)) {
this.selected = i;
} else if (i == -1) {
this.selected = this.getSuitableHotbarSlot();
if (!this.items.get(this.selected).isEmpty()) {
int j = this.getFreeSlot();
if (j != -1) {
this.items.set(j, this.items.get(this.selected));
}
}
this.items.set(this.selected, itemstack);
} else {
this.pickSlot(i);
}
}
@Override
public void pickSlot(int i) {
this.selected = this.getSuitableHotbarSlot();
ItemStack itemstack = this.items.get(this.selected);
this.items.set(this.selected, this.items.get(i));
this.items.set(i, itemstack);
}
@Override
public int findSlotMatchingItem(ItemStack itemstack) {
for(int i = 0; i < this.items.size(); ++i) {
if (!this.items.get(i).isEmpty() && ItemStack.isSameItemSameTags(itemstack, this.items.get(i))) {
return i;
}
}
return -1;
}
@Override
public int findSlotMatchingUnusedItem(ItemStack itemStack) {
for(int i = 0; i < this.items.size(); ++i) {
ItemStack localItem = this.items.get(i);
if (!this.items.get(i).isEmpty() && ItemStack.isSameItemSameTags(itemStack, this.items.get(i)) && !this.items.get(i).isDamaged() && !localItem.isEnchanted() && !localItem.hasCustomHoverName()) {
return i;
}
}
return -1;
}
@Override
public int getSuitableHotbarSlot() {
int i;
int j;
for(j = 0; j < 9; ++j) {
i = (this.selected + j) % 9;
if (this.items.get(i).isEmpty()) {
return i;
}
}
for(j = 0; j < 9; ++j) {
i = (this.selected + j) % 9;
if (!this.items.get(i).isEnchanted()) {
return i;
}
}
return this.selected;
}
@Override
public void swapPaint(double d0) {
if (d0 > 0.0D) {
d0 = 1.0D;
}
if (d0 < 0.0D) {
d0 = -1.0D;
}
this.selected = (int) (this.selected - d0);
while (this.selected < 0) {
this.selected += 9;
}
while(this.selected >= 9) {
this.selected -= 9;
}
}
@Override
public int clearOrCountMatchingItems(Predicate<ItemStack> predicate, int i, Container container) {
byte b0 = 0;
boolean flag = i == 0;
int j = b0 + ContainerHelper.clearOrCountMatchingItems(this, predicate, i - b0, flag);
j += ContainerHelper.clearOrCountMatchingItems(container, predicate, i - j, flag);
ItemStack itemstack = this.player.containerMenu.getCarried();
j += ContainerHelper.clearOrCountMatchingItems(itemstack, predicate, i - j, flag);
if (itemstack.isEmpty()) {
this.player.containerMenu.setCarried(ItemStack.EMPTY);
}
return j;
}
private int addResource(ItemStack itemstack) {
int i = this.getSlotWithRemainingSpace(itemstack);
if (i == -1) {
i = this.getFreeSlot();
}
return i == -1 ? itemstack.getCount() : this.addResource(i, itemstack);
}
private int addResource(int i, ItemStack itemstack) {
Item item = itemstack.getItem();
int j = itemstack.getCount();
ItemStack localItemStack = this.getRawItem(i);
if (localItemStack.isEmpty()) {
localItemStack = new ItemStack(item, 0);
if (itemstack.hasTag()) {
// hasTag ensures tag not null
//noinspection ConstantConditions
localItemStack.setTag(itemstack.getTag().copy());
}
this.setRawItem(i, localItemStack);
}
int k = Math.min(j, localItemStack.getMaxStackSize() - localItemStack.getCount());
if (k > this.getMaxStackSize() - localItemStack.getCount()) {
k = this.getMaxStackSize() - localItemStack.getCount();
}
if (k != 0) {
j -= k;
localItemStack.grow(k);
localItemStack.setPopTime(5);
}
return j;
}
@Override
public int getSlotWithRemainingSpace(ItemStack itemstack) {
if (this.hasRemainingSpaceForItem(this.getRawItem(this.selected), itemstack)) {
return this.selected;
} else if (this.hasRemainingSpaceForItem(this.getRawItem(40), itemstack)) {
return 40;
} else {
for(int i = 0; i < this.items.size(); ++i) {
if (this.hasRemainingSpaceForItem(this.items.get(i), itemstack)) {
return i;
}
}
return -1;
}
}
@Override
public void tick() {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
if (!compartment.get(i).isEmpty()) {
compartment.get(i).inventoryTick(this.player.level(), this.player, i, this.selected == i);
}
}
}
}
@Override
public boolean add(ItemStack itemStack) {
return this.add(-1, itemStack);
}
@Override
public boolean add(int i, ItemStack itemStack) {
if (itemStack.isEmpty()) {
return false;
} else {
try {
if (itemStack.isDamaged()) {
if (i == -1) {
i = this.getFreeSlot();
}
if (i >= 0) {
this.items.set(i, itemStack.copy());
this.items.get(i).setPopTime(5);
itemStack.setCount(0);
return true;
} else if (this.player.getAbilities().instabuild) {
itemStack.setCount(0);
return true;
} else {
return false;
}
} else {
int j;
do {
j = itemStack.getCount();
if (i == -1) {
itemStack.setCount(this.addResource(itemStack));
} else {
itemStack.setCount(this.addResource(i, itemStack));
}
} while(!itemStack.isEmpty() && itemStack.getCount() < j);
if (itemStack.getCount() == j && this.player.getAbilities().instabuild) {
itemStack.setCount(0);
return true;
} else {
return itemStack.getCount() < j;
}
}
} catch (Throwable var6) {
CrashReport crashReport = CrashReport.forThrowable(var6, "Adding item to inventory");
CrashReportCategory crashReportCategory = crashReport.addCategory("Item being added");
crashReportCategory.setDetail("Item ID", Item.getId(itemStack.getItem()));
crashReportCategory.setDetail("Item data", itemStack.getDamageValue());
crashReportCategory.setDetail("Item name", () -> itemStack.getHoverName().getString());
throw new ReportedException(crashReport);
}
}
}
@Override
public void placeItemBackInInventory(ItemStack itemStack) {
this.placeItemBackInInventory(itemStack, true);
}
@Override
public void placeItemBackInInventory(ItemStack itemStack, boolean flag) {
while(true) {
if (!itemStack.isEmpty()) {
int i = this.getSlotWithRemainingSpace(itemStack);
if (i == -1) {
i = this.getFreeSlot();
}
if (i != -1) {
int j = itemStack.getMaxStackSize() - this.getRawItem(i).getCount();
if (this.add(i, itemStack.split(j)) && flag && this.player instanceof ServerPlayer) {
((ServerPlayer)this.player).connection.send(new ClientboundContainerSetSlotPacket(-2, 0, i, this.getRawItem(i)));
}
continue;
}
this.player.drop(itemStack, false);
}
return;
}
}
@Override
public ItemStack removeItem(int rawIndex, final int j) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null
|| indexedCompartment.compartment().get(indexedCompartment.index()).isEmpty()) {
return ItemStack.EMPTY;
}
return ContainerHelper.removeItem(indexedCompartment.compartment(), indexedCompartment.index(), j);
}
@Override
public void removeItem(ItemStack itemStack) {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
if (compartment.get(i) == itemStack) {
compartment.set(i, ItemStack.EMPTY);
break;
}
}
}
}
@Override
public ItemStack removeItemNoUpdate(int rawIndex) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
return ItemStack.EMPTY;
}
ItemStack removed = indexedCompartment.compartment().set(indexedCompartment.index(), ItemStack.EMPTY);
if (removed.isEmpty()) {
return ItemStack.EMPTY;
}
return removed;
}
@Override
public void setItem(int rawIndex, final ItemStack itemStack) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
this.player.drop(itemStack, true);
return;
}
indexedCompartment.compartment().set(indexedCompartment.index(), itemStack);
}
@Override
public float getDestroySpeed(BlockState blockState) {
return this.items.get(this.selected).getDestroySpeed(blockState);
}
@Override
public ListTag save(ListTag listTag) {
for (int i = 0; i < this.items.size(); ++i) {
if (!this.items.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)i);
this.items.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
for (int i = 0; i < this.armor.size(); ++i) {
if (!this.armor.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)(i + 100));
this.armor.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
for (int i = 0; i < this.offhand.size(); ++i) {
if (!this.offhand.get(i).isEmpty()) {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putByte("Slot", (byte)(i + 150));
this.offhand.get(i).save(compoundTag);
listTag.add(compoundTag);
}
}
return listTag;
}
@Override
public void load(ListTag listTag) {
this.items.clear();
this.armor.clear();
this.offhand.clear();
for(int i = 0; i < listTag.size(); ++i) {
CompoundTag compoundTag = listTag.getCompound(i);
int j = compoundTag.getByte("Slot") & 255;
ItemStack itemstack = ItemStack.of(compoundTag);
if (!itemstack.isEmpty()) {
if (j < this.items.size()) {
this.items.set(j, itemstack);
} else if (j >= 100 && j < this.armor.size() + 100) {
this.armor.set(j - 100, itemstack);
} else if (j >= 150 && j < this.offhand.size() + 150) {
this.offhand.set(j - 150, itemstack);
}
}
}
}
@Override
public int getContainerSize() {
return 45;
}
@Override
public boolean isEmpty() {
return !contains(itemStack -> !itemStack.isEmpty());
}
@Override
public ItemStack getItem(int rawIndex) {
IndexedCompartment indexedCompartment = getIndexedContent(rawIndex);
if (indexedCompartment.compartment() == null) {
return ItemStack.EMPTY;
}
return indexedCompartment.compartment().get(indexedCompartment.index());
}
@Override
public Component getName() {
return this.player.getName();
}
@Override
public ItemStack getArmor(int index) {
return this.armor.get(index);
}
@Override
public void hurtArmor(DamageSource damagesource, float damage, int[] armorIndices) {
if (damage > 0.0F) {
damage /= 4.0F;
if (damage < 1.0F) {
damage = 1.0F;
}
for (int index : armorIndices) {
ItemStack itemstack = this.armor.get(index);
if ((!damagesource.is(DamageTypeTags.IS_FIRE) || !itemstack.getItem().isFireResistant()) && itemstack.getItem() instanceof ArmorItem) {
itemstack.hurtAndBreak((int) damage, this.player, localPlayer -> localPlayer.broadcastBreakEvent(EquipmentSlot.byTypeAndIndex(EquipmentSlot.Type.ARMOR, index)));
}
}
}
}
@Override
public void dropAll() {
for (NonNullList<ItemStack> compartment : this.compartments) {
for (int i = 0; i < compartment.size(); ++i) {
ItemStack itemstack = compartment.get(i);
if (!itemstack.isEmpty()) {
this.player.drop(itemstack, true, false);
compartment.set(i, ItemStack.EMPTY);
}
}
}
}
@Override
public void setChanged() {
super.setChanged();
}
@Override
public int getTimesChanged() {
return super.getTimesChanged();
}
@Override
public boolean stillValid(Player player) {
return true;
}
@Override
public boolean contains(ItemStack itemstack) {
return contains(itemStack -> itemStack.isEmpty() && itemStack.is(itemstack.getItem()));
}
@Override
public boolean contains(TagKey<Item> tagKey) {
return contains(itemStack -> !itemStack.isEmpty() && itemStack.is(tagKey));
}
@Override
public void replaceWith(Inventory inventory) {
Function<Integer, ItemStack> getter;
if (inventory instanceof SpecialPlayerInventory specialPlayerInventory) {
getter = specialPlayerInventory::getRawItem;
} else {
getter = inventory::getItem;
}
for(int i = 0; i < this.getContainerSize(); ++i) {
this.setRawItem(i, getter.apply(i));
}
this.selected = inventory.selected;
}
@Override
public void clearContent() {
for (NonNullList<ItemStack> compartment : this.compartments) {
compartment.clear();
}
}
@Override
public void fillStackedContents(StackedContents stackedContents) {
for (ItemStack itemstack : this.items) {
stackedContents.accountSimpleStack(itemstack);
}
}
@Override
public ItemStack removeFromSelected(boolean dropWholeStack) {
ItemStack itemstack = this.getSelected();
return itemstack.isEmpty() ? ItemStack.EMPTY : this.removeItem(this.selected, dropWholeStack ? itemstack.getCount() : 1);
}
}
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_4_R1</artifactId>
<name>OpenInvAdapter1_4_R1</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.4.7-R1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,171 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_4_R1.AxisAlignedBB;
import net.minecraft.server.v1_4_R1.BlockEnderChest;
import net.minecraft.server.v1_4_R1.Container;
import net.minecraft.server.v1_4_R1.EntityOcelot;
import net.minecraft.server.v1_4_R1.EntityPlayer;
import net.minecraft.server.v1_4_R1.IInventory;
import net.minecraft.server.v1_4_R1.InventoryEnderChest;
import net.minecraft.server.v1_4_R1.InventoryLargeChest;
import net.minecraft.server.v1_4_R1.Packet100OpenWindow;
import net.minecraft.server.v1_4_R1.TileEntityChest;
import net.minecraft.server.v1_4_R1.TileEntityEnderChest;
import net.minecraft.server.v1_4_R1.World;
import org.bukkit.craftbukkit.v1_4_R1.event.CraftEventFactory;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
IInventory inventory = (IInventory) tile;
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), inventory);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), inventory);
}
// AnyChest only
if (!silentchest) {
player.openContainer(inventory);
return true;
}
// SilentChest
try {
// Call InventoryOpenEvent
Container container = new SilentContainerChest(player.inventory, inventory);
container = CraftEventFactory.callInventoryOpenEvent(player, container);
if (container == null) {
return false;
}
// Open window
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new Packet100OpenWindow(windowId, 0, inventory.getName(), inventory.getSize()));
player.activeContainer = container;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
return true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent container.");
return false;
}
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_4_R1.IInventory;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,102 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import java.util.Arrays;
import java.util.Collection;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_4_R1.EntityPlayer;
import net.minecraft.server.v1_4_R1.MinecraftServer;
import net.minecraft.server.v1_4_R1.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_4_R1.CraftServer;
import org.bukkit.craftbukkit.v1_4_R1.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Arrays.asList(Bukkit.getOnlinePlayers());
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().f(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import net.minecraft.server.v1_4_R1.ContainerChest;
import net.minecraft.server.v1_4_R1.EntityHuman;
import net.minecraft.server.v1_4_R1.IInventory;
import net.minecraft.server.v1_4_R1.ItemStack;
import net.minecraft.server.v1_4_R1.PlayerInventory;
class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.f();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}
@@ -1,130 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import net.minecraft.server.v1_4_R1.EntityPlayer;
import net.minecraft.server.v1_4_R1.IInventory;
import net.minecraft.server.v1_4_R1.InventoryEnderChest;
import net.minecraft.server.v1_4_R1.InventorySubcontainer;
import net.minecraft.server.v1_4_R1.ItemStack;
import org.bukkit.craftbukkit.v1_4_R1.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_4_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player player, Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.owner = nmsPlayer.getBukkitEntity();
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.owner = nmsPlayer.getBukkitEntity();
InventoryEnderChest playerEnderChest = nmsPlayer.getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}
@@ -1,235 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_4_R1;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_4_R1.ItemStack;
import net.minecraft.server.v1_4_R1.PlayerInventory;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[5];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
this.items = player.inventory.items;
this.armor = player.inventory.armor;
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = PlayerDataManager.getHandle(player);
this.player.inventory.items = this.items;
this.player.inventory.armor = this.armor;
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 5;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
}
else {
itemstack = is[i].a(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
else {
return null;
}
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
else {
return null;
}
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
}
else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
}
else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
// Effects
if (is == this.extra) {
player.drop(itemstack);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27)
return i - 27;
else
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0)
return 3;
if (i == 1)
return 2;
if (i == 2)
return 1;
if (i == 3)
return 0;
else
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
}
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_5_R2</artifactId>
<name>OpenInvAdapter1_5_R2</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.5.1-R0.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,171 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R2;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_5_R2.AxisAlignedBB;
import net.minecraft.server.v1_5_R2.BlockEnderChest;
import net.minecraft.server.v1_5_R2.Container;
import net.minecraft.server.v1_5_R2.EntityOcelot;
import net.minecraft.server.v1_5_R2.EntityPlayer;
import net.minecraft.server.v1_5_R2.IInventory;
import net.minecraft.server.v1_5_R2.InventoryEnderChest;
import net.minecraft.server.v1_5_R2.InventoryLargeChest;
import net.minecraft.server.v1_5_R2.Packet100OpenWindow;
import net.minecraft.server.v1_5_R2.TileEntityChest;
import net.minecraft.server.v1_5_R2.TileEntityEnderChest;
import net.minecraft.server.v1_5_R2.World;
import org.bukkit.craftbukkit.v1_5_R2.event.CraftEventFactory;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
IInventory inventory = (IInventory) tile;
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), inventory);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), inventory);
}
// AnyChest only
if (!silentchest) {
player.openContainer(inventory);
return true;
}
// SilentChest
try {
// Call InventoryOpenEvent
Container container = new SilentContainerChest(player.inventory, inventory);
container = CraftEventFactory.callInventoryOpenEvent(player, container);
if (container == null) {
return false;
}
// Open window
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new Packet100OpenWindow(windowId, 0, inventory.getName(), inventory.getSize(), true));
player.activeContainer = container;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
return true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent container.");
return false;
}
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R2;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_5_R2.IInventory;
import org.bukkit.craftbukkit.v1_5_R2.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,101 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R2;
import java.util.Arrays;
import java.util.Collection;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_5_R2.EntityPlayer;
import net.minecraft.server.v1_5_R2.MinecraftServer;
import net.minecraft.server.v1_5_R2.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_5_R2.CraftServer;
import org.bukkit.craftbukkit.v1_5_R2.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Arrays.asList(Bukkit.getOnlinePlayers());
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().f(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R2;
import net.minecraft.server.v1_5_R2.ContainerChest;
import net.minecraft.server.v1_5_R2.EntityHuman;
import net.minecraft.server.v1_5_R2.IInventory;
import net.minecraft.server.v1_5_R2.ItemStack;
import net.minecraft.server.v1_5_R2.PlayerInventory;
class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.g();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}
@@ -1,131 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R2;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import net.minecraft.server.v1_5_R2.EntityPlayer;
import net.minecraft.server.v1_5_R2.IInventory;
import net.minecraft.server.v1_5_R2.InventoryEnderChest;
import net.minecraft.server.v1_5_R2.InventorySubcontainer;
import net.minecraft.server.v1_5_R2.ItemStack;
import org.bukkit.craftbukkit.v1_5_R2.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_5_R2.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_5_R2.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player player, Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().c(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.owner = nmsPlayer.getBukkitEntity();
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.owner = nmsPlayer.getBukkitEntity();
InventoryEnderChest playerEnderChest = nmsPlayer.getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}
@@ -1,227 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R2;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_5_R2.ItemStack;
import net.minecraft.server.v1_5_R2.PlayerInventory;
import org.bukkit.craftbukkit.v1_5_R2.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[5];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
this.items = player.inventory.items;
this.armor = player.inventory.armor;
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = PlayerDataManager.getHandle(player);
this.player.inventory.items = this.items;
this.player.inventory.armor = this.armor;
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 5;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
} else {
itemstack = is[i].a(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
return null;
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
return null;
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
// Effects
if (is == this.extra) {
player.drop(itemstack);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
}
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_5_R3</artifactId>
<name>OpenInvAdapter1_5_R3</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.5.2-R1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,171 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R3;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_5_R3.AxisAlignedBB;
import net.minecraft.server.v1_5_R3.BlockEnderChest;
import net.minecraft.server.v1_5_R3.Container;
import net.minecraft.server.v1_5_R3.EntityOcelot;
import net.minecraft.server.v1_5_R3.EntityPlayer;
import net.minecraft.server.v1_5_R3.IInventory;
import net.minecraft.server.v1_5_R3.InventoryEnderChest;
import net.minecraft.server.v1_5_R3.InventoryLargeChest;
import net.minecraft.server.v1_5_R3.Packet100OpenWindow;
import net.minecraft.server.v1_5_R3.TileEntityChest;
import net.minecraft.server.v1_5_R3.TileEntityEnderChest;
import net.minecraft.server.v1_5_R3.World;
import org.bukkit.craftbukkit.v1_5_R3.event.CraftEventFactory;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
IInventory inventory = (IInventory) tile;
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), inventory);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), inventory);
}
// AnyChest only
if (!silentchest) {
player.openContainer(inventory);
return true;
}
// SilentChest
try {
// Call InventoryOpenEvent
Container container = new SilentContainerChest(player.inventory, inventory);
container = CraftEventFactory.callInventoryOpenEvent(player, container);
if (container == null) {
return false;
}
// Open window
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new Packet100OpenWindow(windowId, 0, inventory.getName(), inventory.getSize(), true));
player.activeContainer = container;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
return true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent container.");
return false;
}
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R3;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_5_R3.IInventory;
import org.bukkit.craftbukkit.v1_5_R3.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,101 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R3;
import java.util.Arrays;
import java.util.Collection;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_5_R3.EntityPlayer;
import net.minecraft.server.v1_5_R3.MinecraftServer;
import net.minecraft.server.v1_5_R3.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_5_R3.CraftServer;
import org.bukkit.craftbukkit.v1_5_R3.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Arrays.asList(Bukkit.getOnlinePlayers());
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R3;
import net.minecraft.server.v1_5_R3.ContainerChest;
import net.minecraft.server.v1_5_R3.EntityHuman;
import net.minecraft.server.v1_5_R3.IInventory;
import net.minecraft.server.v1_5_R3.ItemStack;
import net.minecraft.server.v1_5_R3.PlayerInventory;
class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.g();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}
@@ -1,131 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R3;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lishid.openinv.internal.ISpecialEnderChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import net.minecraft.server.v1_5_R3.EntityPlayer;
import net.minecraft.server.v1_5_R3.IInventory;
import net.minecraft.server.v1_5_R3.InventoryEnderChest;
import net.minecraft.server.v1_5_R3.InventorySubcontainer;
import net.minecraft.server.v1_5_R3.ItemStack;
import org.bukkit.craftbukkit.v1_5_R3.entity.CraftHumanEntity;
import org.bukkit.craftbukkit.v1_5_R3.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_5_R3.inventory.CraftInventory;
public class SpecialEnderChest extends InventorySubcontainer implements IInventory, ISpecialEnderChest {
private final InventoryEnderChest enderChest;
private final CraftInventory inventory = new CraftInventory(this);
private final List<HumanEntity> transaction = new ArrayList<HumanEntity>();
private boolean playerOnline;
private CraftPlayer owner;
private int maxStack = MAX_STACK;
public SpecialEnderChest(Player player, Boolean online) {
super(PlayerDataManager.getHandle(player).getEnderChest().getName(),
PlayerDataManager.getHandle(player).getEnderChest().c(),
PlayerDataManager.getHandle(player).getEnderChest().getSize());
this.playerOnline = online;
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.enderChest = nmsPlayer.getEnderChest();
this.owner = nmsPlayer.getBukkitEntity();
this.items = enderChest.getContents();
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
try {
EntityPlayer nmsPlayer = PlayerDataManager.getHandle(player);
this.owner = nmsPlayer.getBukkitEntity();
InventoryEnderChest playerEnderChest = nmsPlayer.getEnderChest();
Field field = playerEnderChest.getClass().getField("items");
field.setAccessible(true);
field.set(playerEnderChest, this.items);
} catch (Exception e) {}
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
return this.items;
}
@Override
public void onOpen(CraftHumanEntity who) {
transaction.add(who);
}
@Override
public void onClose(CraftHumanEntity who) {
transaction.remove(who);
}
@Override
public List<HumanEntity> getViewers() {
return transaction;
}
@Override
public InventoryHolder getOwner() {
return this.owner;
}
@Override
public void setMaxStackSize(int size) {
maxStack = size;
}
@Override
public int getMaxStackSize() {
return maxStack;
}
@Override
public void update() {
super.update();
enderChest.update();
}
}
@@ -1,227 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_5_R3;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_5_R3.ItemStack;
import net.minecraft.server.v1_5_R3.PlayerInventory;
import org.bukkit.craftbukkit.v1_5_R3.inventory.CraftInventory;
public class SpecialPlayerInventory extends PlayerInventory implements ISpecialPlayerInventory {
private final ItemStack[] extra = new ItemStack[5];
private final CraftInventory inventory = new CraftInventory(this);
private boolean playerOnline;
public SpecialPlayerInventory(Player bukkitPlayer, Boolean online) {
super(PlayerDataManager.getHandle(bukkitPlayer));
this.playerOnline = online;
this.items = player.inventory.items;
this.armor = player.inventory.armor;
}
@Override
public Inventory getBukkitInventory() {
return inventory;
}
@Override
public void setPlayerOnline(Player player) {
if (!playerOnline) {
this.player = PlayerDataManager.getHandle(player);
this.player.inventory.items = this.items;
this.player.inventory.armor = this.armor;
playerOnline = true;
}
}
@Override
public void setPlayerOffline() {
playerOnline = false;
}
@Override
public boolean isInUse() {
return !this.getViewers().isEmpty();
}
@Override
public ItemStack[] getContents() {
ItemStack[] contents = new ItemStack[getSize()];
System.arraycopy(items, 0, contents, 0, items.length);
System.arraycopy(armor, 0, contents, items.length, armor.length);
return contents;
}
@Override
public int getSize() {
return super.getSize() + 5;
}
@Override
public ItemStack getItem(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
return is[i];
}
@Override
public ItemStack splitStack(int i, int j) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack;
if (is[i].count <= j) {
itemstack = is[i];
is[i] = null;
return itemstack;
} else {
itemstack = is[i].a(j);
if (is[i].count == 0) {
is[i] = null;
}
return itemstack;
}
}
return null;
}
@Override
public ItemStack splitWithoutUpdate(int i) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
if (is[i] != null) {
ItemStack itemstack = is[i];
is[i] = null;
return itemstack;
}
return null;
}
@Override
public void setItem(int i, ItemStack itemstack) {
ItemStack[] is = this.items;
if (i >= is.length) {
i -= is.length;
is = this.armor;
} else {
i = getReversedItemSlotNum(i);
}
if (i >= is.length) {
i -= is.length;
is = this.extra;
} else if (is == this.armor) {
i = getReversedArmorSlotNum(i);
}
// Effects
if (is == this.extra) {
player.drop(itemstack);
itemstack = null;
}
is[i] = itemstack;
player.defaultContainer.b();
}
private int getReversedItemSlotNum(int i) {
if (i >= 27) {
return i - 27;
}
return i + 9;
}
private int getReversedArmorSlotNum(int i) {
if (i == 0) {
return 3;
}
if (i == 1) {
return 2;
}
if (i == 2) {
return 1;
}
if (i == 3) {
return 0;
}
return i;
}
@Override
public String getName() {
if (player.getName().length() > 16) {
return player.getName().substring(0, 16);
}
return player.getName();
}
}
-44
View File
@@ -1,44 +0,0 @@
<!--
~ Copyright (C) 2011-2018 lishid. All rights reserved.
~
~ 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, version 3.
~
~ 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 <http://www.gnu.org/licenses/>.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lishid</groupId>
<artifactId>openinvinternal</artifactId>
<version>3.3.3</version>
</parent>
<artifactId>openinvadapter1_6_R1</artifactId>
<name>OpenInvAdapter1_6_R1</name>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.6.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.lishid</groupId>
<artifactId>openinvcommon</artifactId>
<version>3.3.3</version>
</dependency>
</dependencies>
</project>
@@ -1,171 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_6_R1;
import com.lishid.openinv.internal.IAnySilentContainer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_6_R1.AxisAlignedBB;
import net.minecraft.server.v1_6_R1.BlockEnderChest;
import net.minecraft.server.v1_6_R1.Container;
import net.minecraft.server.v1_6_R1.EntityOcelot;
import net.minecraft.server.v1_6_R1.EntityPlayer;
import net.minecraft.server.v1_6_R1.IInventory;
import net.minecraft.server.v1_6_R1.InventoryEnderChest;
import net.minecraft.server.v1_6_R1.InventoryLargeChest;
import net.minecraft.server.v1_6_R1.Packet100OpenWindow;
import net.minecraft.server.v1_6_R1.TileEntityChest;
import net.minecraft.server.v1_6_R1.TileEntityEnderChest;
import net.minecraft.server.v1_6_R1.World;
import org.bukkit.craftbukkit.v1_6_R1.event.CraftEventFactory;
public class AnySilentContainer implements IAnySilentContainer {
@Override
public boolean isAnySilentContainer(org.bukkit.block.Block block) {
return block.getType() == Material.ENDER_CHEST || block.getState() instanceof org.bukkit.block.Chest;
}
@Override
public boolean isAnyContainerNeeded(Player p, org.bukkit.block.Block block) {
// FOR REFERENCE, LOOK AT net.minecraft.server.BlockChest
EntityPlayer player = PlayerDataManager.getHandle(p);
World world = player.world;
if (block instanceof BlockEnderChest) {
// Ender chests are not blocked by ocelots.
return world.t(block.getX(), block.getY() + 1, block.getZ());
}
// If block or ocelot on top
if (isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ())) {
return true;
}
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
// If block next to chest is chest and has a block or ocelot on top
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() + 1);
} else if(world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
return isBlockedChest(world, block.getX(), block.getY() + 1, block.getZ() - 1);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() + 1, block.getY() + 1, block.getZ());
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
return isBlockedChest(world, block.getX() - 1, block.getY() + 1, block.getZ());
}
return false;
}
private boolean isBlockedChest(World world, int x, int y, int z) {
return world.t(x, y + 1, z) || hasOcelotOnTop(world, x, y, z);
}
private boolean hasOcelotOnTop(World world, int x, int y, int z) {
for (Object localEntity : world.a(EntityOcelot.class,
AxisAlignedBB.a(x, y + 1, z, x + 1, y + 2, z + 1))) {
EntityOcelot localEntityOcelot = (EntityOcelot) localEntity;
if (localEntityOcelot.isSitting()) {
return true;
}
}
return false;
}
@Override
public boolean activateContainer(Player p, boolean silentchest, org.bukkit.block.Block block) {
EntityPlayer player = PlayerDataManager.getHandle(p);
// Silent ender chest is API-only
if (silentchest && block.getType() == Material.ENDER_CHEST) {
p.openInventory(p.getEnderChest());
return true;
}
World world = player.world;
Object tile = world.getTileEntity(block.getX(), block.getY(), block.getZ());
if (tile == null) {
return false;
}
if (tile instanceof TileEntityEnderChest) {
// Anychest ender chest. See net.minecraft.server.BlockEnderChest
InventoryEnderChest enderChest = player.getEnderChest();
enderChest.a((TileEntityEnderChest) tile);
player.openContainer(enderChest);
return true;
}
if (!(tile instanceof IInventory)) {
return false;
}
IInventory inventory = (IInventory) tile;
int id = world.getTypeId(block.getX(), block.getY(), block.getZ());
if (world.getTypeId(block.getX(), block.getY(), block.getZ() + 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() + 1));
} else if (world.getTypeId(block.getX(), block.getY(), block.getZ() - 1) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX(), block.getY(), block.getZ() - 1), inventory);
} else if (world.getTypeId(block.getX() + 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", inventory, (TileEntityChest) world.getTileEntity(block.getX() + 1, block.getY(), block.getZ()));
} else if (world.getTypeId(block.getX() - 1, block.getY(), block.getZ()) == id) {
inventory = new InventoryLargeChest("container.chestDouble", (TileEntityChest) world.getTileEntity(block.getX() - 1, block.getY(), block.getZ()), inventory);
}
// AnyChest only
if (!silentchest) {
player.openContainer(inventory);
return true;
}
// SilentChest
try {
// Call InventoryOpenEvent
Container container = new SilentContainerChest(player.inventory, inventory);
container = CraftEventFactory.callInventoryOpenEvent(player, container);
if (container == null) {
return false;
}
// Open window
int windowId = player.nextContainerCounter();
player.playerConnection.sendPacket(new Packet100OpenWindow(windowId, 0, inventory.getName(), inventory.getSize(), true));
player.activeContainer = container;
player.activeContainer.windowId = windowId;
player.activeContainer.addSlotListener(player);
return true;
} catch (Exception e) {
e.printStackTrace();
p.sendMessage(ChatColor.RED + "Error while sending silent container.");
return false;
}
}
@Override
public void deactivateContainer(final Player bukkitPlayer) {}
}
@@ -1,78 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_6_R1;
import com.lishid.openinv.internal.IInventoryAccess;
import com.lishid.openinv.internal.ISpecialEnderChest;
import com.lishid.openinv.internal.ISpecialPlayerInventory;
import com.lishid.openinv.util.InternalAccessor;
import org.bukkit.inventory.Inventory;
import net.minecraft.server.v1_6_R1.IInventory;
import org.bukkit.craftbukkit.v1_6_R1.inventory.CraftInventory;
public class InventoryAccess implements IInventoryAccess {
@Override
public boolean isSpecialPlayerInventory(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialPlayerInventory;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialPlayerInventory;
}
@Override
public ISpecialPlayerInventory getSpecialPlayerInventory(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialPlayerInventory) {
return (SpecialPlayerInventory) inv;
}
return null;
}
@Override
public boolean isSpecialEnderChest(Inventory inventory) {
if (inventory instanceof CraftInventory) {
return ((CraftInventory) inventory).getInventory() instanceof ISpecialEnderChest;
}
return InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory) instanceof ISpecialEnderChest;
}
@Override
public ISpecialEnderChest getSpecialEnderChest(Inventory inventory) {
IInventory inv;
if (inventory instanceof CraftInventory) {
inv = ((CraftInventory) inventory).getInventory();
} else {
inv = InternalAccessor.grabFieldOfTypeFromObject(IInventory.class, inventory);
}
if (inv instanceof SpecialEnderChest) {
return (SpecialEnderChest) inv;
}
return null;
}
}
@@ -1,101 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_6_R1;
import java.util.Arrays;
import java.util.Collection;
import com.lishid.openinv.internal.IPlayerDataManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_6_R1.EntityPlayer;
import net.minecraft.server.v1_6_R1.MinecraftServer;
import net.minecraft.server.v1_6_R1.PlayerInteractManager;
import org.bukkit.craftbukkit.v1_6_R1.CraftServer;
import org.bukkit.craftbukkit.v1_6_R1.entity.CraftPlayer;
public class PlayerDataManager implements IPlayerDataManager {
@Override
public Player loadPlayer(OfflinePlayer offline) {
// Ensure the player has data
if (offline == null || !offline.hasPlayedBefore()) {
return null;
}
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
// Create an entity to load the player data
EntityPlayer entity = new EntityPlayer(server, server.getWorldServer(0), offline.getName(),
new PlayerInteractManager(server.getWorldServer(0)));
// Get the bukkit entity
Player target = (entity == null) ? null : entity.getBukkitEntity();
if (target != null) {
// Load data
target.loadData();
}
// Return the entity
return target;
}
@Override
public String getPlayerDataID(OfflinePlayer offline) {
return offline.getName();
}
@Override
public OfflinePlayer getPlayerByID(String identifier) {
OfflinePlayer player = Bukkit.getOfflinePlayer(identifier);
// Ensure player is a real player, otherwise return null
if (player == null || !player.hasPlayedBefore() && !player.isOnline()) {
return null;
}
return player;
}
@Override
public Collection<? extends Player> getOnlinePlayers() {
return Arrays.asList(Bukkit.getOnlinePlayers());
}
public static EntityPlayer getHandle(Player player) {
if (player instanceof CraftPlayer) {
return ((CraftPlayer) player).getHandle();
}
Server server = player.getServer();
EntityPlayer nmsPlayer = null;
if (server instanceof CraftServer) {
nmsPlayer = ((CraftServer) server).getHandle().getPlayer(player.getName());
}
if (nmsPlayer == null) {
// Could use reflection to examine fields, but it's honestly not worth the bother.
throw new RuntimeException("Unable to fetch EntityPlayer from provided Player implementation");
}
return nmsPlayer;
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (C) 2011-2018 lishid. All rights reserved.
*
* 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, version 3.
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.lishid.openinv.internal.v1_6_R1;
import net.minecraft.server.v1_6_R1.ContainerChest;
import net.minecraft.server.v1_6_R1.EntityHuman;
import net.minecraft.server.v1_6_R1.IInventory;
import net.minecraft.server.v1_6_R1.ItemStack;
import net.minecraft.server.v1_6_R1.PlayerInventory;
class SilentContainerChest extends ContainerChest {
public SilentContainerChest(IInventory i1, IInventory i2) {
super(i1, i2);
// Send close signal
i2.g();
}
@Override
public void b(EntityHuman entityHuman) {
// Don't send close signal twice, might screw up
PlayerInventory playerinventory = entityHuman.inventory;
if (playerinventory.getCarried() != null) {
ItemStack carried = playerinventory.getCarried();
playerinventory.setCarried(null);
entityHuman.drop(carried);
}
}
}
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more