1
0
mirror of https://github.com/mcMMO-Dev/mcMMO.git synced 2026-02-18 01:42:32 +01:00

Compare commits

..

249 Commits

Author SHA1 Message Date
nossr50
8a71ef5fc2 Revert "Update README.md"
This reverts commit 2cc24db615.
2023-08-19 14:39:38 -07:00
TechnicallyCoded
38e0810f93 Fix non-converted schedulers 2023-08-14 11:47:11 +02:00
Rockyers
34fefc1e70 Change Tick Conversion rates 2023-08-13 22:46:43 -07:00
Rockyers
7f64987585 Replace Bukkit schedulers in SaveTimerTask.java 2023-08-13 19:58:04 -07:00
Rockyers
0603faff33 Replace Bukkit schedulers in ScoreboardWrapper.java 2023-08-13 19:53:01 -07:00
Rockyers
dc8a9102fe Replace Bukkit schedulers in ScoreboardWrapper.java 2023-08-13 19:45:09 -07:00
Rockyers
247d1732e2 Replace Bukkit schedulers in CombatUtils.java 2023-08-13 19:41:35 -07:00
Rockyers
140cd61fd6 Replace Bukkit schedulers in UUIDUpdateAsyncTask.java 2023-08-13 19:39:26 -07:00
Rockyers
4a2020d4af Changes Misc.TICK_CONVERSION_FACTOR to millisecond equivalent of a TICK 2023-08-13 19:37:54 -07:00
Rockyers
7f756c25ab Replaced Bukkit schedulers in mcMMO.java 2023-08-13 19:32:22 -07:00
Rockyers
715f7217f9 Replaced DatabaseConversionTask scheduler 2023-08-13 19:23:43 -07:00
Rockyers
760e610226 Replaced WorldListener Bukkit schedular 2023-08-13 19:09:26 -07:00
Rockyers
e23e8d3884 Added FoliaLib to main class 2023-08-13 19:08:43 -07:00
Rockyers
a7762cd015 Added FoliaLib to the dependencies 2023-08-13 19:05:18 -07:00
Yomamaeatstoes
1781a996b9 Update mcMMO.java Plugin instance 2023-08-13 19:55:21 -04:00
Yomamaeatstoes
2cc24db615 Update README.md 2023-08-13 18:48:48 -04:00
Yomamaeatstoes
7e86701119 Update plugin.yml - Folia True 2023-08-11 23:54:18 -04:00
nossr50
24a57fab3d 2.1.222 2023-07-09 14:43:38 -07:00
nossr50
78596dc00e Glow Lichen nerf 2023-06-25 13:51:00 -07:00
nossr50
0b1b753d4c Merge branch 'master' of https://github.com/mcMMO-Dev/mcMMO 2023-06-25 13:47:25 -07:00
nossr50
3cbdcddcc1 Crossbows do not count as unarmed item with unarmed items setting 2023-06-25 13:47:04 -07:00
dependabot[bot]
25ecb6e1de Bump guava from 31.1-jre to 32.0.0-jre (#4903)
Bumps [guava](https://github.com/google/guava) from 31.1-jre to 32.0.0-jre.
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

---
updated-dependencies:
- dependency-name: com.google.guava:guava
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-06-19 18:46:30 -07:00
nossr50
019d22d92a Make mcMMO quieter by moving most log messages to debug only 2023-06-19 16:26:30 -07:00
nossr50
e39022cc64 2.1.221 2023-06-19 14:11:53 -07:00
nossr50
a41106ee30 Update changelog 2023-06-17 20:34:18 -07:00
nossr50
b2110d4e1c PAPI Support pt 2 2023-06-17 20:32:51 -07:00
nossr50
f22043ebb5 PAPI Support WIP 2023-06-17 20:22:49 -07:00
nossr50
cc1b511c02 Don't look up offline players by name 2023-06-17 15:56:36 -07:00
nossr50
e9a020565f Added fail safes against bonus drop meta not being cleaned up 2023-05-29 14:34:47 -07:00
nossr50
44ab8d93ab Dev mode 2023-05-29 14:15:04 -07:00
Warrior
78922ea337 Fix blast mining bonus drops option not working (#4895) 2023-05-29 13:58:24 -07:00
nossr50
db01b61371 2.1.220 2023-05-13 14:42:14 -07:00
Warrior
133a60c4bf Fix child skills counting towards power level in /inspect (#4889) 2023-04-23 11:08:06 -07:00
nossr50
684e96ff6b Fix RankConfig 2023-04-17 12:17:28 -07:00
nossr50
f40f68bdf0 Fix RankConfig not using the new updating config system 2023-04-17 12:07:59 -07:00
nossr50
640f4b0a9b Fix mcMMO attempting to copy out custom repair/salvage configs 2023-04-17 12:07:41 -07:00
nossr50
978ee4a9a3 Optimize the imports 2023-04-11 15:49:37 -07:00
nossr50
0ab93586fd Config files will update automatically again 2023-04-11 15:48:14 -07:00
nossr50
921a0228db Merge remote-tracking branch 'origin/master' 2023-04-07 17:00:13 -07:00
nossr50
ac68c4ebe6 2.1.219 2023-04-07 17:00:01 -07:00
Smudge
4553310bb9 Fixed fishing exploiting compatibility (#4859)
* Fixed fishing exploiting compatibility

* Moved same target to class variable
2023-04-03 17:52:00 -07:00
Warrior
9b0632d63c Make party loading more resilient (#4881) 2023-04-03 17:49:35 -07:00
Warrior
69ef484b86 Fix dots not being replaced when renaming party (#4882) 2023-04-03 17:48:53 -07:00
Warrior
606a92f1ef Fix /party teleport NPE (#4885) 2023-04-03 17:48:01 -07:00
nossr50
79730383ab Fixed wiki url being incorrect in various commands 2023-04-03 16:47:58 -07:00
nossr50
7264e1a8d6 Small tweaks 2023-04-03 12:07:34 -07:00
nossr50
e011f545a7 Added smithing_table to tool readiness blacklist 2023-04-02 20:44:00 -07:00
nossr50
283fa14380 Add Camel, Sniffer, and Snifflet to taming XP 2023-04-02 20:42:06 -07:00
nossr50
5f388a9906 Add support for torchflower replanting to herbalism 2023-04-02 20:38:05 -07:00
nossr50
cd96bc79d8 Change isHerbalismDrop to use strings.. this method still needs more work 2023-04-02 20:24:04 -07:00
nossr50
ae961caeab Added Torchflower to herbalism experience and bonus drops 2023-04-02 20:11:10 -07:00
nossr50
0b4d87aebc Add Sniffer and Snifflet to combat experience in experience.yml 2023-04-02 20:07:50 -07:00
nossr50
6106f70c24 Added Pitcher_Plants to bonus drops and herbalism experience 2023-04-02 20:05:52 -07:00
nossr50
100a7f8a8f Added pink_petals, cherry_wood, and cherry_log to bonus drops in config.yml 2023-04-02 20:02:32 -07:00
nossr50
4c792c4f2c Added Pink_Petals to experience.yml 2023-04-02 20:00:58 -07:00
nossr50
db4b820f80 Add new hanging signs to tool readiness blacklist 2023-04-02 19:58:16 -07:00
nossr50
ca710b4302 Add chiseled_bookshelf to tool readiness blacklist 2023-04-02 19:55:30 -07:00
nossr50
668cc0e4a3 Add support for upcoming Cherry trees 2023-04-02 19:53:13 -07:00
nossr50
6d0542b524 Merge remote-tracking branch 'origin/master' 2023-03-26 13:22:41 -07:00
nossr50
d84a5b37b7 Update kyori dependencies 2023-03-26 13:22:31 -07:00
optimizing-ci-builds
c072ae4990 disable xml report (#4880) 2023-03-21 22:05:40 -07:00
nossr50
2d78eaa495 Fixed Beetroots double drop issue #4667 2023-03-19 21:21:54 -07:00
Warrior
6bdc51be76 Fix missing return in notify command (#4870) 2023-02-25 15:20:45 -08:00
nossr50
af15617196 Add config toggle for Blast Mining bonus drops to advanced.yml 2023-02-19 13:40:14 -08:00
CuteLittleSky
643dff7915 Update locale_zh_CN.properties (#4858) 2023-02-09 18:16:26 -08:00
Justin
01fbfccc0d feat: Make power level display for offline players (#4861)
Fixes #4599
2023-02-09 18:12:46 -08:00
Jok
2362fe994a Don't call EntityDamageByEntityEvent with null damager (#4863)
Co-authored-by: Elioby <elioby@users.noreply.github.com>
2023-02-09 18:11:30 -08:00
nopeless
08b08b1285 Fix: player is no longer immune to projectiles shot by themselves (#4856) 2023-01-28 11:57:31 -08:00
nossr50
965540dfaf 2.1.218 2022-12-04 14:32:34 -08:00
destro174
75822472fc Add item in mainhand when spawning in lumber bonus blocks. (#4826) 2022-12-04 14:22:37 -08:00
Daniil Z
59aecb79a1 Update Russian locale (#4832)
Added/updated some lines
Fixed new-line characters
2022-12-04 14:21:44 -08:00
DarkKnights22
c865c2d2e3 Fix bug where players could know staff are invis (#4833)
* Fix bug where players could know staff are invis

* remove whitespace
2022-12-04 14:21:22 -08:00
MrPowerGamerBR
93c64a8770 Fix pt_BR ability on typo (#4837) 2022-12-04 14:19:48 -08:00
Greymagic27
30ac82181e Updated plugins to latest version (#4817) 2022-08-09 07:35:12 -07:00
nossr50
2b219f48ec Dev mode 2022-08-07 16:13:18 -07:00
nossr50
fed0483d40 2.1.217 2022-08-07 16:03:55 -07:00
nossr50
101c43a4bc Tree Feller now partially destroys trees if the whole tree is too big
Fixes #4811
2022-08-07 15:55:19 -07:00
nossr50
fb738d85f6 Mangrove trees are now properly marked natural from growth
Fixes #4810
2022-08-07 15:54:22 -07:00
nossr50
032a407c8a Update changelog and version 2022-08-07 14:27:42 -07:00
Greymagic27
33e615f0f1 Updated dependencies to fix hovering over subskills for 1.19.2 (#4814)
* Updated dependencies that should fix the issue

* Updated spigotmc version

* Updated rest of dependencies

* Updated dependencies that fix the issue. Investigating what dependency update breaks compiling.

* Found the dependency that caused the compile issue, so have not updated that one
2022-08-07 14:19:46 -07:00
dod0lp
8feba60e2c Update config.yml (#4809) 2022-08-03 07:43:03 -07:00
nossr50
8a4fe8ae5d 2.1.216 2022-07-24 10:09:48 -07:00
nossr50
45f96793a5 Revert "Players who used unarmed combat are still considered using unarmed while not holding weapons for a brief time period"
This reverts commit 993b418fbc.
2022-07-24 10:05:56 -07:00
nossr50
df0362bcba Allow mining benefits while using Hoe 2022-07-23 17:04:43 -07:00
nossr50
25d558a5fa Added Sculk blocks to Mining 2022-07-23 16:57:42 -07:00
nossr50
c0e4d7a43d 2.1.215 - Unarmed change + Bug Fixes 2022-07-23 16:22:02 -07:00
nossr50
993b418fbc Players who used unarmed combat are still considered using unarmed while not holding weapons for a brief time period 2022-07-23 16:13:49 -07:00
nossr50
9cf856221d update changelog 2022-07-23 14:47:32 -07:00
nossr50
4db6e03517 Hacky workaround for Spigot API bug not showing burntime to the client when burntime was too high 2022-07-23 14:43:24 -07:00
nossr50
eb1393c02c Fix burnTime debug prints on mmodebug players 2022-07-23 14:24:31 -07:00
nossr50
e1a54b72a9 update changelog 2022-07-23 13:34:38 -07:00
Greymagic27
b266c7ce5b Updated Dependencies (#4798)
* Updated Dependencies

* Fix spelling mistake in dependencies

* Fixed dependency error that would prevent the plugin from loading.

Turned out I put in the wrong acf-bukkit, preventing the plugin from working. Oops!
2022-07-17 14:59:19 -07:00
nossr50
38f937fa01 revert potential furnace animation bug fix 2022-07-17 14:56:44 -07:00
nossr50
6d7982c0cf Merge branch 'master' of github.com:mcMMO-Dev/mcMMO 2022-07-17 14:03:10 -07:00
nossr50
89fa26d0eb Potential fix for #3005 2022-07-17 14:00:03 -07:00
Greymagic27
edd85c2f19 Updated kyori adventure-platform dependencies (#4797) 2022-07-17 13:38:44 -07:00
Greymagic27
88b6517f88 Added Dripstone Block to experience.yml (#4796) 2022-07-15 15:07:19 -07:00
PikaMug
2c09a0fdb6 Switch to new sk89q repo (#4791) 2022-07-02 19:25:27 -07:00
nossr50
90721ee859 Add missing Mangrove_Log to experience.yml 2022-06-26 18:43:09 -07:00
destro174
aa4011a226 Use item in mainhand to get drops when using treefeller (#4781) 2022-06-11 16:41:27 -07:00
nossr50
fa82fe8e67 Level up broadcasts should be visible to the player of origin 2022-06-09 22:50:36 -07:00
nossr50
444e1532f2 2.1.214 2022-06-09 22:39:11 -07:00
Smudge
1a34d2f647 Added 25% xp boost permission (#4773) 2022-06-09 14:31:06 -07:00
abridgedcarp
d543843235 Fix Maven build failure (#4779) 2022-06-09 14:26:50 -07:00
nossr50
c40af913f4 mcMMO 2.1.213 2022-06-07 18:07:14 -07:00
nossr50
f6268fe291 Add in new 1.19 stuff and tweak treasures.yml 2022-06-07 18:00:32 -07:00
nossr50
27854720f0 Add some exploit prevention to fishing 2022-05-15 15:24:25 -07:00
nossr50
d19cf1e260 2.1.212 - Fixed herbalism exploit and added damage limit for XP
calculations used in combat
2022-04-28 18:31:10 -07:00
Warrior
4a8630262e Fix hanging plants searching up instead of down. (#4766) 2022-04-28 08:33:45 -07:00
Werner
c41d2d1f39 Bump shade-plugin to 3.3.1 (#4762)
fixes building
2022-04-10 13:09:03 -07:00
nossr50
8821fb0b2f 2.1.211 2022-03-18 15:07:02 -07:00
nossr50
5ab55c1653 mcMMO will no longer use the DamageModifier API (potentially fix immortal player bug) 2022-03-17 19:58:42 -07:00
nossr50
8066f7f7f2 Tweak damage debug info to show modifier values 2022-03-17 16:08:50 -07:00
nossr50
5ea18e8ba7 Add combat debug info for player versus player combat /mmodebug 2022-03-17 15:03:42 -07:00
nossr50
0bf3f98d95 2.1.210 2022-03-17 13:59:17 -07:00
nossr50
fa33fa3d32 Revert 3 commits (work will be continued in branch)
Revert "Disabling mcMMO when the config breaks is dumb"

This reverts commit 86e7bfbf89.

Revert "Config validation rewrite part 1"

This reverts commit 16e90da8fd.

Revert "Update changelog"

This reverts commit 0ccd89fad4.
2022-03-17 13:49:46 -07:00
Mads U. Jensen
8b6a4c1e5b Update doubledrops IDs (#4743) 2022-02-10 17:31:22 -08:00
nossr50
0ccd89fad4 Update changelog 2022-01-30 15:47:08 -08:00
nossr50
16e90da8fd Config validation rewrite part 1 2022-01-30 15:31:52 -08:00
nossr50
86e7bfbf89 Disabling mcMMO when the config breaks is dumb
Fixes #4732
2022-01-30 14:24:21 -08:00
nossr50
8f0fb76847 Silence API out of date warning on config load 2022-01-17 15:57:04 -08:00
nossr50
3be15d3f65 Rewrite how mob/item/block metadata is tracked/retrieved
Fixes #4720
2022-01-17 15:32:02 -08:00
nossr50
74ced18bd0 Dev mode 2022-01-15 11:51:44 -08:00
nossr50
2e0a371ed8 Update changelog 2022-01-14 16:50:19 -08:00
nossr50
68ffe31246 2.1.209 2022-01-14 16:41:33 -08:00
nossr50
405de477d3 (thanks chew) Fix older MC versions not loading config files
Fixes #4716
2022-01-11 19:28:18 -08:00
nossr50
db0ae36fa7 fixed bug where duplicate comments with leading whitespace were ignored 2022-01-11 19:22:28 -08:00
nossr50
5d2028b5dc Java 16 compile target 2022-01-10 22:36:37 -08:00
nossr50
3e645a022d 2.1.208 2022-01-10 22:34:21 -08:00
nossr50
c21a040ddb Huge changes to how config files are loaded/updated, fixes many issues
Fixes #4715
2022-01-10 22:29:22 -08:00
the456gamer
dd4a5a6b9a remove YAML parsing hacks in favor of native bukkit provided parsing (#4714)
* fix yaml config to use native comment handling.
fixes #4702
replaces #4713
2022-01-09 11:16:17 -08:00
nossr50
d5ce8fc6ff Dev mode 2022-01-09 11:14:11 -08:00
dexasz
829aaea5d4 add & translate missing strings & fix a typo that broke placeholders (#4707) 2022-01-09 11:07:18 -08:00
Olivia
c92ae16c7f Fix extra 0 in level for gunpowder in retro mode (#4701) 2021-12-30 14:21:46 -08:00
nossr50
40160498ca 2.1.207 2021-12-27 11:40:33 -08:00
nossr50
9d08d88f2a Add new repair setting to default file 2021-12-27 11:34:55 -08:00
JeBobs
2ca3544741 Added option to disallow using enchanted materials to repair items. (#4693) 2021-12-27 11:29:54 -08:00
nossr50
ef714f98c9 Fix parties at level cap gaining XP and thus spamming messages
Fixes #4686
2021-12-27 11:22:16 -08:00
nossr50
dd550feb65 Update BlockTracker to use Spigot API directly instead of compatibility
layer
Fixes #4692 Fixes #4698
2021-12-27 11:09:27 -08:00
nossr50
ddc9a69f4b Fix ScoreboardManager NPE and added locale messages relating to scoreboards 2021-12-27 10:46:56 -08:00
TheBusyBiscuit
61388f46f1 Fixed #4694 (#4695) 2021-12-27 09:27:13 -08:00
nossr50
341dc45202 Takeout this warning 2021-12-14 23:27:51 -08:00
nossr50
13f7482b39 Unicode support for locale files 2021-12-14 23:08:08 -08:00
nossr50
a78dcffde7 Temporarily roll back to Java 16 2021-12-14 22:26:40 -08:00
nossr50
3671d0b565 dev mode 2021-12-14 22:23:31 -08:00
lilac & gooseberries
1b11fd2369 lithuanian translation for mcmmo (#4676) 2021-12-14 22:22:58 -08:00
nossr50
c36ff85cbf 2.1.206 - Memory leaks fixed and other changes Fixes #4681 2021-12-11 22:27:54 -08:00
nossr50
77cefbdfab Merge branch 'master' of https://github.com/mcMMO-Dev/mcMMO 2021-12-11 22:22:37 -08:00
nossr50
fbe0cd1471 Fixing like 10 memory leaks Fixes #4670 2021-12-11 22:22:02 -08:00
Robert Alan Chapton
728ba512c3 Java 17 for GH actions 2021-12-11 21:21:22 -08:00
nossr50
10470dde13 Reduce default volume of level up sound 2021-12-11 21:19:30 -08:00
nossr50
11245e87ef squelch ChunkStoreTest log output 2021-12-11 20:57:25 -08:00
nossr50
b88d752f61 update dependencies 2021-12-11 20:56:10 -08:00
Enderaoe
09ce259288 fix issue #4667 (#4669) 2021-12-07 19:55:42 -08:00
PikaMug
519d469cb2 Add null check to XP gain handler, fixes #4663 (#4677)
* Add null check to XP gain handler, fixes #4663

Co-authored-by: Robert Alan Chapton <nossr50@gmail.com>
2021-12-07 19:54:48 -08:00
nossr50
cf67e3502a dev mode 2021-12-07 19:29:36 -08:00
nossr50
9ab4584dfe MOB_METADATA_KEYS should be immutable 2021-11-14 09:36:00 -08:00
nossr50
8d27e8fccf 2.1.205 2021-11-14 09:33:27 -08:00
NemuruYama
ba1f15b655 Fixed the alchemy properly (#4658) 2021-11-14 08:05:42 -08:00
nossr50
5b1a69b3f7 2.1.204 2021-11-10 14:55:54 -08:00
Enderaoe
d185c7538c Fix issue #4626 double smelting on raw copper (#4652) 2021-11-10 04:55:04 -08:00
gecko10000
2347fc294f Fix IndexOutOfBoundsException for fake brew event by adding to list instead of setting the index (which doesn't work) (#4655) 2021-11-10 04:54:31 -08:00
nossr50
7aaec5b707 2.1.203 2021-11-08 19:07:02 -08:00
nossr50
20a713e04d Update changelog 2021-11-08 19:02:37 -08:00
gecko10000
81faf93f31 Fix hex colors in broadcasts (#4651) 2021-11-08 19:01:14 -08:00
PikaMug
19c0f6757e Add deprecated constructor w/o startinglevel per d9e195f (#4647) 2021-11-08 19:00:00 -08:00
nossr50
ec0815043e Update changelog 2021-11-08 18:58:11 -08:00
Enderaoe
182717eacf Fix issue #4105 Fishing shake percentage seems off. (#4649) 2021-11-08 18:57:32 -08:00
Robert Alan Chapton
e287ad47d1 updating github actions
hope this works
2021-11-08 18:54:46 -08:00
nossr50
8eee39b88b mcMMO now requires the latest MC version (currently 1.17.1)
Fixed a few bugs from API breaks
2021-11-08 18:38:50 -08:00
nossr50
4bf2ad46ea Require Java 16 2021-11-08 18:15:33 -08:00
nossr50
def676d8d7 2.1.202 2021-10-05 12:41:25 -07:00
nossr50
f8433cdbcc Fixed Kelp not awarding XP
Fixed #4639 Fixed #4110
2021-10-05 12:39:56 -07:00
nossr50
a2e10dbd0c Azalea trees bone mealed into existence no longer get marked unnatural
Fixes #4640
2021-10-05 11:58:31 -07:00
nossr50
e55ce00d62 Update changelog 2021-10-05 10:13:07 -07:00
nossr50
73c465ee64 Fixed a bug where mcMMO didn't flag all blocks as natural appropriately
in some StructureGrowEvent(s)
2021-09-28 16:58:40 -07:00
nossr50
c30892a0a5 Add flowering azalea leaves to Tree Feller 2021-09-28 00:09:04 -07:00
nossr50
58e7323c3e Bring adventure-api and adventure-platform (and dependencies) up to date 2021-09-23 12:59:58 -07:00
tunagohan
7fc6577196 Propose: Add an option for Exploiting Fishing. (#4619)
* feat: Add exploiting option for fishing

* Update experience.yml

Let's change how this was named

* Update ExperienceConfig.java

Let's change how this was named

Co-authored-by: Robert Alan Chapton <nossr50@gmail.com>
2021-09-22 15:11:54 -07:00
PikaMug
162c605dac Trigger change event for party create/disband (#4620) 2021-09-22 15:05:41 -07:00
rosaage
280eb0ba51 Added support for allowPublicKeyRetrieval=true in the JDBC launch (#4635)
options for MySQL

Co-authored-by: BuildTools <unconfigured@null.spigotmc.org>
2021-09-22 15:03:03 -07:00
GhostDC
8e5251ba66 update locale_zh_CN.properties (#4628) 2021-09-22 15:00:03 -07:00
Warrior
1e43e34547 Make /party kick case insensitive (#4630) 2021-09-22 14:59:39 -07:00
nossr50
5575309b79 Add amethyst block to experience.yml for Mining 2021-08-15 21:59:38 -07:00
nossr50
88dae5d5dd dev mode ( 2.1.202 ) 2021-08-10 14:59:13 -07:00
nossr50
da3909c08f 2.1.201 2021-08-10 14:44:13 -07:00
nossr50
6cad4993ed Tweaked Rupture's visual/audio effect 2021-08-10 14:42:08 -07:00
nossr50
af6e6b9545 Update changelog 2021-08-10 14:21:16 -07:00
emanondev
cd937a812d Fix for impact armor damage formula (#4425)
* Update SkillUtils.java

Add handleArmorDurabilityChange() to handle armor damage reduction correctly

* Update AxesManager.java

Changed method to handle impact damage calculation

* Update SkillUtils.java
2021-08-10 14:19:18 -07:00
Griffin Kubesa
264c0e2c78 Add /<skill> keep (#4512)
* Add /<skill> keep

* Add keep to tab completion

* Case insensitive
2021-08-10 14:17:37 -07:00
David
b42278932e Update locale_pt_BR.properties (#4566) 2021-08-10 14:15:56 -07:00
蘭蘭露 Flandre_tw
7fc7125ed3 Reupload new Chinese Traditional translation (#4584)
Hello, I have completed the Chinese Traditional translation. :)
2021-08-10 14:14:45 -07:00
nossr50
d3f012de27 Update changelog 2021-08-10 14:14:07 -07:00
Griffin Kubesa
dfa16c70a7 Set TNT source in blast mining (#4580)
* Set TNT source in blast mining

* Compatibility with older versions

Co-authored-by: TheBusyBiscuit <TheBusyBiscuit@users.noreply.github.com>

Co-authored-by: TheBusyBiscuit <TheBusyBiscuit@users.noreply.github.com>
2021-08-10 14:13:25 -07:00
GhostDC
8805a25d85 update locale_zh_CN.properties (#4585)
Thank you
2021-08-10 14:09:32 -07:00
nossr50
f91a2217c8 Fixed plugin incompatibility and exploits regarding buffed tools remaining buffed
Fixes #4616
2021-08-10 14:04:59 -07:00
nossr50
64f1ae4af6 Merge branch 'master' of github.com:mcMMO-Dev/mcMMO 2021-08-10 13:47:55 -07:00
nossr50
6d9a9d165d Blast Mining shouldn't drop Budding Amethyst
Fixes #4589
2021-08-10 13:46:33 -07:00
nossr50
5edc0d065d Add aliases to inspect command (mcinspect, mmoinspect) 2021-08-06 21:54:28 -07:00
Diablolend
a346fc3338 Fixed in every line of "\ \ " characters (#4588)
Where did they come from? 🤔
2021-07-29 15:16:07 -07:00
nossr50
dc94fedee1 Added member getPlayer to McMMOItemSpawnEvent
Fixes #4572
2021-07-20 18:47:25 -07:00
nossr50
93a6a73b4e Revert Woodcutting translation forortuguese
Fixes #4568
2021-07-20 18:32:34 -07:00
TheBusyBiscuit
2c849d9cb4 Added a Unit Test for mc version detection (#4560)
* Added a Unit Test for mc version detection

* Merge upstream and update server software string
2021-07-05 16:02:46 -07:00
nossr50
b79d452a6d 2.1.200 2021-07-01 21:02:59 -07:00
nossr50
fb94374e3c Update changelog 2021-07-01 16:14:13 -07:00
TheBusyBiscuit
5255ae846d Fixed #4556 (#4559) 2021-07-01 16:11:22 -07:00
stepech
e816310da8 Fix mcmmo picking wrong version on builds withou patch number (#4555)
* Fix server versioning

* Switch to regex when getting server version

* add comment

* Poor beginner mistakes

Co-authored-by: TheBusyBiscuit <TheBusyBiscuit@users.noreply.github.com>

Co-authored-by: TheBusyBiscuit <TheBusyBiscuit@users.noreply.github.com>
2021-07-01 16:07:44 -07:00
nossr50
de6ba4fb6a Dodge no longer triggers while blocking
Fixes #4543
2021-06-22 14:59:40 -07:00
TheBusyBiscuit
e35bfe758c Update to Junit5 and allow for mcMMO to be compiled on Java 16 (#4552)
* Updated all unit tests to Junit5 and removed Powermock

* Some formatting

* I did not mean to commit this file

* Fixed file ending

* We don't need these extra dependencies

* Replaced delegate with Junit5 assertThrows

* Revert this change

* Re-add mockito-core

* A bit more refactoring

* Update surefire and remove failsafe

* Updated Mockito

* Add failsafe back

* Bump Mockito to 3.11.2

They literally just released that.
2021-06-21 09:21:55 -07:00
nossr50
fffbacd239 2.1.199 2021-06-15 14:30:16 -07:00
nossr50
f286af3fff update changelog 2021-06-15 14:25:02 -07:00
nossr50
7e28799f94 Fix SQL on 1.17 (hacky) and optimized CompatibilityManager 2021-06-15 14:19:30 -07:00
nossr50
78dc56d263 Update Deepslate Lapis Ore on MaterialMapStore 2021-06-11 14:47:11 -07:00
nossr50
e3dfdfc6ee Fixed Deesplate Lapis Ore not being recognized 2021-06-11 14:46:27 -07:00
nossr50
4819a45be9 2.1.198 2021-06-11 14:26:28 -07:00
nossr50
5e0f8a334d Update changelog 2021-06-11 14:23:24 -07:00
nossr50
5f0cc2b09a Fix Smelting not recognizing the new 1.17 smeltables (like raw ores) 2021-06-11 14:22:33 -07:00
nossr50
6ff37c8baa Update changelog 2021-06-11 09:10:43 -07:00
TheBusyBiscuit
f7dc72359b Bump adventure to 4.8.0 (#4546) 2021-06-11 09:09:47 -07:00
nossr50
1ab5b82b22 2.1.198 dev mode 2021-06-11 09:08:22 -07:00
nossr50
28c6c90f23 2.1.197 2021-06-06 21:00:27 -07:00
nossr50
9bb38e3193 Add more 1.17 blocks 2021-06-06 20:59:43 -07:00
nossr50
551fac84a5 Add Glow Berries to Farmer's Diet 2021-06-06 20:56:14 -07:00
nossr50
0bc25b263b Add support for Glow Berries / Cave Vines 2021-06-06 20:52:27 -07:00
nossr50
fa9a3ae766 Add support for Glow Lichen 2021-06-06 20:44:33 -07:00
nossr50
33df92ea3a Add tuff to super breaker 2021-06-06 20:42:07 -07:00
nossr50
c3d86ba6c5 Add support for Tuff 2021-06-06 20:41:59 -07:00
nossr50
b569b9456e Add support for Mossy Block and Azalea Leaves 2021-06-06 20:37:51 -07:00
nossr50
4e6e58d9ca Add more support for 1.17 (mining related) 2021-06-06 11:18:03 -07:00
nossr50
619eec7667 Add new 'raw' ores to experience values and bonus drops 2021-06-03 14:34:36 -07:00
nossr50
97cfb1cfc7 More 1.17 support 2021-06-03 14:23:19 -07:00
nossr50
c28c8d164a Adding more 1.17 support 2021-06-03 14:20:00 -07:00
nossr50
e74e1e6829 Add Amethyst related blocks to experience.yml and update Super Breaker 2021-06-03 14:04:08 -07:00
nossr50
6dbc7adf48 Add glow_squid, goat, and axolotl to experience.yml 2021-06-03 13:44:56 -07:00
nossr50
cbaef4a092 Update changelog 2021-05-31 09:09:45 -07:00
lexikiq
eb10bcbc96 Disable launching from Minecart Anti-AFK (#4508) 2021-05-31 09:08:06 -07:00
nossr50
2875545fa4 Update pt_BR locale 2021-05-31 08:55:10 -07:00
nossr50
be595f2568 Update changelog 2021-05-31 08:37:07 -07:00
snake
882f6197c6 Update locale_ja_JP.propaties (#4529)
* Update locale_ja_JP.propaties

* Escape non-ASCII characters
2021-05-31 08:34:18 -07:00
nossr50
0d2f370185 Update our dependencies to their latest versions (where possibly)
Also adds Guava as a dependency as version upgrading our dependencies resulted in the loss of the included Guava libraries
2021-04-23 15:08:57 -07:00
nossr50
da1fcfe30a 2.1.196 2021-04-23 11:26:35 -07:00
nossr50
f983f95961 Remove explosion from rupture, and rupture bug fixes and other tweaks 2021-04-23 11:13:59 -07:00
nossr50
d67c561fed Update changelog 2021-04-23 10:46:59 -07:00
nossr50
989f7fd51b Fix Serrated Strikes not processing Rupture for additional targets 2021-04-23 10:45:19 -07:00
nossr50
e4b8b74987 Optimize imports 2021-04-23 10:37:22 -07:00
nossr50
9e7bb12dc3 Also avoid issues in this test by mocking instead of implementing an ever changing interface 2021-04-23 10:34:00 -07:00
nossr50
95c291d630 Avoid the pitfalls of implementing an everchanging interface from a SNAPSHOT 2021-04-23 10:30:26 -07:00
nossr50
9b4070d971 Don't process null McMMOPlayer events
Fixes #4499
2021-04-23 10:20:20 -07:00
lexikiq
6d0fe4fb58 Add McMMOEntityDamageByRuptureEvent (#4498) 2021-04-20 14:51:57 -07:00
369 changed files with 22995 additions and 22334 deletions

View File

@@ -31,12 +31,13 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v2
# 2. Setup Java 1.8 JDK
- name: Java 1.8 setup
uses: actions/setup-java@v1.4.3
# 2. Setup Java 17 JDK (Adopt)
- name: Java 17 setup
uses: actions/setup-java@v2
with:
distribution: 'adopt'
java-package: jdk
java-version: 1.8
java-version: '17'
# 3. Setup local Maven package cache to speed up building
- name: Cache Maven packages
@@ -48,4 +49,4 @@ jobs:
# 4. Build via Maven
- name: Build via Maven
run: mvn verify -B --file pom.xml
run: mvn verify -B --file pom.xml -DdisableXmlReport=true

1
.gitignore vendored
View File

@@ -55,3 +55,4 @@
# Atlassian Stuff
/atlassian-ide-plugin.xml
/nulllocale_override.properties

View File

@@ -1,113 +1,393 @@
Version 2.2.000
//TODO: Add level up milestone processing hooks
//TODO: Verify fishing durability change is removed
Version 2.1.222
Fixed dupe exploit
Glow Lichen default XP changed from 200 to 5
A lot of mcMMO logging was moved from INFO to DEBUG, this should reduce the amount of noise in your logs and console
Removed the mcimport command as its useless (was for mod configs)
mcMMO-API is now the library used for mcMMO API
Parts of the API have been migrated to mcMMO-API
(API) mcMMO makes use of jmal (Java Minecraft Abstraction Library) for some abstraction now
(API) Added skill register
(API) Skill hierarchy is now defined by Skill in mcMMO-API, and mcMMO needs a skill to be registered to be aware of it
(API) A lot of changes to the API, I'll be including a document with the release of this update to explain the finer details
When using commands that require typing a skill name, locale names are now always checked
When using commands that require typing a skill name, it is now legal to provide the skills fully qualified identifier
NOTES: If you want to see all logging messages, modify config.yml and set General.Verbose_Logging to true
You will have to adjust experience.yml to get the balance changes, or delete it to generate a new one
Version 2.1.221
PAPI Support is now built into mcMMO and loads when mcMMO loads (as long as you have PAPI running)
Fixed blast mining bonus drops not working (Thanks warriiorrrr)
Added fail safes to prevent bonus drops metadata from lingering on blocks
Codebase Stuff
Many places that passed type Player now passes type McMMOPlayer instead
NOTES: Placeholders were brought in from electroniccat's original work on a PAPI expansion for mcMMO, the placeholders are the same as a result
I will be adding a leaderboard placeholder in the next patch (most likely). Feel free to share details of what functionality you'd want from additional placeholders on discord.
Version 2.1.220
(API) Added TreeFellerBlockBreakEvent class which extends FakeBlockBreakEvent (see notes), this is sent out during Tree Feller processing to allow other plugins to differentiate between Tree Feller and other fake block break events
Config files update automatically again
Default configs are now copied to plugins/mcMMO/defaults for easy reference
Fixed child skills counting towards power level in /inspect (Thanks Wariorrrr)
New Skill - Tridents
New Skill - Crossbows
NOTES: For a while configs were not updating automatically as a rewrite of how config files were loaded was partially done, this is now complete and configs will update automatically again.
Fake block break events have been sent out historically by mcMMO to check other plugins for a players permission to break or place a block, Tree Feller will now specify via inheritance its own event type for this so mcMMO plugins can handle Tree Feller fake block break events differently if they so choose.
You can now view the default configs more easily as they are now copied to plugins/mcMMO/defaults, these configs will be overwritten on start up to match the default values of the config in the JAR
Version 2.1.219
Fixed Fishing exploit protection being triggered inappropriately by other plugins (Thanks smudgge)
Fixed wiki url being incorrect in commands
Party loading is more resilient (Thanks Wariorrrr)
Fixed periods not being replaced whe nrenaming party (Thanks Wariorrrr)
Fixed Party Teleport NPE (Thanks Wariorrrr)
Added support for various new things from Minecraft 1.20
Fixed double drop issue with Beetroots
Added 'Camel' to taming experience in experience.yml
Added 'Sniffer' to taming experience in experience.yml
Added 'Snifflet' to taming experience in experience.yml
Added 'Pitcher_Plant' to bonus drops in config.yml
Added 'Torchflower' to bonus drops in config.yml
Added 'Pink_Petals' to bonus drops in config.yml
Added 'Cherry_Log' to bonus drops in config.yml
Added 'Cherry_Wood' to bonus drops in config.yml
Added 'Camel' to combat experience in experience.yml
Added 'Sniffer' to combat experience in experience.yml
Added 'Snifflet' to combat experience in experience.yml
Added 'Torchflower' to herbalism experience in experience.yml
Added 'Pitcher_Plant' to herbalism experience in experience.yml
Added 'Pink_Petals' to herbalism experience in experience.yml
Added 'Cherry_Log' to woodcutting experience in experience.yml
Added 'Cherry_Wood' to woodcutting experience in experience.yml
Added 'Stripped_Cherry_Log' to woodcutting experience in experience.yml
Added 'Stripped_Cherry_Wood' to woodcutting experience in experience.yml
Added 'Skills.Mining.BlastMining.Bonus_Drops.Enabled' to advanced.yml to enable/disable bonus drops from Blast Mining
NOTE: There are plans to add experience and potentially subskills for discovering items via the new brushing mechanic, but this will have to wait for new Spigot API to become available
New config file named 'tridents.yml'
Version 2.1.218
Fixed locale pt_BR type (thanks MrPowerGamerBR)
Updated Russian Locale (thanks imDaniX)
Harvest Lumber checks main hand enchantments when delivering bonuses (thanks destro174)
Fixed bug where players could use inspect to determine if vanished players were online (thanks DarkKnights22)
New command /tridents - Skill Info for Tridents
New command /crossbows - Skill Info for Crossbows
Added Sub-Skill named Multi Tasking to Tridents
Added Sub-Skill named Tridents Limit Break to Tridents
Added Sub-Skill named Super Shotgun to Crossbows
Added Sub-Skill named Crossbows Limit Break to Crossbows
Permission node descriptions had mentions of ability changed to sub-skill and other minor corrections
mcMMO will now register arrows shot from the offhand as being from either Archery or Crossbows (before mcMMO ignored offhand Archery)
(These permissions are all included in the mcmmo.defaults node)
New permission node 'mcmmo.commands.tridents'
New permission node 'mcmmo.skills.tridents'
New permission node 'mcmmo.ability.tridents.all'
New permission node 'mcmmo.ability.tridents.multitasking'
New permission node 'mcmmo.ability.tridents.tridentslimitbreak'
New permission node 'mcmmo.commands.crossbows'
New permission node 'mcmmo.skills.crossbows'
New permission node 'mcmmo.ability.crossbows.all'
New permission node 'mcmmo.ability.crossbows.crossbowslimitbreak'
New permission node 'mcmmo.ability.crossbows.coneofdeath'
The Party system has some new features, and a lot of bad features were removed completely, read the notes
Parties can no longer have passwords (see notes)
Parties can no longer be locked (see notes)
Parties no longer have item share (see notes)
Party alliances are gone (see notes)
Parties are always private (see notes)
Party members can be promoted to Officer by the Party Leader (officers are mini-party leaders)
Added Party Officer chat, only other officers (including the party leader) can read and participate
Added the following party subcommands: promote, demote
Removed the following party subcommands: join, lock, unlock, password, alliance, item share
Added permission node 'mcmmo.chat.officerpartychat'
The following permission nodes were removed because their related feature was removed
Removed permission node 'mcmmo.commands.party.unlock'
Removed permission node 'mcmmo.commands.party.alliance'
Removed permission node 'mcmmo.commands.party.password'
Removed permission node 'mcmmo.commands.party.itemshare'
The following permission nodes were removed because permissions for these commands don't make sense, if you want to disable party commands just negate 'mcmmo.commands.party'
Removed permission node 'mcmmo.commands.party.quit'
Removed permission node 'mcmmo.commands.party.kick'
Added new locale string 'Overhaul.Name.Tridents'
Added new locale string 'Tridents.SubSkill.TridentsLimitBreak.Name'
Added new locale string 'Tridents.SubSkill.TridentsLimitBreak.Description'
Added new locale string 'Tridents.SubSkill.TridentsLimitBreak.Stat'
Added new locale string 'Overhaul.Name.Crossbows'
Added new locale string 'Crossbows.SubSkill.CrossbowsLimitBreak.Name'
Added new locale string 'Crossbows.SubSkill.CrossbowsLimitBreak.Description'
Added new locale string 'Crossbows.SubSkill.CrossbowsLimitBreak.Stat'
Added new locale string 'Commands.MissingProfile'
Removed locale string 'Commands.Offline'
Player Power Levels no longer need to pass permission checks when summing skills
Minor improvements to how player data is serialized
SMP mod settings removed from config.yml (this is a legacy feature and didn't really do anything anymore)
Refactored & Optimized a bunch of code involving player and party data
Added XP bar settings for Tridents & Crossbows to experience.yml
Changed some debug level logging to info level for convenience
Database Changes
XP Bar settings (set by /mmoxpbar command) are now saved
Players can now be marked as exempt from leadboards
Party Chat Spy toggle is now saved
(FlatFile) Fixed a bug where last login was not being saved
Schema updated for the new skills and supers and things mentioned above
Notes:
These are the first new skills that I've written for mcMMO in about 9 years, I'll be listening closely to feedback and tweaking them often.
Parties got unnecessarily complex in my absence, I have removed many party features in order to simplify parties and bring them closer to my vision. I have also added new features which should improve parties where it matters.
About the removed party features, all the features I removed I consider poor quality features and I don't think they belong in mcMMO. Feel free to yell at me in discord if you disagree.
I don't know what genius decided to make parties public by default, when I found out that parties had been changed to such a system I could barely contain my disgust. Parties are back to being private, you get invited by a party leader or party officer. That is the only way to join a party.
Version 2.1.196
Crossbows can now be fished up with enchantments
Version 2.1.217
Tree Feller will now break blocks within the limit instead of refusing to fell the entire tree (partial big tree destruction)
Mangrove trees resulting from growth are now marked as natural (existing trees marked unnatural before this update will not be retroactively fixed)
Fixed a bug removing comments from configs (see notes)
Fixed mouse-hover tooltip windows (thanks Greymagic27)
NOTES:
Regarding the secure chat feature Minecraft rolled out, once APIs have updated I will look into rolling support for that into admin/party chat.
Comments should no longer get removed from config but I haven't added any code to add missing comments back in, for now if you want comments you can delete the config file to regenerate it (sorry for the inconvenience)
Version 2.1.216
Reverted Unarmed changes from 2.1.215 (fixes block breaker/beserk active at all time for all players)
Added Sculk_* blocks to Mining XP
You can use Hoe(s) to gain mining XP, Hoe(s) won't benefit from Super Breaker nor will they activate it (see notes)
NOTES:
Hoe's being able to gain Mining XP is primarily for Sculk blocks which have Hoe as the fastest tool yet to me feel like Mining blocks, let me know what you think
The Sculk blocks don't quite fit perfectly as mining-related, especially since hoes are the fastest tool to use for them. Let me know what you think.
Version 2.1.215
Fixed Coal Blocks and potentially other fuel sources not showing burning animation to players (see notes)
Level up broadcasts from level milestones will now be visible to the player who achieved them
Fixed a bug where hovering over skill descriptions did not display anything (thanks Greymagic27)
Added Dripstone to experience.yml (thanks Greymagic27)
Added Mangrove_Log to experience.yml (should fix behavior for tree-feller etc)
Item in main hand is now used for Tree Feller drops (thanks destro174)
NOTES:
The burning animation bug is actually in Spigot, it takes an int for setBurnTime when it really should only take a short as the game is expecting a short value, I implemented a hacky workaround via Math.min
There is a bug where you may lose your config comments, this will be complex to solve, for now you can check our GitHub for the configs with comments.
Version 2.1.214
Temporarily removed FakePlayerAnimationEvent (see notes)
Players can now see their own level up broadcasts
NOTES:
Spigot updated PlayerAnimationEvent with an API break between versions 1.18 and 1.19, as a temporary fix for mcMMO to be able to support both of these
Minecraft versions I have temporarily removed FakePlayerAnimationEvent. I am working on a fix to dynamically use the correct API depending on the version of MC
as many people will likely be stuck on 1.18 for a while.
FakePlayerAnimationEvent existed to circumvent false positives on anti-cheat plugins such as NoCheat, however
I am unsure if it is still needed and removing it may have no ill effects.. however I cannot be certain.
Anti-cheat plugin authors should be informed to update if you run into false positives with mcMMO after this update so they can make the appropriate changes.
Version 2.1.213
Updated various mechanics to recognize and understand the new blocks
Added 'Packed_Mud' to mining xp
Added 'Mud_Bricks' to mining xp
Added 'Reinforced_Deepslate' to mining xp
Added 'Mud' to excavation xp
Added 'Muddy Mangrove Roots' to excavation xp
Added 'Mangrove_Roots' to woodcutting xp
Added 'Stripped_Mangrove_Log' to woodcutting xp
Added 'Stripped_Crimson_Stem' to woodcutting xp
Added 'Stripped_Warped_Stem' to woodcutting xp
Added 'Allay' to combat experience
Added 'Frog' to combat experience and taming experience
Added 'Tadpole' to combat experience
Added 'Warden' to combat experience
Changes to excavation treasures (requires manual editing or regenerating the config)
Added Mud as a block which can drop various treasures (see notes)
Added Muddy_Mangrove_Roots as a block which can drop various treasures (see notes)
Added Stick as a new excavation drop, which drops from mud and muddy mangrove roots (see notes)
Added Potato as a new excavation drop, which drops from mud and dirt (see notes)
Added Feather as a new excavation drop, which drops from mud (see notes)
Added Spyglass as a new excavation drop, which drops rarely from mud and dirt (see notes)
Added Trident as a new excavation drop, which drops somewhat rarely from mud, muddy mangrove roots, and clay (see notes)
Added Heart of the Sea as a new excavation drop, which drops very rarely from mud and requires a very high excavation level to appear
NOTES:
To get the new excavation drop list, the easiest way is to delete treasures.yml and mcMMO will regenerate it with the newest version
I'll likely be tweaking the treasures list in the near future, leave feedback on discord if you have suggestions
Version 2.1.212
An herbalism exploit has been patched (thanks WhatsTheBadNews)
Added 'ExploitFix.Combat.XPCeiling.Enabled' to experience.yml
Added 'ExploitFix.Combat.XPCeiling.Damage_Limit' to experience.yml
Single instances of combat damage above 100 give are capped to give the same reward as 100 by default (100 is a lot, but you can change this in settings)
NOTES: The damage ceiling won't affect server that don't have mobs running around with abnormally high health, if your server does you'll want to adjust this limit or disable it.
Version 2.1.211
Added /mmodebug info for players hitting other players
Fixed Immortal Player bug
Removed all of Spigot's buggy and deprecated DamageModifier API, this fixes the bug where players would become immortal when using certain other plugins
Rupture is back to doing "pure" damage (due to the above change)
NOTES:
Rupture damage will be tweaked based on feedback as it is dealing "pure" damage
Version 2.1.210
Fixed a memory leak involving mob metadata
Fixed a potential null pointer exception in InventoryListener
NOTES:
If you're having issues with "immortal players" this is a known plugin incompatibility between mcMMO and another plugin, I need more info on what plugins need to be present to cause it. Please post info to GitHub issues or tag me on discord.
There was a big rewrite in this update relating to how various types of metadata were being tracked/stored/retrieved
If you run into issues with this version of mcMMO, please post about it on GitHub
Version 2.1.209
Fixed a bug where some config files did not get trimmed completely
NOTES:
This should fix the issue for everyone, let me know if you still run into trouble!
Don't be afraid to ping me on discord
Version 2.1.208
Significantly rewrote to how mcMMO loads/updates config files
Fixed a bug where huge config files caused the server to take forever to start/shutdown
Fixed config files duplicating comments and updated their code to use Spigot API (thanks the456gamer)
mcMMO now repairs config files (removing duplicate comments, see notes)
Updated lithuanian locale (thanks dexasz)
NOTES:
Due to a change in Spigot mcMMO started growing config files at an alarming rate until they became so big they wouldn't load, and well before they got to that stage they slowed down loading the server
mcMMO now uses the Spigot API in a smarter way for config files
Version 2.1.207
Fixed an IndexOutOfBounds exception with our BlockTracker
Fixed a bug where leveling up a party at level cap would spam the chat with messages
mcMMO will no longer use enchanted repair materials (thanks JeBobs)
Added an option to allow enchanted repair materials 'Skills.Repair.Use_Enchanted_Materials' in config.yml
Temporarily rolling required Java version back to 16
Added unicode (UTF-8) support to locale files (no more UTF-16 codes needed)
Added locale key 'Scoreboard.Disabled' to en_US
Added locale key 'Scoreboard.NotSetupYet' to en_US
Fixed a bug where Salvage sent messages even though the event was cancelled (Thanks TheBusyBiscuit)
Version 2.1.206
Fixed a memory leak involving Herbalism under specific circumstances
Fixed a memory leak involving Rupture under specific circumstances
Fixed a memory leak involving Dodge
Fixed a memory leak involving Endermen and block pickups
Fixed a memory leak from plugin conflicts when double drops get activated
Fixed a memory leak that required a specific config.yml setup with mob health bars
You can no longer set mob health bars to -1 in config.yml to set it to display permanently (this was problematic behavior)
Fixed a bug preventing Action Bar messages from showing
Fixed a bug where Alchemy XP wasn't being granted
Lowered the default volume of level up from .75 to .3 in sounds.yml (delete sounds.yml to get this change automagically)
Updated adventure platform dependency
Updated to use Java 17
NOTES:
mcMMO will target the newest version of MC moving forward, any backwards compatibility with prior versions of Minecraft should be considered a side effect rather than intended.
Version 2.1.205
Fixed yet another exception preventing Alchemy from working (thanks NemuruYama)
Added some code to cleanup potential memory leaks
NOTES:
Sorry for the delay in this patch, I have had a terrible cold all weekend, feeling better now
Version 2.1.204
Fixed IndexOutOfBounds exception (thanks gecko10000) (related to Alchemy)
Added double smelt to copper ingot and netherite scrap (thanks Lyther)
Version 2.1.203
mcMMO now requires Java 16
mcMMO now requires the newest version of Minecraft (currently 1.17.1)
Fixed several API breaks (mostly affected Alchemy)
Fixed a bug relating to Shake percentages (thanks Lyther)
Fixed hexcolors not displaying correctly in level up milestone broadcasts (thanks gecko10000)
(API) Added deprecated constructors for PlayerProfile (thanks PikaMug)
mcMMO has had many of its dependencies updated to newer builds
NOTES:
If you want to play mcMMO on older versions, simply use 2.1.202 instead
Keeping mcMMO backwards compatible with older versions is getting messy, and I'd rather be able to focus my attention at newer features than having to make an elaborate build process (or alternatively hacky code) to support older versions of the game
Furthermore, it seems most people are playing 1.17.1 by a wide margin
You may have trouble compiling the source code if your maven is not setup to run JDK16, if you get any errors when compiling this is likely the reason
The data from bstats went into making this decision (shoutout to Qixils for typing this up too)
71.9% of servers are running 1.17.X
97.9% of servers are running ≥1.16
99.3% of servers are running ≥1.15
Version 2.1.202
Fixed a bug where mcMMO didn't reward XP for Kelp
Fixed a bug where mcMMO marked bonemealed Azalea trees as unnatural (and thus did not give XP or get affected by Tree Feller)
Added Amethyst_Block to experience.yml for Mining
Added Flowering Azalea Leaves to Tree Feller's white list
Fixed a bug where mcMMO didn't appropriately flag blocks as natural in some tree growing events
(SQL) Added more MySQL/MariaDB settings (allowPublicKeyRetrieval - thanks rosaage)
(API) Added CREATED_PARTY and DISBANDED_PARTY to EventReason (used in some party events - thanks PikaMug )
Party member name matching is no longer case sensitive (thanks Wariorrrr)
Updated zh_CN locale (thanks GhostDC)
Added some settings for over fishing (Settings are in experience.yml under Fishing_ExploitFix_Options - thanks tunagohan)
NOTES:
This means tree feller will correctly traverse flowering azalea leaves during its ability
Version 2.1.201
Tweaked the visual/audio effect for Rupture
(API) TNT is set as the source in Blast Mining (1.16.1 and up)
Fixed an exploit related to Ability Buffs remaining on tools
Blast Mining no longer drops Budding Amethyst since its not legal to obtain this item through normal gameplay
Added mcinspect and mmoinspect aliases to inspect command
Portuguese translation of Woodcutting changed back to Lenhador
Updated zh_CN (Chinese) locale, thanks GhostDC!
Major changes to zh_TW locale, thanks gregman98
Added '/skill keep' shortcut (for example /mining keep) thanks GriffinCodes
Impact is now more balanced as the formula has been changed (see notes) thanks emanondev
NOTES:
Impact will deal less durability damage to armors without unbreaking, and more to armors with unbreaking
Version 2.1.200
Fixed a major 1.17 exploit
Dodge will no longer trigger while blocking
Action Bar messages can now be disabled (thanks TheBusyBiscuit)
mcMMO is better at MC version parsing now (thanks stepech & TheBusyBiscuit)
Version 2.1.199
Fixed IndexOutOfBounds error for servers running 1.17 or higher
Fixed a bug that caused MySQL/MariaDB to malfunction for 1.17 (see notes)
Renamed Deepslate Lapis Lazuli Ore to Deepslate Lapis Ore in experience.yml and config.yml
Added some code to prevent mcMMO from breaking if it doesn't recognize the version of the game
Optimized CompatibilitySupportLayer - this handles some of the logic for supporting multiple versions of the game
Added Unit Tests for MinecraftGameVersion
NOTES:
I have temporarily disabled SSL for MySQL/MariaDB for 1.17 ( proper fix coming soon )
Version 2.1.198
Fixed a bug where Smelting didn't work with the new 1.17 materials
Updated dependency Adventure to 4.8.0 (thanks TheBusyBiscuit)
Version 2.1.197
This update adds compatibility for new mobs and blocks from 1.17
This build of mcMMO should be more compatible with certain versions of ViaVersion
Players are no longer launched from Minecarts when using a Fishing Rod (they are still dismounted) thanks lexikiq
Updated Japanese locale (thanks ViaSnake)
Updated Brazil Portuguese (pt_BR) locale (thanks Paulo Guilherme)
Added Goat to experience.yml for combat and taming
Added Axolotl to experience.yml for combat and taming
Added Glow_Squid to experience.yml for combat and taming
Added Glow Berries to Farmer's Diet
Updated Super Breaker to recognize the new pick-axe appropriate blocks
Updated Tree Feller to recognize Azalea Leaves
Added Rooted Dirt to experience.yml for Excavation
Added Small Dripleaf to experience.yml for Herbalism
Added Big Dripleaf to experience.yml for Herbalism
Added Moss Block to experience.yml for Herbalism
Added Cave Vines to experience.yml for Herbalism
Added Cave Vines Plant to experience.yml for Herbalism
Added Glow Lichen to experience.yml for Herbalism
Added Tuff to experience.yml for Mining
Added Calcite to experience.yml for Mining
Added Smooth Basalt to experience.yml for Mining
Added Block_Of_Amethyst to experience.yml for Mining
Added Budding Amethyst to experience.yml for Mining
Added Small_Amethyst_Bud to experience.yml for Mining
Added Medium Amethyst Bud to experience.yml for Mining
Added Large Amethyst Bud to experience.yml for Mining
Added Amethyst Cluster to experience.yml for Mining
Added Deepslate to experience.yml for Mining
Added Cobbled Deepslate to experience.yml for Mining
Added Copper Ore to experience.yml for Mining
Added Deepslate Redstone Ore to experience.yml for Mining
Added Deepslate Copper Ore to experience.yml for Mining
Added Deepslate Coal Ore to experience.yml for Mining
Added Deepslate Diamond Ore to experience.yml for Mining
Added Deepslate Emerald Ore to experience.yml for Mining
Added Deepslate Iron Ore to experience.yml for Mining
Added Deepslate Gold Ore to experience.yml for Mining
Added Deepslate Lapis Lazuli Ore to experience.yml for Mining
Added Lapis Lazuli Ore to experience.yml for Mining (was missing)
Added Moss Block to Bonus Drops for Herbalism in config.yml
Added Glow Berries to Bonus Drops for Herbalism in config.yml
Added Cave Vines to Bonus Drops for Herbalism in config.yml
Added Cave Vines Plant to Bonus Drops for Herbalism in config.yml
Added Tuff to Bonus Drops for Mining in config.yml
Added Amethyst Shard to Bonus Drops for Mining in config.yml
Added Calcite to Bonus Drops for Mining in config.yml
Added Smooth Basalt to Bonus Drops for Mining in config.yml
Added Block_Of_Amethyst to Bonus Drops for Mining in config.yml
Added Budding Amethyst to Bonus Drops for Mining in config.yml
Added Small_Amethyst_Bud to Bonus Drops for Mining in config.yml
Added Medium Amethyst Bud to Bonus Drops for Mining in config.yml
Added Large Amethyst Bud to Bonus Drops for Mining in config.yml
Added Amethyst Cluster to Bonus Drops for Mining in config.yml
Added Deepslate to Bonus Drops for Mining in config.yml
Added Cobbled Deepslate to Bonus Drops for Mining in config.yml
Added Raw Iron to Bonus Drops for Mining in config.yml
Added Raw Gold to Bonus Drops for Mining in config.yml
Added Raw Copper to Bonus Drops for Mining in config.yml
Added Copper Ore to Bonus Drops for Mining in config.yml
Added Deepslate Redstone Ore to Bonus Drops for Mining in config.yml
Added Deepslate Copper Ore to Bonus Drops for Mining in config.yml
Added Deepslate Coal Ore to Bonus Drops for Mining in config.yml
Added Deepslate Diamond Ore to Bonus Drops for Mining in config.yml
Added Deepslate Emerald Ore to Bonus Drops for Mining in config.yml
Added Deepslate Iron Ore to Bonus Drops for Mining in config.yml
Added Deepslate Gold Ore to Bonus Drops for Mining in config.yml
Added Deepslate Lapis Lazuli Ore to Bonus Drops for Mining in config.yml
Added Lapis Lazuli Ore to Bonus Drops for Mining in config.yml (was missing)
Added Cobbled Deepslate to experience.yml for Smelting
Added Raw Copper to experience.yml for Smelting
Added Raw Iron to experience.yml for Smelting
Added Raw Gold to experience.yml for Smelting
Added Copper Ore to experience.yml for Smelting
Added Deepslate Redstone Ore to experience.yml for Smelting
Added Deepslate Copper Ore to experience.yml for Smelting
Added Deepslate Coal Ore to experience.yml for Smelting
Added Deepslate Diamond Ore to experience.yml for Smelting
Added Deepslate Emerald Ore to experience.yml for Smelting
Added Deepslate Iron Ore to experience.yml for Smelting
Added Deepslate Gold Ore to experience.yml for Smelting
Added Deepslate Lapis Lazuli Ore to experience.yml for Smelting
Added Lapis Lazuli Ore to experience.yml for Smelting (was missing)
NOTES:
Another patch will follow this one shortly to add more 1.17 support, I am waiting on the Spigot API to test some stuff which isn't out yet.
You shouldn't need to edit your configs for this update, your configs should update automatically.
Expect some patches following this update for Axolotl and other new entities, waiting on the Spigot API to become available
If you run into any issues with ViaVersion or ViaBackwards, use the latest dev builds for each.
Version 2.1.196
Removed the explosion from Rupture
Adjusted Rupture to play its particle effect less often
Fixed a bug where Rupture never applied to additional targets during Serrated Strikes
Fixed a bug where players without Rupture permission could use Rupture during Serrated Strikes
Fixed a possible null error for our SelfListener
Added locale string 'Swords.Combat.Rupture.Note.Update.One'
Updated locale string 'Guides.Swords.Section.1'
Crossbows can now be fished up with enchantments
(API) Added McMMOEntityDamageByRuptureEvent (thanks qixils)
NOTES:
For now Rupture is non-lethal, I may add back a lethal component at the end of its damage
Rupture will be in a state of change for a while as I receive feedback (give me feedback in Discord!)
Crossbows is not in the default fishing loot list, you'd have to add it yourself.
For Devs: McMMOEntityDamageByRuptureEvent extends EntityDamageByEntityEvent and uses CUSTOM type damage
Version 2.1.195
Fixed a null connection error which affected some SQL users

202
pom.xml Executable file → Normal file
View File

@@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.gmail.nossr50.mcMMO</groupId>
<artifactId>mcMMO</artifactId>
<version>2.2.000-ALPHA-SNAPSHOT</version>
<version>2.1.222</version>
<name>mcMMO</name>
<url>https://github.com/mcMMO-Dev/mcMMO</url>
<scm>
@@ -14,6 +14,9 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
<java.version>16</java.version>
</properties>
<issueManagement>
@@ -72,28 +75,37 @@
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<version>3.0.0-M7</version>
<configuration>
<junitArtifactName>org.junit.jupiter:junit-jupiter</junitArtifactName>
<trimStackTrace>false</trimStackTrace>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
<version>3.0.0-M7</version>
<configuration>
<junitArtifactName>org.junit.jupiter:junit-jupiter</junitArtifactName>
<trimStackTrace>false</trimStackTrace>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.2</version>
<version>3.0.0-M6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.10.1</version>
<configuration>
<release>16</release>
<compilerArgs>
<arg>-parameters</arg> <!-- used for ACF syntax stuff -->
</compilerArgs>
<source>1.8</source>
<target>1.8</target>
<excludes>
</excludes>
</configuration>
@@ -118,7 +130,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.3</version>
<version>3.3.0</version>
<configuration>
<artifactSet>
<includes>
@@ -131,7 +143,6 @@
<include>net.kyori:adventure-text-serializer-gson</include>
<include>net.kyori:adventure-platform-bukkit</include>
<include>net.kyori:adventure-platform-api</include>
<include>net.kyori:adventure-platform-common</include>
<include>net.kyori:adventure-platform-viaversion</include>
<include>net.kyori:adventure-platform-facet</include>
<include>net.kyori:adventure-nbt</include>
@@ -143,25 +154,17 @@
<include>net.kyori:adventure-text-serializer-craftbukkit</include>
<include>net.kyori:adventure-text-serializer-gson-legacy-impl</include>
<include>co.aikar:acf-bukkit</include>
<include>com.neetgames:mcMMO-API</include>
<!-- <include>com.neetgames:jmal</include>-->
<include>com.neetgames:NEET-lib</include>
</includes>
</artifactSet>
<!-- <dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>-->
<relocations>
<relocation>
<pattern>net.kyori.examination</pattern>
<shadedPattern>com.gmail.nossr50.kyori.examination</shadedPattern>
<shadedPattern>com.gmail.nossr50.mcmmo.kyori.examination</shadedPattern>
</relocation>
<relocation>
<pattern>net.kyori.adventure</pattern>
<shadedPattern>com.gmail.nossr50.mcmmo.kyori.adventure</shadedPattern>
</relocation>
<relocation>
<pattern>com.neetgames.neetlib</pattern>
<shadedPattern>com.gmail.nossr50.neetlib</shadedPattern>
</relocation>
<relocation>
<pattern>co.aikar.commands</pattern>
<shadedPattern>com.gmail.nossr50.mcmmo.acf</shadedPattern> <!-- Replace this -->
@@ -186,6 +189,10 @@
<pattern>org.bstats</pattern>
<shadedPattern>com.gmail.nossr50.mcmmo.metrics.bstats</shadedPattern>
</relocation>
<relocation>
<pattern>com.tcoded.folialib</pattern>
<shadedPattern>com.gmail.nossr50.mcmmo.folialib</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
@@ -202,15 +209,18 @@
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-file</artifactId>
<version>2.2</version>
<version>3.5.2</version>
</extension>
</extensions>
</build>
<pluginRepositories>
<pluginRepository>
<id>maven-snapshots</id>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>neet-games</id>
<url>https://nexus.neetgames.com/repository/maven-public/</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
@@ -220,8 +230,8 @@
<url>https://repo.codemc.org/repository/maven-public</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>https://maven.sk89q.com/repo/</url>
<id>enginehub-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository> <!-- for development builds -->
<id>sonatype-oss</id>
@@ -231,122 +241,90 @@
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
<repository> <!-- for development builds -->
<id>sonatype-oss</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
<repository>
<id>sonatype-oss-snapshots1</id>
<url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
<repository>
<id>devmart-other</id>
<url>https://nexuslite.gcnt.net/repos/other/</url>
</repository>
<!-- ... -->
<!-- ... -->
</repositories>
<!-- <dependencyManagement>-->
<!-- <dependencies>-->
<!-- <dependency>-->
<!-- <groupId>org.junit</groupId>-->
<!-- <artifactId>junit-bom</artifactId>-->
<!-- <version>5.7.1</version>-->
<!-- <type>pom</type>-->
<!-- <scope>import</scope>-->
<!-- </dependency>-->
<!-- </dependencies>-->
<!-- </dependencyManagement>-->
<dependencies>
<dependency>
<groupId>com.neetgames</groupId>
<artifactId>mcMMO-API</artifactId>
<version>0.01.00-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.neetgames</groupId>
<artifactId>jmal-core</artifactId>
<version>0.01.00-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.neetgames</groupId>
<artifactId>jmal-bukkit</artifactId>
<version>0.01.00-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.neetgames</groupId>
<artifactId>NEET-lib</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.github.seeseemelk</groupId>
<artifactId>MockBukkit-v1.16</artifactId>
<version>0.25.0</version>
<scope>test</scope>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>co.aikar</groupId>
<artifactId>acf-bukkit</artifactId> <!-- Don't forget to replace this -->
<version>0.5.0-SNAPSHOT</version> <!-- Replace this as well -->
<version>0.5.1-SNAPSHOT</version> <!-- Replace this as well -->
</dependency>
<!-- adventure-api, adventure-text-serializer-gson, adventure-platform-bukkit-->
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-serializer-gson</artifactId>
<version>4.7.0</version>
<version>4.13.0</version>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-api</artifactId>
<version>4.7.0</version>
<version>4.13.0</version>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-nbt</artifactId>
<version>4.7.0</version>
<version>4.13.0</version>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-key</artifactId>
<version>4.7.0</version>
<version>4.13.0</version>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-text-serializer-gson-legacy-impl</artifactId>
<version>4.7.0</version>
<version>4.13.0</version>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-platform-bukkit</artifactId>
<version>4.0.0-SNAPSHOT</version>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-platform-api</artifactId>
<version>4.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>net.kyori</groupId>
<artifactId>adventure-platform-common</artifactId>
<version>4.0.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>net.kyori</groupId>
<artifactId>adventure-nbt</artifactId>
</exclusion>
</exclusions>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.scm</groupId>
<artifactId>maven-scm-provider-gitexe</artifactId>
<version>1.9.4</version>
<version>2.0.0-M1</version>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>2.2.1</version>
<version>3.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<version>1.19.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-core</artifactId>
<version>7.0.1-SNAPSHOT</version>
<version>7.0.7</version>
<exclusions>
<exclusion>
<!-- We use jetbrains instead. Excluding this -->
@@ -369,50 +347,44 @@
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.7</version>
<artifactId>junit-jupiter</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.8.0</version>
<version>4.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>4.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>7.0.52</version>
<version>10.1.0-M17</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>19.0.0</version>
<version>23.0.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.0.0-jre</version> <!-- At this time Spigot is including 29.0 Guava classes that we are using -->
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.tcoded</groupId>
<artifactId>FoliaLib</artifactId>
<version>0.2.4</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@@ -2,7 +2,7 @@ package com.gmail.nossr50.api;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.MetadataConstants;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
@@ -84,7 +84,7 @@ public final class AbilityAPI {
public static boolean isBleeding(LivingEntity entity) {
if(entity.isValid()) {
if(entity.hasMetadata(mcMMO.RUPTURE_META_KEY)) {
if(entity.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) {
return true;
}
}

View File

@@ -1,142 +1,142 @@
//package com.gmail.nossr50.api;
//
//import com.gmail.nossr50.datatypes.chat.ChatChannel;
//import com.gmail.nossr50.mcMMO;
//import com.gmail.nossr50.util.player.UserManager;
//import org.bukkit.entity.Player;
//
//public final class ChatAPI {
// private ChatAPI() {}
//
//// /**
//// * Send a message to all members of a party
//// * </br>
//// * This function is designed for API usage.
//// *
//// * @param plugin The plugin sending the message
//// * @param sender The name of the sender
//// * @param displayName The display name of the sender
//// * @param party The name of the party to send to
//// * @param message The message to send
//// */
//// public static void sendPartyChat(Plugin plugin, String sender, String displayName, String party, String message) {
//// getPartyChatManager(plugin, party).handleChat(sender, displayName, message);
//// }
////
//// /**
//// * Send a message to all members of a party
//// * </br>
//// * This function is designed for API usage.
//// *
//// * @param plugin The plugin sending the message
//// * @param sender The name of the sender to display in the chat
//// * @param party The name of the party to send to
//// * @param message The message to send
//// */
//// public static void sendPartyChat(Plugin plugin, String sender, String party, String message) {
//// getPartyChatManager(plugin, party).handleChat(sender, message);
//// }
////
//// /**
//// * Send a message to administrators
//// * </br>
//// * This function is designed for API usage.
//// *
//// * @param plugin The plugin sending the message
//// * @param sender The name of the sender
//// * @param displayName The display name of the sender
//// * @param message The message to send
//// */
//// public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) {
//// ChatManagerFactory.getChatManager(plugin, ChatChannel.ADMIN).handleChat(sender, displayName, message);
//// }
////
//// /**
//// * Send a message to administrators
//// * </br>
//// * This function is designed for API usage.
//// *
//// * @param plugin The plugin sending the message
//// * @param sender The name of the sender to display in the chat
//// * @param message The message to send
//// */
//// public static void sendAdminChat(Plugin plugin, String sender, String message) {
//// ChatManagerFactory.getChatManager(plugin, ChatChannel.ADMIN).handleChat(sender, message);
//// }
//
package com.gmail.nossr50.api;
import com.gmail.nossr50.datatypes.chat.ChatChannel;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.entity.Player;
public final class ChatAPI {
private ChatAPI() {}
// /**
// * Check if a player is currently talking in party chat.
// * Send a message to all members of a party
// * </br>
// * This function is designed for API usage.
// *
// * @param player The player to check
// * @return true if the player is using party chat, false otherwise
// * @param plugin The plugin sending the message
// * @param sender The name of the sender
// * @param displayName The display name of the sender
// * @param party The name of the party to send to
// * @param message The message to send
// */
// public static boolean isUsingPartyChat(Player player) {
// return UserManager.getPlayer(player).getChatChannel() == ChatChannel.PARTY;
// public static void sendPartyChat(Plugin plugin, String sender, String displayName, String party, String message) {
// getPartyChatManager(plugin, party).handleChat(sender, displayName, message);
// }
//
// /**
// * Check if a player is currently talking in party chat.
// * Send a message to all members of a party
// * </br>
// * This function is designed for API usage.
// *
// * @param playerName The name of the player to check
// * @return true if the player is using party chat, false otherwise
// * @param plugin The plugin sending the message
// * @param sender The name of the sender to display in the chat
// * @param party The name of the party to send to
// * @param message The message to send
// */
// public static boolean isUsingPartyChat(String playerName) {
// return UserManager.getPlayer(playerName).getChatChannel() == ChatChannel.PARTY;
// public static void sendPartyChat(Plugin plugin, String sender, String party, String message) {
// getPartyChatManager(plugin, party).handleChat(sender, message);
// }
//
// /**
// * Check if a player is currently talking in admin chat.
// * Send a message to administrators
// * </br>
// * This function is designed for API usage.
// *
// * @param player The player to check
// * @return true if the player is using admin chat, false otherwise
// * @param plugin The plugin sending the message
// * @param sender The name of the sender
// * @param displayName The display name of the sender
// * @param message The message to send
// */
// public static boolean isUsingAdminChat(Player player) {
// return UserManager.getPlayer(player).getChatChannel() == ChatChannel.ADMIN;
// public static void sendAdminChat(Plugin plugin, String sender, String displayName, String message) {
// ChatManagerFactory.getChatManager(plugin, ChatChannel.ADMIN).handleChat(sender, displayName, message);
// }
//
// /**
// * Check if a player is currently talking in admin chat.
// * Send a message to administrators
// * </br>
// * This function is designed for API usage.
// *
// * @param playerName The name of the player to check
// * @return true if the player is using admin chat, false otherwise
// * @param plugin The plugin sending the message
// * @param sender The name of the sender to display in the chat
// * @param message The message to send
// */
// public static boolean isUsingAdminChat(String playerName) {
// return UserManager.getPlayer(playerName).getChatChannel() == ChatChannel.ADMIN;
// public static void sendAdminChat(Plugin plugin, String sender, String message) {
// ChatManagerFactory.getChatManager(plugin, ChatChannel.ADMIN).handleChat(sender, message);
// }
//
// /**
// * Toggle the party chat mode of a player.
// *
// * @param player The player to toggle party chat on.
// */
// public static void togglePartyChat(Player player) {
// mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.PARTY);
// }
//
// /**
// * Toggle the party chat mode of a player.
// *
// * @param playerName The name of the player to toggle party chat on.
// */
// public static void togglePartyChat(String playerName) {
// mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.PARTY);
// }
//
// /**
// * Toggle the admin chat mode of a player.
// *
// * @param player The player to toggle admin chat on.
// */
// public static void toggleAdminChat(Player player) {
// mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.ADMIN);
// }
//
// /**
// * Toggle the admin chat mode of a player.
// *
// * @param playerName The name of the player to toggle party chat on.
// */
// public static void toggleAdminChat(String playerName) {
// mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.ADMIN);
// }
//}
/**
* Check if a player is currently talking in party chat.
*
* @param player The player to check
* @return true if the player is using party chat, false otherwise
*/
public static boolean isUsingPartyChat(Player player) {
return UserManager.getPlayer(player).getChatChannel() == ChatChannel.PARTY;
}
/**
* Check if a player is currently talking in party chat.
*
* @param playerName The name of the player to check
* @return true if the player is using party chat, false otherwise
*/
public static boolean isUsingPartyChat(String playerName) {
return UserManager.getPlayer(playerName).getChatChannel() == ChatChannel.PARTY;
}
/**
* Check if a player is currently talking in admin chat.
*
* @param player The player to check
* @return true if the player is using admin chat, false otherwise
*/
public static boolean isUsingAdminChat(Player player) {
return UserManager.getPlayer(player).getChatChannel() == ChatChannel.ADMIN;
}
/**
* Check if a player is currently talking in admin chat.
*
* @param playerName The name of the player to check
* @return true if the player is using admin chat, false otherwise
*/
public static boolean isUsingAdminChat(String playerName) {
return UserManager.getPlayer(playerName).getChatChannel() == ChatChannel.ADMIN;
}
/**
* Toggle the party chat mode of a player.
*
* @param player The player to toggle party chat on.
*/
public static void togglePartyChat(Player player) {
mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.PARTY);
}
/**
* Toggle the party chat mode of a player.
*
* @param playerName The name of the player to toggle party chat on.
*/
public static void togglePartyChat(String playerName) {
mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.PARTY);
}
/**
* Toggle the admin chat mode of a player.
*
* @param player The player to toggle admin chat on.
*/
public static void toggleAdminChat(Player player) {
mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(player), ChatChannel.ADMIN);
}
/**
* Toggle the admin chat mode of a player.
*
* @param playerName The name of the player to toggle party chat on.
*/
public static void toggleAdminChat(String playerName) {
mcMMO.p.getChatManager().setOrToggleChatChannel(UserManager.getPlayer(playerName), ChatChannel.ADMIN);
}
}

View File

@@ -35,13 +35,13 @@ public final class ExperienceAPI {
* @param skillType A string that may or may not be a skill
* @return true if this is a valid mcMMO skill
*/
public static boolean isValidSkillType(String skillType) {
public static boolean isValidSkillType(@NotNull String skillType) {
return mcMMO.p.getSkillTools().matchSkill(skillType) != null;
}
/**
* Start the task that gives combat XP.
* Processes combat XP like mcMMO normally would, so mcMMO will check whether or not the entity should reward XP when giving out the XP
* Processes combat XP like mcMMO normally would, so mcMMO will check whether the entity should reward XP when giving out the XP
*
* @param mcMMOPlayer The attacking player
* @param target The defending entity
@@ -56,7 +56,7 @@ public final class ExperienceAPI {
/**
* Start the task that gives combat XP.
* Processes combat XP like mcMMO normally would, so mcMMO will check whether or not the entity should reward XP when giving out the XP
* Processes combat XP like mcMMO normally would, so mcMMO will check whether the entity should reward XP when giving out the XP
*
* @param mcMMOPlayer The attacking player
* @param target The defending entity

View File

@@ -0,0 +1,6 @@
package com.gmail.nossr50.api;
public enum FakeBlockBreakEventType {
FAKE,
TREE_FELLER
}

View File

@@ -1,17 +1,17 @@
//package com.gmail.nossr50.api;
//
//public enum ItemSpawnReason {
// ARROW_RETRIEVAL_ACTIVATED, //Players sometimes can retrieve arrows instead of losing them when hitting a mob
// EXCAVATION_TREASURE, //Any drops when excavation treasures activate fall under this
// FISHING_EXTRA_FISH, //A config setting allows more fish to be found when fishing, the extra fish are part of this
// FISHING_SHAKE_TREASURE, //When using a fishing rod on a mob and finding a treasure via Shake
// HYLIAN_LUCK_TREASURE, //When finding a treasure in grass via hylian luck
// BLAST_MINING_DEBRIS_NON_ORES, //The non-ore debris that are dropped from blast mining
// BLAST_MINING_ORES, //The ore(s) which may include player placed ores being dropped from blast mining
// BLAST_MINING_ORES_BONUS_DROP, //Any bonus ores that drop from a result of a players Mining skills
// UNARMED_DISARMED_ITEM, //When you disarm an opponent and they drop their weapon
// SALVAGE_ENCHANTMENT_BOOK, //When you salvage an enchanted item and get the enchantment back in book form
// SALVAGE_MATERIALS, //When you salvage an item and get materials back
// TREE_FELLER_DISPLACED_BLOCK,
// BONUS_DROPS, //Can be from Mining, Woodcutting, Herbalism, etc
//}
package com.gmail.nossr50.api;
public enum ItemSpawnReason {
ARROW_RETRIEVAL_ACTIVATED, //Players sometimes can retrieve arrows instead of losing them when hitting a mob
EXCAVATION_TREASURE, //Any drops when excavation treasures activate fall under this
FISHING_EXTRA_FISH, //A config setting allows more fish to be found when fishing, the extra fish are part of this
FISHING_SHAKE_TREASURE, //When using a fishing rod on a mob and finding a treasure via Shake
HYLIAN_LUCK_TREASURE, //When finding a treasure in grass via hylian luck
BLAST_MINING_DEBRIS_NON_ORES, //The non-ore debris that are dropped from blast mining
BLAST_MINING_ORES, //The ore(s) which may include player placed ores being dropped from blast mining
BLAST_MINING_ORES_BONUS_DROP, //Any bonus ores that drop from a result of a players Mining skills
UNARMED_DISARMED_ITEM, //When you disarm an opponent and they drop their weapon
SALVAGE_ENCHANTMENT_BOOK, //When you salvage an enchanted item and get the enchantment back in book form
SALVAGE_MATERIALS, //When you salvage an item and get materials back
TREE_FELLER_DISPLACED_BLOCK,
BONUS_DROPS, //Can be from Mining, Woodcutting, Herbalism, etc
}

View File

@@ -0,0 +1,12 @@
package com.gmail.nossr50.api;
import com.gmail.nossr50.events.fake.FakeBlockBreakEvent;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class TreeFellerBlockBreakEvent extends FakeBlockBreakEvent {
public TreeFellerBlockBreakEvent(@NotNull Block theBlock, @NotNull Player player) {
super(theBlock, player);
}
}

View File

@@ -0,0 +1,11 @@
package com.gmail.nossr50.api.exceptions;
import org.jetbrains.annotations.NotNull;
public class IncompleteNamespacedKeyRegister extends RuntimeException {
private static final long serialVersionUID = -6905157273569301219L;
public IncompleteNamespacedKeyRegister(@NotNull String message) {
super(message);
}
}

View File

@@ -0,0 +1,9 @@
package com.gmail.nossr50.api.exceptions;
public class InvalidFormulaTypeException extends RuntimeException {
private static final long serialVersionUID = 3368670229490121886L;
public InvalidFormulaTypeException() {
super("That is not a valid FormulaType.");
}
}

View File

@@ -0,0 +1,9 @@
package com.gmail.nossr50.api.exceptions;
public class InvalidPlayerException extends RuntimeException {
private static final long serialVersionUID = 907213002618581385L;
public InvalidPlayerException() {
super("That player does not exist in the database.");
}
}

View File

@@ -0,0 +1,13 @@
package com.gmail.nossr50.api.exceptions;
public class InvalidSkillException extends RuntimeException {
private static final long serialVersionUID = 942705284195791157L;
public InvalidSkillException() {
super("That is not a valid skill.");
}
public InvalidSkillException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,9 @@
package com.gmail.nossr50.api.exceptions;
public class InvalidXPGainReasonException extends RuntimeException {
private static final long serialVersionUID = 4427052841957931157L;
public InvalidXPGainReasonException() {
super("That is not a valid XPGainReason.");
}
}

View File

@@ -0,0 +1,12 @@
package com.gmail.nossr50.api.exceptions;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class McMMOPlayerNotFoundException extends RuntimeException {
private static final long serialVersionUID = 761917904993202836L;
public McMMOPlayerNotFoundException(@NotNull Player player) {
super("McMMOPlayer object was not found for [NOTE: This can mean the profile is not loaded yet! : " + player.getName() + " " + player.getUniqueId());
}
}

View File

@@ -6,13 +6,13 @@ import com.gmail.nossr50.chat.mailer.AdminChatMailer;
import com.gmail.nossr50.chat.mailer.PartyChatMailer;
import com.gmail.nossr50.config.ChatConfig;
import com.gmail.nossr50.datatypes.chat.ChatChannel;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.text.StringUtils;
import com.neetgames.mcmmo.party.Party;
import com.neetgames.mcmmo.player.OnlineMMOPlayer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.TextComponent;
import org.bukkit.command.ConsoleCommandSender;
@@ -43,9 +43,9 @@ public class ChatManager {
*
* @param mmoPlayer target player
* @param rawMessage the raw message from the player as it was typed
* @param isAsync whether or not this is getting processed via async
* @param isAsync whether this is getting processed via async
*/
public void processPlayerMessage(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull String rawMessage, boolean isAsync) {
public void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull String rawMessage, boolean isAsync) {
processPlayerMessage(mmoPlayer, mmoPlayer.getChatChannel(), rawMessage, isAsync);
}
@@ -56,7 +56,7 @@ public class ChatManager {
* @param args the raw command arguments from the player
* @param chatChannel target channel
*/
public void processPlayerMessage(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull String[] args, @NotNull ChatChannel chatChannel) {
public void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull String[] args, @NotNull ChatChannel chatChannel) {
String chatMessageWithoutCommand = buildChatMessage(args);
//Commands are never async
@@ -69,9 +69,9 @@ public class ChatManager {
* @param mmoPlayer target player
* @param chatChannel target chat channel
* @param rawMessage raw chat message as it was typed
* @param isAsync whether or not this is getting processed via async
* @param isAsync whether this is getting processed via async
*/
private void processPlayerMessage(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull ChatChannel chatChannel, @NotNull String rawMessage, boolean isAsync) {
private void processPlayerMessage(@NotNull McMMOPlayer mmoPlayer, @NotNull ChatChannel chatChannel, @NotNull String rawMessage, boolean isAsync) {
switch (chatChannel) {
case ADMIN:
adminChatMailer.processChatMessage(mmoPlayer.getPlayerAuthor(), rawMessage, isAsync, Permissions.colorChat(mmoPlayer.getPlayer()));
@@ -119,19 +119,19 @@ public class ChatManager {
}
/**
* Change the chat channel of a {@link OnlineMMOPlayer}
* Change the chat channel of a {@link McMMOPlayer}
* Targeting the channel a player is already in will remove that player from the chat channel
* @param mmoPlayer target player
* @param targetChatChannel target chat channel
*/
public void setOrToggleChatChannel(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull ChatChannel targetChatChannel) {
public void setOrToggleChatChannel(@NotNull McMMOPlayer mmoPlayer, @NotNull ChatChannel targetChatChannel) {
if(targetChatChannel == mmoPlayer.getChatChannel()) {
//Disabled message
Misc.adaptPlayer(mmoPlayer).sendMessage(LocaleLoader.getString("Chat.Channel.Off", StringUtils.getCapitalized(targetChatChannel.toString())));
mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Chat.Channel.Off", StringUtils.getCapitalized(targetChatChannel.toString())));
mmoPlayer.setChatMode(ChatChannel.NONE);
} else {
mmoPlayer.setChatMode(targetChatChannel);
Misc.adaptPlayer(mmoPlayer).sendMessage(LocaleLoader.getString("Chat.Channel.On", StringUtils.getCapitalized(targetChatChannel.toString())));
mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Chat.Channel.On", StringUtils.getCapitalized(targetChatChannel.toString())));
}
}
@@ -155,14 +155,14 @@ public class ChatManager {
}
/**
* Whether or not the player is allowed to send a message to the chat channel they are targeting
* Whether the player is allowed to send a message to the chat channel they are targeting
* @param mmoPlayer target player
* @return true if the player can send messages to that chat channel
*/
public boolean isMessageAllowed(@NotNull OnlineMMOPlayer mmoPlayer) {
public boolean isMessageAllowed(@NotNull McMMOPlayer mmoPlayer) {
switch (mmoPlayer.getChatChannel()) {
case ADMIN:
if(Misc.adaptPlayer(mmoPlayer).isOp() || Permissions.adminChat(mmoPlayer.getPlayer())) {
if(mmoPlayer.getPlayer().isOp() || Permissions.adminChat(mmoPlayer.getPlayer())) {
return true;
}
break;
@@ -197,7 +197,7 @@ public class ChatManager {
}
/**
* Whether or not a specific chat channel is enabled
* Whether a specific chat channel is enabled
* ChatChannels are enabled/disabled via user config
*
* If chat is disabled, this always returns false

View File

@@ -1,7 +1,8 @@
package com.gmail.nossr50.chat;
import com.neetgames.mcmmo.party.Party;
import com.neetgames.mcmmo.player.OnlineMMOPlayer;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
@@ -22,9 +23,8 @@ public class SamePartyPredicate<T extends CommandSender> implements Predicate<T>
if(t instanceof ConsoleCommandSender) {
return false; //Party audiences are special, we exclude console from them to avoid double messaging since we send a more verbose version to consoles
} else {
if(t instanceof Player) {
Player player = (Player) t;
OnlineMMOPlayer mcMMOPlayer = UserManager.queryPlayer(player);
if(t instanceof Player player) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if(mcMMOPlayer != null) {
return mcMMOPlayer.getParty() == party;
}

View File

@@ -73,7 +73,7 @@ public abstract class AbstractPlayerAuthor implements Author {
* Sanitized names are associated with a {@link ChatChannel} as different chat channels have different chat name settings
*
* @param chatChannel target chat channel
* @param useDisplayName whether or not to use this authors display name
* @param useDisplayName whether to use this authors display name
*/
private void updateSanitizedNameCache(@NotNull ChatChannel chatChannel, boolean useDisplayName) {
if(useDisplayName) {

View File

@@ -17,14 +17,14 @@ public interface Author extends Identity {
@NotNull String getAuthoredName(@NotNull ChatChannel chatChannel);
/**
* Whether or not this author is a {@link org.bukkit.command.ConsoleCommandSender}
* Whether this author is a {@link org.bukkit.command.ConsoleCommandSender}
*
* @return true if this author is the console
*/
boolean isConsole();
/**
* Whether or not this author is a {@link org.bukkit.entity.Player}
* Whether this author is a {@link org.bukkit.entity.Player}
* @return true if this author is a player
*/
boolean isPlayer();

View File

@@ -73,8 +73,8 @@ public class AdminChatMailer extends AbstractChatMailer {
*
* @param author the author
* @param rawString the raw message as the author typed it before any styling
* @param isAsync whether or not this is being processed asynchronously
* @param canColor whether or not the author can use colors in chat
* @param isAsync whether this is being processed asynchronously
* @param canColor whether the author can use colors in chat
*/
public void processChatMessage(@NotNull Author author, @NotNull String rawString, boolean isAsync, boolean canColor) {
AdminChatMessage chatMessage = new AdminChatMessage(pluginRef, author, constructAudience(), rawString, addStyle(author, rawString, canColor));

View File

@@ -4,12 +4,12 @@ import com.gmail.nossr50.chat.author.Author;
import com.gmail.nossr50.chat.message.ChatMessage;
import com.gmail.nossr50.chat.message.PartyChatMessage;
import com.gmail.nossr50.datatypes.chat.ChatChannel;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOChatEvent;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.text.TextUtils;
import com.neetgames.mcmmo.party.Party;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.TextComponent;
import org.bukkit.Bukkit;
@@ -27,8 +27,8 @@ public class PartyChatMailer extends AbstractChatMailer {
*
* @param author the author
* @param rawString the raw message as the author typed it before any styling
* @param isAsync whether or not this is being processed asynchronously
* @param canColor whether or not the author can use colors in chat
* @param isAsync whether this is being processed asynchronously
* @param canColor whether the author can use colors in chat
*/
public void processChatMessage(@NotNull Author author, @NotNull String rawString, @NotNull Party party, boolean isAsync, boolean canColor, boolean isLeader) {
PartyChatMessage chatMessage = new PartyChatMessage(pluginRef, author, constructPartyAudience(party), rawString, addStyle(author, rawString, canColor, isLeader), party);

View File

@@ -2,12 +2,12 @@ package com.gmail.nossr50.chat.message;
import com.gmail.nossr50.chat.author.Author;
import com.gmail.nossr50.datatypes.chat.ChatChannel;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.base.Objects;
import com.neetgames.mcmmo.party.Party;
import com.neetgames.mcmmo.player.OnlineMMOPlayer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.TextComponent;
import org.bukkit.entity.Player;
@@ -61,7 +61,7 @@ public class PartyChatMessage extends AbstractChatMessage {
*/
private void messagePartyChatSpies(@NotNull TextComponent spyMessage) {
//Find the people with permissions
for(OnlineMMOPlayer mcMMOPlayer : UserManager.getPlayers()) {
for(McMMOPlayer mcMMOPlayer : UserManager.getPlayers()) {
Player player = mcMMOPlayer.getPlayer();
//Check for toggled players

View File

@@ -0,0 +1,336 @@
package com.gmail.nossr50.commands;
import com.gmail.nossr50.datatypes.skills.ModConfigType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Misc;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public class McImportCommand implements CommandExecutor {
int fileAmount;
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 0) {
importModConfig();
return true;
}
return false;
}
public boolean importModConfig() {
String importFilePath = mcMMO.getModDirectory() + File.separator + "import";
File importFile = new File(importFilePath, "import.log");
mcMMO.p.getLogger().info("Starting import of mod materials...");
fileAmount = 0;
HashMap<ModConfigType, ArrayList<String>> materialNames = new HashMap<>();
BufferedReader in = null;
try {
// Open the file
in = new BufferedReader(new FileReader(importFile));
String line;
String materialName;
String modName;
// While not at the end of the file
while ((line = in.readLine()) != null) {
String[] split1 = line.split("material ");
if (split1.length != 2) {
continue;
}
String[] split2 = split1[1].split(" with");
if (split2.length != 2) {
continue;
}
materialName = split2[0];
// Categorise each material under a mod config type
ModConfigType type = ModConfigType.getModConfigType(materialName);
if (!materialNames.containsKey(type)) {
materialNames.put(type, new ArrayList<>());
}
materialNames.get(type).add(materialName);
}
}
catch (FileNotFoundException e) {
mcMMO.p.getLogger().warning("Could not find " + importFile.getAbsolutePath() + " ! (No such file or directory)");
mcMMO.p.getLogger().warning("Copy and paste latest.log to " + importFile.getParentFile().getAbsolutePath() + " and rename it to import.log");
return false;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
finally {
tryClose(in);
}
createOutput(materialNames);
mcMMO.p.getLogger().info("Import finished! Created " + fileAmount + " files!");
return true;
}
private void createOutput(HashMap<ModConfigType, ArrayList<String>> materialNames) {
for (ModConfigType modConfigType : materialNames.keySet()) {
HashMap<String, ArrayList<String>> materialNamesType = new HashMap<>();
for (String materialName : materialNames.get(modConfigType)) {
String modName = Misc.getModName(materialName);
if (!materialNamesType.containsKey(modName)) {
materialNamesType.put(modName, new ArrayList<>());
}
materialNamesType.get(modName).add(materialName);
}
createOutput(modConfigType, materialNamesType);
}
}
private void tryClose(Closeable c) {
if (c == null) {
return;
}
try {
c.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
private void createOutput(ModConfigType modConfigType, HashMap<String, ArrayList<String>> materialNames) {
File outputFilePath = new File(mcMMO.getModDirectory() + File.separator + "output");
if (!outputFilePath.exists() && !outputFilePath.mkdirs()) {
mcMMO.p.getLogger().severe("Could not create output directory! " + outputFilePath.getAbsolutePath());
}
FileWriter out = null;
String type = modConfigType.name().toLowerCase(Locale.ENGLISH);
for (String modName : materialNames.keySet()) {
File outputFile = new File(outputFilePath, modName + "." + type + ".yml");
mcMMO.p.getLogger().info("Creating " + outputFile.getName());
try {
if (outputFile.exists() && !outputFile.delete()) {
mcMMO.p.getLogger().severe("Not able to delete old output file! " + outputFile.getAbsolutePath());
}
if (!outputFile.createNewFile()) {
mcMMO.p.getLogger().severe("Could not create output file! " + outputFile.getAbsolutePath());
continue;
}
StringBuilder writer = new StringBuilder();
HashMap<String, ArrayList<String>> configSections = getConfigSections(modConfigType, modName, materialNames);
if (configSections == null) {
mcMMO.p.getLogger().severe("Something went wrong!! type is " + type);
return;
}
// Write the file, go through each skill and write all the materials
for (String configSection : configSections.keySet()) {
if (configSection.equals("UNIDENTIFIED")) {
writer.append("# This isn't a valid config section and all materials in this category need to be").append("\r\n");
writer.append("# copy and pasted to a valid section of this config file.").append("\r\n");
}
writer.append(configSection).append(":").append("\r\n");
for (String line : configSections.get(configSection)) {
writer.append(line).append("\r\n");
}
writer.append("\r\n");
}
out = new FileWriter(outputFile);
out.write(writer.toString());
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
tryClose(out);
fileAmount++;
}
}
}
private HashMap<String, ArrayList<String>> getConfigSections(ModConfigType type, String modName, HashMap<String, ArrayList<String>> materialNames) {
switch (type) {
case BLOCKS:
return getConfigSectionsBlocks(modName, materialNames);
case TOOLS:
return getConfigSectionsTools(modName, materialNames);
case ARMOR:
return getConfigSectionsArmor(modName, materialNames);
case UNKNOWN:
return getConfigSectionsUnknown(modName, materialNames);
}
return null;
}
private HashMap<String, ArrayList<String>> getConfigSectionsBlocks(String modName, HashMap<String, ArrayList<String>> materialNames) {
HashMap<String, ArrayList<String>> configSections = new HashMap<>();
// Go through all the materials and categorise them under a skill
for (String materialName : materialNames.get(modName)) {
String skillName = "UNIDENTIFIED";
if (materialName.contains("ORE")) {
skillName = "Mining";
}
else if (materialName.contains("LOG") || materialName.contains("LEAVES")) {
skillName = "Woodcutting";
}
else if (materialName.contains("GRASS") || materialName.contains("FLOWER") || materialName.contains("CROP")) {
skillName = "Herbalism";
}
else if (materialName.contains("DIRT") || materialName.contains("SAND")) {
skillName = "Excavation";
}
if (!configSections.containsKey(skillName)) {
configSections.put(skillName, new ArrayList<>());
}
ArrayList<String> skillContents = configSections.get(skillName);
skillContents.add(" " + materialName + "|0:");
skillContents.add(" " + " " + "XP_Gain: 99");
skillContents.add(" " + " " + "Double_Drops_Enabled: true");
if (skillName.equals("Mining")) {
skillContents.add(" " + " " + "Smelting_XP_Gain: 9");
}
else if (skillName.equals("Woodcutting")) {
skillContents.add(" " + " " + "Is_Log: " + materialName.contains("LOG"));
}
}
return configSections;
}
private HashMap<String, ArrayList<String>> getConfigSectionsTools(String modName, HashMap<String, ArrayList<String>> materialNames) {
HashMap<String, ArrayList<String>> configSections = new HashMap<>();
// Go through all the materials and categorise them under a tool type
for (String materialName : materialNames.get(modName)) {
String toolType = "UNIDENTIFIED";
if (materialName.contains("PICKAXE")) {
toolType = "Pickaxes";
}
else if (materialName.contains("AXE")) {
toolType = "Axes";
}
else if (materialName.contains("BOW")) {
toolType = "Bows";
}
else if (materialName.contains("HOE")) {
toolType = "Hoes";
}
else if (materialName.contains("SHOVEL") || materialName.contains("SPADE")) {
toolType = "Shovels";
}
else if (materialName.contains("SWORD")) {
toolType = "Swords";
}
if (!configSections.containsKey(toolType)) {
configSections.put(toolType, new ArrayList<>());
}
ArrayList<String> skillContents = configSections.get(toolType);
skillContents.add(" " + materialName + ":");
skillContents.add(" " + " " + "XP_Modifier: 1.0");
skillContents.add(" " + " " + "Tier: 1");
skillContents.add(" " + " " + "Ability_Enabled: true");
addRepairableLines(materialName, skillContents);
}
return configSections;
}
private HashMap<String, ArrayList<String>> getConfigSectionsArmor(String modName, HashMap<String, ArrayList<String>> materialNames) {
HashMap<String, ArrayList<String>> configSections = new HashMap<>();
// Go through all the materials and categorise them under an armor type
for (String materialName : materialNames.get(modName)) {
String toolType = "UNIDENTIFIED";
if (materialName.contains("BOOT") || materialName.contains("SHOE")) {
toolType = "Boots";
}
else if (materialName.contains("CHESTPLATE") || materialName.contains("CHEST")) {
toolType = "Chestplates";
}
else if (materialName.contains("HELM") || materialName.contains("HAT")) {
toolType = "Helmets";
}
else if (materialName.contains("LEGGINGS") || materialName.contains("LEGS") || materialName.contains("PANTS")) {
toolType = "Leggings";
}
if (!configSections.containsKey(toolType)) {
configSections.put(toolType, new ArrayList<>());
}
ArrayList<String> skillContents = configSections.get(toolType);
skillContents.add(" " + materialName + ":");
addRepairableLines(materialName, skillContents);
}
return configSections;
}
private void addRepairableLines(String materialName, ArrayList<String> skillContents) {
skillContents.add(" " + " " + "Repairable: true");
skillContents.add(" " + " " + "Repair_Material: REPAIR_MATERIAL_NAME");
skillContents.add(" " + " " + "Repair_Material_Data_Value: 0");
skillContents.add(" " + " " + "Repair_Material_Quantity: 9");
skillContents.add(" " + " " + "Repair_Material_Pretty_Name: Repair Item Name");
skillContents.add(" " + " " + "Repair_MinimumLevel: 0");
skillContents.add(" " + " " + "Repair_XpMultiplier: 1.0");
Material material = Material.matchMaterial(materialName);
short durability = (material == null) ? (short) 9999 : material.getMaxDurability();
skillContents.add(" " + " " + "Durability: " + ((durability > 0) ? durability : (short) 9999));
}
private HashMap<String, ArrayList<String>> getConfigSectionsUnknown(String modName, HashMap<String, ArrayList<String>> materialNames) {
HashMap<String, ArrayList<String>> configSections = new HashMap<>();
// Go through all the materials and print them
for (String materialName : materialNames.get(modName)) {
String configKey = "UNIDENTIFIED";
if (!configSections.containsKey(configKey)) {
configSections.put(configKey, new ArrayList<>());
}
ArrayList<String> skillContents = configSections.get(configKey);
skillContents.add(" " + materialName);
}
return configSections;
}
}

View File

@@ -5,7 +5,7 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
import org.bukkit.command.CommandSender;
public class AbilityToggleCommand extends ToggleCommand {
public class McabilityCommand extends ToggleCommand {
@Override
protected boolean hasOtherPermission(CommandSender sender) {
return Permissions.mcabilityOthers(sender);

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.commands;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.commands.party.PartySubcommandType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;

View File

@@ -24,8 +24,10 @@ public class McnotifyCommand implements TabExecutor {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
//Not Loaded yet
if (mcMMOPlayer == null)
if (mcMMOPlayer == null) {
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Notifications." + (mcMMOPlayer.useChatNotifications() ? "Off" : "On")));
mcMMOPlayer.toggleChatNotifications();

View File

@@ -23,6 +23,16 @@ public class McscoreboardCommand implements TabExecutor {
return true;
}
if(!mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) {
sender.sendMessage(LocaleLoader.getString("Scoreboard.Disabled"));
return true;
}
if(!ScoreboardManager.isPlayerBoardSetup(sender.getName())) {
sender.sendMessage(LocaleLoader.getString("Scoreboard.NotSetupYet"));
return true;
}
switch (args.length) {
case 1:
if (args[0].equalsIgnoreCase("clear") || args[0].equalsIgnoreCase("reset")) {

View File

@@ -61,7 +61,7 @@ public class ConvertDatabaseCommand implements CommandExecutor {
PlayerProfile profile = oldDatabase.loadPlayerProfile(player);
if (profile.isLoaded()) {
mcMMO.getDatabaseManager().saveUser(profile.getPlayerData());
mcMMO.getDatabaseManager().saveUser(profile);
}
new PlayerProfileLoadingTask(player).runTaskLaterAsynchronously(mcMMO.p, 1); // 1 Tick delay to ensure the player is marked as online before we begin loading

View File

@@ -16,7 +16,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class RemoveCommand implements TabExecutor {
public class McremoveCommand implements TabExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 1) {

View File

@@ -1,5 +1,6 @@
package com.gmail.nossr50.commands.experience;
import com.gmail.nossr50.datatypes.experience.XPGainReason;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
@@ -8,7 +9,6 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import com.neetgames.mcmmo.experience.XPGainReason;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -29,7 +29,7 @@ public class AddlevelsCommand extends ExperienceCommand {
profile.addLevels(skill, value);
if (player == null) {
UserManager.getPlayerSaveHandler().scheduleAsyncSave(profile.getPlayerData());
profile.scheduleAsyncSave();
return;
}

View File

@@ -33,7 +33,7 @@ public class AddxpCommand extends ExperienceCommand {
}
else {
profile.addXp(skill, value);
UserManager.getPlayerSaveHandler().scheduleAsyncSave(profile.getPlayerData());
profile.scheduleAsyncSave();
}
}

View File

@@ -9,7 +9,6 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import com.neetgames.mcmmo.experience.XPGainReason;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -32,7 +31,7 @@ public class MmoeditCommand extends ExperienceCommand {
profile.modifySkill(skill, value);
if (player == null) {
UserManager.getPlayerSaveHandler().scheduleAsyncSave(profile.getPlayerData());
profile.scheduleAsyncSave();
return;
}

View File

@@ -1,5 +1,6 @@
package com.gmail.nossr50.commands.experience;
import com.gmail.nossr50.datatypes.experience.XPGainReason;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
@@ -26,7 +27,7 @@ import java.util.List;
* This class mirrors the structure of ExperienceCommand, except the
* value/quantity argument is removed.
*/
public class SkillResetCommand implements TabExecutor {
public class SkillresetCommand implements TabExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
PrimarySkillType skill;
@@ -125,7 +126,7 @@ public class SkillResetCommand implements TabExecutor {
profile.modifySkill(skill, 0);
if (player == null) {
UserManager.getPlayerSaveHandler().scheduleAsyncSave(profile.getPlayerData());
profile.scheduleAsyncSave();
return;
}

View File

@@ -1,6 +1,8 @@
package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.commands.party.alliance.PartyAllianceCommand;
import com.gmail.nossr50.commands.party.teleport.PtpCommand;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
@@ -36,19 +38,23 @@ public class PartyCommand implements TabExecutor {
PARTY_SUBCOMMANDS = ImmutableList.copyOf(subcommands);
}
private final CommandExecutor partyJoinCommand = new PartyJoinCommand();
private final CommandExecutor partyAcceptCommand = new PartyAcceptCommand();
private final CommandExecutor partyCreateCommand = new PartyCreateCommand();
private final CommandExecutor partyQuitCommand = new PartyQuitCommand();
private final CommandExecutor partyXpShareCommand = new PartyXpShareCommand();
private final CommandExecutor partyItemShareCommand = new PartyItemShareCommand();
private final CommandExecutor partyInviteCommand = new PartyInviteCommand();
private final CommandExecutor partyKickCommand = new PartyKickCommand();
private final CommandExecutor partyDisbandCommand = new PartyDisbandCommand();
private final CommandExecutor partyChangeOwnerCommand = new PartyChangeOwnerCommand();
private final CommandExecutor partyLockCommand = new PartyLockCommand();
private final CommandExecutor partyChangePasswordCommand = new PartyChangePasswordCommand();
private final CommandExecutor partyRenameCommand = new PartyRenameCommand();
private final CommandExecutor partyInfoCommand = new PartyInfoCommand();
private final CommandExecutor partyHelpCommand = new PartyHelpCommand();
private final CommandExecutor partyTeleportCommand = new PtpCommand();
private final CommandExecutor partyAllianceCommand = new PartyAllianceCommand();
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
@@ -194,15 +200,19 @@ public class PartyCommand implements TabExecutor {
if (matches.size() == 0) {
Player player = (Player) sender;
final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
//Not Loaded
if(UserManager.getPlayer(player) == null)
if(mcMMOPlayer == null)
{
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return ImmutableList.of();
}
Party party = UserManager.getPlayer(player).getParty();
if (mcMMOPlayer.getParty() == null)
return ImmutableList.of();
final Party party = mcMMOPlayer.getParty();
playerNames = party.getOnlinePlayerNames(player);
return StringUtil.copyPartialMatches(args[1], playerNames, new ArrayList<>(playerNames.size()));

View File

@@ -1,6 +1,7 @@
package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent.EventReason;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
@@ -15,13 +16,14 @@ public class PartyDisbandCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 1) {
if (UserManager.getPlayer((Player) sender) == null) {
final McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
if (mcMMOPlayer == null) {
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
Party playerParty = UserManager.getPlayer((Player) sender).getParty();
String partyName = playerParty.getName();
final Party playerParty = mcMMOPlayer.getParty();
final String partyName = playerParty.getName();
for (Player member : playerParty.getOnlineMembers()) {
if (!PartyManager.handlePartyChangeEvent(member, partyName, null, EventReason.KICKED_FROM_PARTY)) {
@@ -31,7 +33,7 @@ public class PartyDisbandCommand implements CommandExecutor {
member.sendMessage(LocaleLoader.getString("Party.Disband"));
}
PartyManager.disbandParty(playerParty);
PartyManager.disbandParty(mcMMOPlayer, playerParty);
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "disband"));

View File

@@ -0,0 +1,97 @@
package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.datatypes.party.ItemShareType;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.party.PartyFeature;
import com.gmail.nossr50.datatypes.party.ShareMode;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.text.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.Locale;
public class PartyItemShareCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if(UserManager.getPlayer((Player) sender) == null)
{
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
Party party = UserManager.getPlayer((Player) sender).getParty();
if (party.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.ITEM_SHARE)) {
sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.4"));
return true;
}
switch (args.length) {
case 2:
ShareMode mode = ShareMode.getShareMode(args[1].toUpperCase(Locale.ENGLISH));
if (mode == null) {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<NONE | EQUAL | RANDOM>"));
return true;
}
handleChangingShareMode(party, mode);
return true;
case 3:
boolean toggle;
if (CommandUtils.shouldEnableToggle(args[2])) {
toggle = true;
}
else if (CommandUtils.shouldDisableToggle(args[2])) {
toggle = false;
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting | misc> <true | false>"));
return true;
}
try {
handleToggleItemShareCategory(party, ItemShareType.valueOf(args[1].toUpperCase(Locale.ENGLISH)), toggle);
}
catch (IllegalArgumentException ex) {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting | misc> <true | false>"));
}
return true;
default:
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<NONE | EQUAL | RANDOM>"));
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", "<loot | mining | herbalism | woodcutting | misc> <true | false>"));
return true;
}
}
private void handleChangingShareMode(Party party, ShareMode mode) {
party.setItemShareMode(mode);
String changeModeMessage = LocaleLoader.getString("Commands.Party.SetSharing", LocaleLoader.getString("Party.ShareType.Item"), LocaleLoader.getString("Party.ShareMode." + StringUtils.getCapitalized(mode.toString())));
for (Player member : party.getOnlineMembers()) {
member.sendMessage(changeModeMessage);
}
}
private void handleToggleItemShareCategory(Party party, ItemShareType type, boolean toggle) {
party.setSharingDrops(type, toggle);
String toggleMessage = LocaleLoader.getString("Commands.Party.ToggleShareCategory", StringUtils.getCapitalized(type.toString()), toggle ? "enabled" : "disabled");
for (Player member : party.getOnlineMembers()) {
member.sendMessage(toggleMessage);
}
}
}

View File

@@ -0,0 +1,88 @@
package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class PartyJoinCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
switch (args.length) {
case 2:
case 3:
String targetName = CommandUtils.getMatchedPlayerName(args[1]);
McMMOPlayer mcMMOTarget = UserManager.getPlayer(targetName);
if (!CommandUtils.checkPlayerExistence(sender, targetName, mcMMOTarget)) {
return true;
}
Player target = mcMMOTarget.getPlayer();
if (!mcMMOTarget.inParty()) {
sender.sendMessage(LocaleLoader.getString("Party.PlayerNotInParty", targetName));
return true;
}
Player player = (Player) sender;
if(UserManager.getPlayer((Player) sender) == null)
{
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
Party targetParty = mcMMOTarget.getParty();
if (player.equals(target) || (mcMMOPlayer.inParty() && mcMMOPlayer.getParty().equals(targetParty))) {
sender.sendMessage(LocaleLoader.getString("Party.Join.Self"));
return true;
}
String password = getPassword(args);
// Make sure party passwords match
if (!PartyManager.checkPartyPassword(player, targetParty, password)) {
return true;
}
String partyName = targetParty.getName();
// Changing parties
if (!PartyManager.changeOrJoinParty(mcMMOPlayer, partyName)) {
return true;
}
if(PartyManager.isPartyFull(player, targetParty))
{
player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull", targetParty.toString()));
return true;
}
player.sendMessage(LocaleLoader.getString("Commands.Party.Join", partyName));
PartyManager.addToParty(mcMMOPlayer, targetParty);
return true;
default:
sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "join", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">", "[" + LocaleLoader.getString("Commands.Usage.Password") + "]"));
return true;
}
}
private String getPassword(String[] args) {
if (args.length == 3) {
return args[2];
}
return null;
}
}

View File

@@ -0,0 +1,79 @@
package com.gmail.nossr50.commands.party;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class PartyLockCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
switch (args.length) {
case 1:
if (args[0].equalsIgnoreCase("lock")) {
togglePartyLock(sender, true);
}
else if (args[0].equalsIgnoreCase("unlock")) {
togglePartyLock(sender, false);
}
return true;
case 2:
if (!args[0].equalsIgnoreCase("lock")) {
sendUsageStrings(sender);
return true;
}
if (CommandUtils.shouldEnableToggle(args[1])) {
togglePartyLock(sender, true);
}
else if (CommandUtils.shouldDisableToggle(args[1])) {
togglePartyLock(sender, false);
}
else {
sendUsageStrings(sender);
}
return true;
default:
sendUsageStrings(sender);
return true;
}
}
private void sendUsageStrings(CommandSender sender) {
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "lock", "[on|off]"));
sender.sendMessage(LocaleLoader.getString("Commands.Usage.1", "party", "unlock"));
}
private void togglePartyLock(CommandSender sender, boolean lock) {
if(UserManager.getPlayer((Player) sender) == null)
{
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return;
}
Party party = UserManager.getPlayer((Player) sender).getParty();
if (!Permissions.partySubcommand(sender, lock ? PartySubcommandType.LOCK : PartySubcommandType.UNLOCK)) {
sender.sendMessage(LocaleLoader.getString("mcMMO.NoPermission"));
return;
}
if (lock == party.isLocked()) {
sender.sendMessage(LocaleLoader.getString("Party." + (lock ? "IsLocked" : "IsntLocked")));
return;
}
party.setLocked(lock);
sender.sendMessage(LocaleLoader.getString("Party." + (lock ? "Locked" : "Unlocked")));
}
}

View File

@@ -25,7 +25,7 @@ public class PartyRenameCommand implements CommandExecutor {
Party playerParty = mcMMOPlayer.getParty();
String oldPartyName = playerParty.getName();
String newPartyName = args[1];
String newPartyName = args[1].replace(".", "");
// This is to prevent party leaders from spamming other players with the rename message
if (oldPartyName.equalsIgnoreCase(newPartyName)) {

View File

@@ -1,6 +1,6 @@
package com.gmail.nossr50.commands.party;
public enum PartySubCommandType {
public enum PartySubcommandType {
JOIN,
ACCEPT,
CREATE,
@@ -8,18 +8,21 @@ public enum PartySubCommandType {
INFO,
QUIT,
XPSHARE,
ITEMSHARE,
INVITE,
KICK,
DISBAND,
OWNER,
LOCK,
UNLOCK,
PASSWORD,
RENAME,
TELEPORT,
CHAT,
PROMOTE,
DEMOTE;
ALLIANCE;
public static PartySubCommandType getSubcommand(String commandName) {
for (PartySubCommandType command : values()) {
public static PartySubcommandType getSubcommand(String commandName) {
for (PartySubcommandType command : values()) {
if (command.name().equalsIgnoreCase(commandName)) {
return command;
}
@@ -36,8 +39,14 @@ public enum PartySubCommandType {
}
else if (commandName.equalsIgnoreCase("xpshare") || commandName.equalsIgnoreCase("shareexp") || commandName.equalsIgnoreCase("sharexp")) {
return XPSHARE;
} else {
return null;
}
else if (commandName.equalsIgnoreCase("shareitem") || commandName.equalsIgnoreCase("shareitems")) {
return ITEMSHARE;
}
else if (commandName.equalsIgnoreCase("ally")) {
return ALLIANCE;
}
return null;
}
}

View File

@@ -0,0 +1,40 @@
package com.gmail.nossr50.commands.party.alliance;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class PartyAllianceAcceptCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 2) {
if (UserManager.getPlayer((Player) sender) == null) {
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (!mcMMOPlayer.hasPartyAllianceInvite()) {
sender.sendMessage(LocaleLoader.getString("mcMMO.NoInvites"));
return true;
}
if (mcMMOPlayer.getParty().getAlly() != null) {
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.AlreadyAllies"));
return true;
}
PartyManager.acceptAllianceInvite(mcMMOPlayer);
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "alliance", "accept"));
return true;
}
}

View File

@@ -0,0 +1,138 @@
package com.gmail.nossr50.commands.party.alliance;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.party.PartyFeature;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableList;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class PartyAllianceCommand implements TabExecutor {
private Player player;
private Party playerParty;
private Party targetParty;
public static final List<String> ALLIANCE_SUBCOMMANDS = ImmutableList.of("invite", "accept", "disband");
private final CommandExecutor partyAllianceInviteCommand = new PartyAllianceInviteCommand();
private final CommandExecutor partyAllianceAcceptCommand = new PartyAllianceAcceptCommand();
private final CommandExecutor partyAllianceDisbandCommand = new PartyAllianceDisbandCommand();
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (CommandUtils.noConsoleUsage(sender)) {
return true;
}
if(UserManager.getPlayer((Player) sender) == null)
{
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
playerParty = mcMMOPlayer.getParty();
switch (args.length) {
case 1:
if (playerParty.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.ALLIANCE)) {
sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.3"));
return true;
}
if (playerParty.getAlly() == null) {
printUsage();
return true;
}
targetParty = playerParty.getAlly();
displayPartyHeader();
displayMemberInfo(mcMMOPlayer);
return true;
case 2:
case 3:
if (playerParty.getLevel() < mcMMO.p.getGeneralConfig().getPartyFeatureUnlockLevel(PartyFeature.ALLIANCE)) {
sender.sendMessage(LocaleLoader.getString("Party.Feature.Disabled.3"));
return true;
}
if (args[1].equalsIgnoreCase("invite")) {
return partyAllianceInviteCommand.onCommand(sender, command, label, args);
}
if (args[1].equalsIgnoreCase("accept")) {
return partyAllianceAcceptCommand.onCommand(sender, command, label, args);
}
if (args[1].equalsIgnoreCase("disband")) {
return partyAllianceDisbandCommand.onCommand(sender, command, label, args);
}
if (playerParty.getAlly() == null) {
printUsage();
return true;
}
targetParty = playerParty.getAlly();
displayPartyHeader();
displayMemberInfo(mcMMOPlayer);
return true;
default:
return false;
}
}
private boolean printUsage() {
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Help.0"));
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Help.1"));
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 1) {
List<String> matches = StringUtil.copyPartialMatches(args[0], ALLIANCE_SUBCOMMANDS, new ArrayList<>(ALLIANCE_SUBCOMMANDS.size()));
if (matches.size() == 0) {
List<String> playerNames = CommandUtils.getOnlinePlayerNames(commandSender);
return StringUtil.copyPartialMatches(args[0], playerNames, new ArrayList<>(playerNames.size()));
}
return matches;
}
return ImmutableList.of();
}
private void displayPartyHeader() {
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Header"));
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Ally", playerParty.getName(), targetParty.getName()));
}
private void displayMemberInfo(McMMOPlayer mcMMOPlayer) {
List<Player> nearMembers = PartyManager.getNearMembers(mcMMOPlayer);
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Members.Header"));
player.sendMessage(playerParty.createMembersList(player));
player.sendMessage(ChatColor.DARK_GRAY + "----------------------------");
player.sendMessage(targetParty.createMembersList(player));
}
}

View File

@@ -0,0 +1,37 @@
package com.gmail.nossr50.commands.party.alliance;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class PartyAllianceDisbandCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 2) {
if (UserManager.getPlayer((Player) sender) == null) {
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
Party party = mcMMOPlayer.getParty();
if (party.getAlly() == null) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.None"));
return true;
}
PartyManager.disbandAlliance(player, party, party.getAlly());
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "alliance", "disband"));
return true;
}
}

View File

@@ -0,0 +1,74 @@
package com.gmail.nossr50.commands.party.alliance;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public class PartyAllianceInviteCommand implements CommandExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 3) {
String targetName = CommandUtils.getMatchedPlayerName(args[2]);
McMMOPlayer mcMMOTarget = UserManager.getOfflinePlayer(targetName);
if (!CommandUtils.checkPlayerExistence(sender, targetName, mcMMOTarget)) {
return false;
}
Player target = mcMMOTarget.getPlayer();
if (UserManager.getPlayer((Player) sender) == null) {
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
String playerName = player.getName();
if (player.equals(target)) {
sender.sendMessage(LocaleLoader.getString("Party.Invite.Self"));
return true;
}
if (!mcMMOTarget.inParty()) {
player.sendMessage(LocaleLoader.getString("Party.PlayerNotInParty", targetName));
return true;
}
if (PartyManager.inSameParty(player, target)) {
sender.sendMessage(LocaleLoader.getString("Party.Player.InSameParty", targetName));
return true;
}
if (!mcMMOTarget.getParty().getLeader().getUniqueId().equals(target.getUniqueId())) {
player.sendMessage(LocaleLoader.getString("Party.Target.NotOwner", targetName));
return true;
}
Party playerParty = mcMMOPlayer.getParty();
if (playerParty.getAlly() != null) {
player.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.AlreadyAllies"));
return true;
}
mcMMOTarget.setPartyAllianceInvite(playerParty);
sender.sendMessage(LocaleLoader.getString("Commands.Invite.Success"));
target.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.0", playerParty.getName(), playerName));
target.sendMessage(LocaleLoader.getString("Commands.Party.Alliance.Invite.1"));
return true;
}
sender.sendMessage(LocaleLoader.getString("Commands.Usage.3", "party", "alliance", "invite", "<" + LocaleLoader.getString("Commands.Usage.Player") + ">"));
return true;
}
}

View File

@@ -9,6 +9,7 @@ import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager;
import com.gmail.nossr50.util.skills.SkillTools;
import com.google.common.collect.ImmutableList;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@@ -62,6 +63,12 @@ public class InspectCommand implements TabExecutor {
sender.sendMessage(CommandUtils.displaySkill(profile, skill));
}
// Sum power level
int powerLevel = 0;
for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS)
powerLevel += profile.getSkillLevel(skill);
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel", powerLevel));
} else {
Player target = mcMMOPlayer.getPlayer();
boolean isVanished = false;
@@ -85,10 +92,16 @@ public class InspectCommand implements TabExecutor {
}
}
sender.sendMessage(LocaleLoader.getString("Inspect.Stats", target.getName()));
if (isVanished) {
sender.sendMessage(LocaleLoader.getString("Inspect.OfflineStats", playerName));
} else {
sender.sendMessage(LocaleLoader.getString("Inspect.Stats", target.getName()));
}
CommandUtils.printGatheringSkills(target, sender);
CommandUtils.printCombatSkills(target, sender);
CommandUtils.printMiscSkills(target, sender);
sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel", mcMMOPlayer.getPowerLevel()));
}

View File

@@ -4,6 +4,7 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.commands.McrankCommandAsyncTask;
import com.gmail.nossr50.util.MetadataConstants;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
@@ -97,11 +98,11 @@ public class McrankCommand implements TabExecutor {
return;
}
if (((Player) sender).hasMetadata(mcMMO.databaseCommandKey)) {
if (((Player) sender).hasMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND)) {
sender.sendMessage(LocaleLoader.getString("Commands.Database.Processing"));
return;
} else {
((Player) sender).setMetadata(mcMMO.databaseCommandKey, new FixedMetadataValue(mcMMO.p, null));
((Player) sender).setMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, new FixedMetadataValue(mcMMO.p, null));
}
mcMMOPlayer.actualizeDatabaseATS();

View File

@@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask;
import com.gmail.nossr50.util.MetadataConstants;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.commands.CommandUtils;
import com.gmail.nossr50.util.player.UserManager;
@@ -97,11 +98,11 @@ public class MctopCommand implements TabExecutor {
return;
}
if (((Player) sender).hasMetadata(mcMMO.databaseCommandKey)) {
if (((Player) sender).hasMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND)) {
sender.sendMessage(LocaleLoader.getString("Commands.Database.Processing"));
return;
} else {
((Player) sender).setMetadata(mcMMO.databaseCommandKey, new FixedMetadataValue(mcMMO.p, null));
((Player) sender).setMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, new FixedMetadataValue(mcMMO.p, null));
}
mcMMOPlayer.actualizeDatabaseATS();

View File

@@ -1,50 +0,0 @@
package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.skills.crossbows.CrossbowsManager;
import com.gmail.nossr50.util.text.TextComponentFactory;
import com.neetgames.mcmmo.player.OnlineMMOPlayer;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class CrossbowsCommand extends SkillCommand {
public CrossbowsCommand() {
super(PrimarySkillType.CROSSBOWS);
}
@Override
protected void dataCalculations(@NotNull OnlineMMOPlayer mmoPlayer, float skillValue) {
}
@Override
protected void permissionsCheck(@NotNull OnlineMMOPlayer mmoPlayer) {
}
@Override
protected @NotNull List<String> statsDisplay(@NotNull OnlineMMOPlayer mmoPlayer, float skillValue, boolean hasEndurance, boolean isLucky) {
List<String> messages = new ArrayList<>();
CrossbowsManager crossbowsManager = ((McMMOPlayer) (mmoPlayer)).getCrossbowManager();
if(canUseSubskill(mmoPlayer, SubSkillType.CROSSBOWS_SUPER_SHOTGUN)) {
String additionalArrowCount = String.valueOf(crossbowsManager.getSuperShotgunAdditionalArrowCount());
messages.add(getStatMessage(SubSkillType.CROSSBOWS_SUPER_SHOTGUN, additionalArrowCount));
}
return messages;
}
@Override
protected @NotNull List<Component> getTextComponents(@NotNull OnlineMMOPlayer mmoPlayer) {
List<Component> textComponents = new ArrayList<>();
TextComponentFactory.getSubSkillTextComponents(mmoPlayer, textComponents, PrimarySkillType.CROSSBOWS);
return textComponents;
}
}

View File

@@ -91,7 +91,7 @@ public class HerbalismCommand extends SkillCommand {
protected void permissionsCheck(Player player) {
hasHylianLuck = canUseSubskill(player, SubSkillType.HERBALISM_HYLIAN_LUCK);
canGreenTerra = Permissions.greenTerra(player);
canGreenThumbPlants = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbPlant(player, Material.WHEAT) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.BEETROOT) || Permissions.greenThumbPlant(player, Material.NETHER_WART) || Permissions.greenThumbPlant(player, Material.COCOA));
canGreenThumbPlants = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbPlant(player, Material.WHEAT) || Permissions.greenThumbPlant(player, Material.CARROT) || Permissions.greenThumbPlant(player, Material.POTATO) || Permissions.greenThumbPlant(player, Material.BEETROOTS) || Permissions.greenThumbPlant(player, Material.NETHER_WART) || Permissions.greenThumbPlant(player, Material.COCOA));
canGreenThumbBlocks = RankUtils.hasUnlockedSubskill(player, SubSkillType.HERBALISM_GREEN_THUMB) && (Permissions.greenThumbBlock(player, Material.DIRT) || Permissions.greenThumbBlock(player, Material.COBBLESTONE) || Permissions.greenThumbBlock(player, Material.COBBLESTONE_WALL) || Permissions.greenThumbBlock(player, Material.STONE_BRICKS));
canFarmersDiet = canUseSubskill(player, SubSkillType.HERBALISM_FARMERS_DIET);
canDoubleDrop = canUseSubskill(player, SubSkillType.HERBALISM_DOUBLE_DROPS) && !mcMMO.p.getGeneralConfig().getDoubleDropsDisabled(skill);

View File

@@ -27,12 +27,11 @@ public class MmoInfoCommand implements TabExecutor {
/*
* Only allow players to use this command
*/
if(commandSender instanceof Player)
if(commandSender instanceof Player player)
{
if(args.length < 1)
return false;
Player player = (Player) commandSender;
if(Permissions.mmoinfo(player))
{
if(args == null || args[0] == null)

View File

@@ -59,18 +59,17 @@ public abstract class SkillCommand implements TabExecutor {
return true;
}
if(UserManager.getPlayer((Player) sender) == null)
{
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if (mcMMOPlayer == null) {
sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad"));
return true;
}
if (args.length == 0) {
Player player = (Player) sender;
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
boolean isLucky = Permissions.lucky(player, skill);
boolean hasEndurance = (PerksUtils.handleActivationPerks(player, 0, 0) != 0);
boolean hasEndurance = PerksUtils.handleActivationPerks(player, 0, 0) != 0;
float skillValue = mcMMOPlayer.getSkillLevel(skill);
//Send the players a few blank lines to make finding the top of the skill command easier
@@ -116,8 +115,21 @@ public abstract class SkillCommand implements TabExecutor {
ScoreboardManager.enablePlayerSkillScoreboard(player, skill);
}
return true;
} else if ("keep".equals(args[0].toLowerCase())) {
if (!mcMMO.p.getGeneralConfig().getAllowKeepBoard()
|| !mcMMO.p.getGeneralConfig().getScoreboardsEnabled()
|| !mcMMO.p.getGeneralConfig().getSkillUseBoard()) {
sender.sendMessage(LocaleLoader.getString("Commands.Disabled"));
return true;
}
ScoreboardManager.enablePlayerSkillScoreboard(player, skill);
ScoreboardManager.keepBoard(sender.getName());
sender.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Keep"));
return true;
}
return skillGuideCommand.onCommand(sender, command, label, args);
}
@@ -211,7 +223,7 @@ public abstract class SkillCommand implements TabExecutor {
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
if (args.length == 1) {
return ImmutableList.of("?");
return ImmutableList.of("?", "keep");
}
return ImmutableList.of();
}

View File

@@ -91,9 +91,9 @@ public class SwordsCommand extends SkillCommand {
ruptureLengthSecondsAgainstMobs));
messages.add(LocaleLoader.getString("Swords.SubSkill.Rupture.Stat.TickDamage", rupturePureTickDamageAgainstPlayers, rupturePureTickDamageAgainstMobs));
messages.add(LocaleLoader.getString("Swords.SubSkill.Rupture.Stat.ExplosionDamage", ruptureExplosionDamageAgainstPlayers, ruptureExplosionDamageAgainstMobs));
// messages.add(LocaleLoader.getString("Swords.SubSkill.Rupture.Stat.ExplosionDamage", ruptureExplosionDamageAgainstPlayers, ruptureExplosionDamageAgainstMobs));
messages.add(LocaleLoader.getString("Swords.Combat.Rupture.Note"));
messages.add(LocaleLoader.getString("Swords.Combat.Rupture.Note.Update.One"));
}
if (canSerratedStrike) {

View File

@@ -1,41 +0,0 @@
package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.util.text.TextComponentFactory;
import com.neetgames.mcmmo.player.OnlineMMOPlayer;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class TridentsCommand extends SkillCommand {
public TridentsCommand() {
super(PrimarySkillType.TRIDENTS);
}
@Override
protected void dataCalculations(@NotNull OnlineMMOPlayer mmoPlayer, float skillValue) {
}
@Override
protected void permissionsCheck(@NotNull OnlineMMOPlayer mmoPlayer) {
}
@Override
protected @NotNull List<String> statsDisplay(@NotNull OnlineMMOPlayer mmoPlayer, float skillValue, boolean hasEndurance, boolean isLucky) {
return null;
}
@Override
protected @NotNull List<Component> getTextComponents(@NotNull Player player) {
List<Component> textComponents = new ArrayList<>();
TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.TRIDENTS);
return textComponents;
}
}

View File

@@ -10,7 +10,7 @@ import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AdvancedConfig extends AutoUpdateConfigLoader {
public class AdvancedConfig extends BukkitConfig {
public AdvancedConfig(File dataFolder) {
super("advanced.yml", dataFolder);
@@ -99,8 +99,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
}
/* AXES */
if(getAxeMasteryRankDamageMultiplier() < 0)
{
if (getAxeMasteryRankDamageMultiplier() < 0) {
reason.add("Skills.Axes.AxeMastery.RankDamageMultiplier should be at least 0!");
}
@@ -404,12 +403,18 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
}
@Override
protected void loadKeys() {}
protected void loadKeys() {
}
/* GENERAL */
public boolean canApplyLimitBreakPVE() { return config.getBoolean("Skills.General.LimitBreak.AllowPVE", false); }
public int getStartingLevel() { return config.getInt("Skills.General.StartingLevel", 0); }
public boolean canApplyLimitBreakPVE() {
return config.getBoolean("Skills.General.LimitBreak.AllowPVE", false);
}
public int getStartingLevel() {
return config.getInt("Skills.General.StartingLevel", 1);
}
public boolean allowPlayerTips() {
return config.getBoolean("Feedback.PlayerTips", true);
@@ -417,11 +422,12 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
/**
* This returns the maximum level at which superabilities will stop lengthening from scaling alongside skill level.
* It returns a different value depending on whether or not the server is in retro mode
* It returns a different value depending on whether the server is in retro mode
*
* @return the level at which abilities stop increasing in length
*/
public int getAbilityLengthCap() {
if(!mcMMO.isRetroModeEnabled())
if (!mcMMO.isRetroModeEnabled())
return config.getInt("Skills.General.Ability.Length.Standard.CapLevel", 50);
else
return config.getInt("Skills.General.Ability.Length.RetroMode.CapLevel", 500);
@@ -429,28 +435,33 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
/**
* This returns the frequency at which abilities will increase in length
* It returns a different value depending on whether or not the server is in retro mode
* It returns a different value depending on whether the server is in retro mode
*
* @return the number of levels required per ability length increase
*/
public int getAbilityLength() {
if(!mcMMO.isRetroModeEnabled())
if (!mcMMO.isRetroModeEnabled())
return config.getInt("Skills.General.Ability.Length.Standard.IncreaseLevel", 5);
else
return config.getInt("Skills.General.Ability.Length.RetroMode.IncreaseLevel", 50);
}
public int getEnchantBuff() { return config.getInt("Skills.General.Ability.EnchantBuff", 5); }
public int getEnchantBuff() {
return config.getInt("Skills.General.Ability.EnchantBuff", 5);
}
/**
* Grabs the max bonus level for a skill used in RNG calculations
* All max level values in the config are multiplied by 10 if the server is in retro mode as the values in the config are based around the new 1-100 skill system scaling
* A value of 10 in the file will be returned as 100 for retro mode servers to accommodate the change in scaling
*
* @param subSkillType target subskill
*
* @return the level at which this skills max benefits will be reached on the curve
*/
public int getMaxBonusLevel(SubSkillType subSkillType) {
String keyPath = subSkillType.getAdvConfigAddress() + ".MaxBonusLevel.";
return mcMMO.isRetroModeEnabled() ? config.getInt(keyPath+"RetroMode", 1000) : config.getInt(keyPath+"Standard", 100);
return mcMMO.isRetroModeEnabled() ? config.getInt(keyPath + "RetroMode", 1000) : config.getInt(keyPath + "Standard", 100);
}
public int getMaxBonusLevel(AbstractSubSkill abstractSubSkill) {
@@ -462,35 +473,29 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
return config.getDouble(subSkillType.getAdvConfigAddress() + ".ChanceMax", 100.0D);
}
public double getMaximumProbability(AbstractSubSkill abstractSubSkill)
{
public double getMaximumProbability(AbstractSubSkill abstractSubSkill) {
return getMaximumProbability(abstractSubSkill.getSubSkillType());
}
/* Notification Settings */
public boolean doesSkillCommandSendBlankLines()
{
public boolean doesSkillCommandSendBlankLines() {
return config.getBoolean("Feedback.SkillCommand.BlankLinesAboveHeader", true);
}
public boolean doesNotificationUseActionBar(NotificationType notificationType)
{
return config.getBoolean("Feedback.ActionBarNotifications."+notificationType.toString()+".Enabled", true);
public boolean doesNotificationUseActionBar(NotificationType notificationType) {
return config.getBoolean("Feedback.ActionBarNotifications." + notificationType.toString() + ".Enabled", true);
}
public boolean doesNotificationSendCopyToChat(NotificationType notificationType)
{
return config.getBoolean("Feedback.ActionBarNotifications."+notificationType.toString()+".SendCopyOfMessageToChat", false);
public boolean doesNotificationSendCopyToChat(NotificationType notificationType) {
return config.getBoolean("Feedback.ActionBarNotifications." + notificationType.toString() + ".SendCopyOfMessageToChat", false);
}
public boolean useTitlesForXPEvent()
{
public boolean useTitlesForXPEvent() {
return config.getBoolean("Feedback.Events.XP.SendTitles", true);
}
public boolean sendAbilityNotificationToOtherPlayers()
{
public boolean sendAbilityNotificationToOtherPlayers() {
return config.getBoolean("Feedback.Events.AbilityActivation.SendNotificationToOtherPlayers", true);
}
@@ -509,6 +514,7 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
/**
* Used to color our details header in our JSON Hover Object tooltips
*
* @return the ChatColor for this element
*/
/*public ChatColor getJSONStatHoverDetailsColor()
@@ -557,7 +563,6 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
{
return getChatColor(config.getString("Style.JSON.Notification."+notificationType.toString()+".Color"));
}*/
private ChatColor getChatColorFromKey(String keyLocation) {
String colorName = config.getString(keyLocation);
@@ -598,110 +603,247 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
/**
* Some SubSkills have the ability to retain classic functionality
*
* @param subSkillType SubSkillType with classic functionality
*
* @return true if the subskill is in classic mode
*/
public boolean isSubSkillClassic(SubSkillType subSkillType)
{
return config.getBoolean(subSkillType.getAdvConfigAddress()+".Classic");
public boolean isSubSkillClassic(SubSkillType subSkillType) {
return config.getBoolean(subSkillType.getAdvConfigAddress() + ".Classic");
}
/* ACROBATICS */
public double getDodgeDamageModifier() { return config.getDouble("Skills.Acrobatics.Dodge.DamageModifier", 2.0D); }
public double getDodgeDamageModifier() {
return config.getDouble("Skills.Acrobatics.Dodge.DamageModifier", 2.0D);
}
public double getRollDamageThreshold() { return config.getDouble("Skills.Acrobatics.Roll.DamageThreshold", 7.0D); }
public double getRollDamageThreshold() {
return config.getDouble("Skills.Acrobatics.Roll.DamageThreshold", 7.0D);
}
public double getGracefulRollDamageThreshold() { return config.getDouble("Skills.Acrobatics.GracefulRoll.DamageThreshold", 14.0D); }
public double getGracefulRollDamageThreshold() {
return config.getDouble("Skills.Acrobatics.GracefulRoll.DamageThreshold", 14.0D);
}
/* ALCHEMY */
public int getCatalysisMaxBonusLevel() { return config.getInt("Skills.Alchemy.Catalysis.MaxBonusLevel", 1000); }
public int getCatalysisMaxBonusLevel() {
return config.getInt("Skills.Alchemy.Catalysis.MaxBonusLevel", 1000);
}
public double getCatalysisMinSpeed() { return config.getDouble("Skills.Alchemy.Catalysis.MinSpeed", 1.0D); }
public double getCatalysisMaxSpeed() { return config.getDouble("Skills.Alchemy.Catalysis.MaxSpeed", 4.0D); }
public double getCatalysisMinSpeed() {
return config.getDouble("Skills.Alchemy.Catalysis.MinSpeed", 1.0D);
}
public double getCatalysisMaxSpeed() {
return config.getDouble("Skills.Alchemy.Catalysis.MaxSpeed", 4.0D);
}
/* ARCHERY */
public double getSkillShotRankDamageMultiplier() { return config.getDouble("Skills.Archery.SkillShot.RankDamageMultiplier", 10.0D); }
public double getSkillShotDamageMax() { return config.getDouble("Skills.Archery.SkillShot.MaxDamage", 9.0D); }
public double getSkillShotRankDamageMultiplier() {
return config.getDouble("Skills.Archery.SkillShot.RankDamageMultiplier", 10.0D);
}
public double getDazeBonusDamage() { return config.getDouble("Skills.Archery.Daze.BonusDamage", 4.0D); }
public double getSkillShotDamageMax() {
return config.getDouble("Skills.Archery.SkillShot.MaxDamage", 9.0D);
}
public double getForceMultiplier() { return config.getDouble("Skills.Archery.ForceMultiplier", 2.0D); }
public double getDazeBonusDamage() {
return config.getDouble("Skills.Archery.Daze.BonusDamage", 4.0D);
}
public double getForceMultiplier() {
return config.getDouble("Skills.Archery.ForceMultiplier", 2.0D);
}
/* AXES */
public double getAxeMasteryRankDamageMultiplier() { return config.getDouble("Skills.Axes.AxeMastery.RankDamageMultiplier", 1.0D); }
public double getAxeMasteryRankDamageMultiplier() {
return config.getDouble("Skills.Axes.AxeMastery.RankDamageMultiplier", 1.0D);
}
public double getCriticalStrikesPVPModifier() { return config.getDouble("Skills.Axes.CriticalStrikes.PVP_Modifier", 1.5D); }
public double getCriticalStrikesPVEModifier() { return config.getDouble("Skills.Axes.CriticalStrikes.PVE_Modifier", 2.0D); }
public double getCriticalStrikesPVPModifier() {
return config.getDouble("Skills.Axes.CriticalStrikes.PVP_Modifier", 1.5D);
}
public double getGreaterImpactChance() { return config.getDouble("Skills.Axes.GreaterImpact.Chance", 25.0D); }
public double getGreaterImpactModifier() { return config.getDouble("Skills.Axes.GreaterImpact.KnockbackModifier", 1.5D); }
public double getGreaterImpactBonusDamage() { return config.getDouble("Skills.Axes.GreaterImpact.BonusDamage", 2.0D); }
public double getCriticalStrikesPVEModifier() {
return config.getDouble("Skills.Axes.CriticalStrikes.PVE_Modifier", 2.0D);
}
public double getImpactChance() { return config.getDouble("Skills.Axes.ArmorImpact.Chance", 25.0D); }
public double getImpactDurabilityDamageMultiplier() { return config.getDouble("Skills.Axes.ArmorImpact.DamagePerRank", 6.5D); }
public double getGreaterImpactChance() {
return config.getDouble("Skills.Axes.GreaterImpact.Chance", 25.0D);
}
public double getSkullSplitterModifier() { return config.getDouble("Skills.Axes.SkullSplitter.DamageModifier", 2.0D); }
public double getGreaterImpactModifier() {
return config.getDouble("Skills.Axes.GreaterImpact.KnockbackModifier", 1.5D);
}
public double getGreaterImpactBonusDamage() {
return config.getDouble("Skills.Axes.GreaterImpact.BonusDamage", 2.0D);
}
public double getImpactChance() {
return config.getDouble("Skills.Axes.ArmorImpact.Chance", 25.0D);
}
public double getImpactDurabilityDamageMultiplier() {
return config.getDouble("Skills.Axes.ArmorImpact.DamagePerRank", 6.5D);
}
public double getSkullSplitterModifier() {
return config.getDouble("Skills.Axes.SkullSplitter.DamageModifier", 2.0D);
}
/* EXCAVATION */
//Nothing to configure, everything is already configurable in config.yml
/* FISHING */
public double getShakeChance(int rank) { return config.getDouble("Skills.Fishing.ShakeChance.Rank_" + rank); }
public int getFishingVanillaXPModifier(int rank) { return config.getInt("Skills.Fishing.VanillaXPMultiplier.Rank_" + rank); }
public double getShakeChance(int rank) {
return config.getDouble("Skills.Fishing.ShakeChance.Rank_" + rank);
}
public int getFishingReductionMinWaitTicks() { return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Per_Rank.Min_Wait", 10);}
public int getFishingReductionMaxWaitTicks() { return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Per_Rank.Max_Wait", 30);}
public int getFishingBoatReductionMinWaitTicks() { return config.getInt("Skills.Fishing.MasterAngler.Boat_Tick_Reduction.Min_Wait", 10);}
public int getFishingBoatReductionMaxWaitTicks() { return config.getInt("Skills.Fishing.MasterAngler.Boat_Tick_Reduction.Max_Wait", 30);}
public int getFishingReductionMinWaitCap() { return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Caps.Min_Wait", 40);}
public int getFishingReductionMaxWaitCap() { return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Caps.Max_Wait", 100);}
public int getFishermanDietRankChange() { return config.getInt("Skills.Fishing.FishermansDiet.RankChange", 200); }
public int getFishingVanillaXPModifier(int rank) {
return config.getInt("Skills.Fishing.VanillaXPMultiplier.Rank_" + rank);
}
public int getFishingReductionMinWaitTicks() {
return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Per_Rank.Min_Wait", 10);
}
public int getFishingReductionMaxWaitTicks() {
return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Per_Rank.Max_Wait", 30);
}
public int getFishingBoatReductionMinWaitTicks() {
return config.getInt("Skills.Fishing.MasterAngler.Boat_Tick_Reduction.Min_Wait", 10);
}
public int getFishingBoatReductionMaxWaitTicks() {
return config.getInt("Skills.Fishing.MasterAngler.Boat_Tick_Reduction.Max_Wait", 30);
}
public int getFishingReductionMinWaitCap() {
return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Caps.Min_Wait", 40);
}
public int getFishingReductionMaxWaitCap() {
return config.getInt("Skills.Fishing.MasterAngler.Tick_Reduction_Caps.Max_Wait", 100);
}
public int getFishermanDietRankChange() {
return config.getInt("Skills.Fishing.FishermansDiet.RankChange", 200);
}
public double getMasterAnglerBoatModifier() {return config.getDouble("Skills.Fishing.MasterAngler.BoatModifier", 2.0); }
public double getMasterAnglerBiomeModifier() {return config.getDouble("Skills.Fishing.MasterAngler.BiomeModifier", 2.0); }
public double getMasterAnglerBoatModifier() {
return config.getDouble("Skills.Fishing.MasterAngler.BoatModifier", 2.0);
}
public double getMasterAnglerBiomeModifier() {
return config.getDouble("Skills.Fishing.MasterAngler.BiomeModifier", 2.0);
}
/* HERBALISM */
public int getFarmerDietRankChange() { return config.getInt("Skills.Herbalism.FarmersDiet.RankChange", 200); }
public int getFarmerDietRankChange() {
return config.getInt("Skills.Herbalism.FarmersDiet.RankChange", 200);
}
public int getGreenThumbStageChange() { return config.getInt("Skills.Herbalism.GreenThumb.StageChange", 200); }
public int getGreenThumbStageChange() {
return config.getInt("Skills.Herbalism.GreenThumb.StageChange", 200);
}
/* MINING */
public boolean getDoubleDropSilkTouchEnabled() { return config.getBoolean("Skills.Mining.DoubleDrops.SilkTouch", true); }
public boolean getAllowMiningTripleDrops() { return config.getBoolean("Skills.Mining.SuperBreaker.AllowTripleDrops", true); }
public int getBlastMiningRankLevel(int rank) { return config.getInt("Skills.Mining.BlastMining.Rank_Levels.Rank_" + rank); }
public double getBlastDamageDecrease(int rank) { return config.getDouble("Skills.Mining.BlastMining.BlastDamageDecrease.Rank_" + rank); }
public double getOreBonus(int rank) { return config.getDouble("Skills.Mining.BlastMining.OreBonus.Rank_" + rank); }
public double getDebrisReduction(int rank) { return config.getDouble("Skills.Mining.BlastMining.DebrisReduction.Rank_" + rank); }
public int getDropMultiplier(int rank) { return config.getInt("Skills.Mining.BlastMining.DropMultiplier.Rank_" + rank); }
public double getBlastRadiusModifier(int rank) { return config.getDouble("Skills.Mining.BlastMining.BlastRadiusModifier.Rank_" + rank); }
public boolean getDoubleDropSilkTouchEnabled() {
return config.getBoolean("Skills.Mining.DoubleDrops.SilkTouch", true);
}
public boolean getAllowMiningTripleDrops() {
return config.getBoolean("Skills.Mining.SuperBreaker.AllowTripleDrops", true);
}
public int getBlastMiningRankLevel(int rank) {
return config.getInt("Skills.Mining.BlastMining.Rank_Levels.Rank_" + rank);
}
public double getBlastDamageDecrease(int rank) {
return config.getDouble("Skills.Mining.BlastMining.BlastDamageDecrease.Rank_" + rank);
}
public double getOreBonus(int rank) {
return config.getDouble("Skills.Mining.BlastMining.OreBonus.Rank_" + rank);
}
public boolean isBlastMiningBonusDropsEnabled() {
return config.getBoolean("Skills.Mining.BlastMining.Bonus_Drops.Enabled", true);
}
public double getDebrisReduction(int rank) {
return config.getDouble("Skills.Mining.BlastMining.DebrisReduction.Rank_" + rank);
}
public int getDropMultiplier(int rank) {
return config.getInt("Skills.Mining.BlastMining.DropMultiplier.Rank_" + rank);
}
public double getBlastRadiusModifier(int rank) {
return config.getDouble("Skills.Mining.BlastMining.BlastRadiusModifier.Rank_" + rank);
}
/* REPAIR */
public double getRepairMasteryMaxBonus() { return config.getDouble("Skills.Repair.RepairMastery.MaxBonusPercentage", 200.0D); }
public int getRepairMasteryMaxLevel() { return config.getInt("Skills.Repair.RepairMastery.MaxBonusLevel", 100); }
public double getRepairMasteryMaxBonus() {
return config.getDouble("Skills.Repair.RepairMastery.MaxBonusPercentage", 200.0D);
}
public boolean getArcaneForgingEnchantLossEnabled() { return config.getBoolean("Skills.Repair.ArcaneForging.May_Lose_Enchants", true); }
public double getArcaneForgingKeepEnchantsChance(int rank) { return config.getDouble("Skills.Repair.ArcaneForging.Keep_Enchants_Chance.Rank_" + rank); }
public int getRepairMasteryMaxLevel() {
return config.getInt("Skills.Repair.RepairMastery.MaxBonusLevel", 100);
}
public boolean getArcaneForgingDowngradeEnabled() { return config.getBoolean("Skills.Repair.ArcaneForging.Downgrades_Enabled", true); }
public double getArcaneForgingDowngradeChance(int rank) { return config.getDouble("Skills.Repair.ArcaneForging.Downgrades_Chance.Rank_" + rank); }
public boolean getAllowEnchantedRepairMaterials() {
return config.getBoolean("Skills.Repair.Use_Enchanted_Materials", false);
}
public boolean getArcaneSalvageEnchantDowngradeEnabled() { return config.getBoolean("Skills.Salvage.ArcaneSalvage.EnchantDowngradeEnabled", true); }
public boolean getArcaneSalvageEnchantLossEnabled() { return config.getBoolean("Skills.Salvage.ArcaneSalvage.EnchantLossEnabled", true); }
public boolean getArcaneForgingEnchantLossEnabled() {
return config.getBoolean("Skills.Repair.ArcaneForging.May_Lose_Enchants", true);
}
public double getArcaneSalvageExtractFullEnchantsChance(int rank) { return config.getDouble("Skills.Salvage.ArcaneSalvage.ExtractFullEnchant.Rank_" + rank); }
public double getArcaneSalvageExtractPartialEnchantsChance(int rank) { return config.getDouble("Skills.Salvage.ArcaneSalvage.ExtractPartialEnchant.Rank_" + rank); }
public double getArcaneForgingKeepEnchantsChance(int rank) {
return config.getDouble("Skills.Repair.ArcaneForging.Keep_Enchants_Chance.Rank_" + rank);
}
public boolean getArcaneForgingDowngradeEnabled() {
return config.getBoolean("Skills.Repair.ArcaneForging.Downgrades_Enabled", true);
}
public double getArcaneForgingDowngradeChance(int rank) {
return config.getDouble("Skills.Repair.ArcaneForging.Downgrades_Chance.Rank_" + rank);
}
public boolean getArcaneSalvageEnchantDowngradeEnabled() {
return config.getBoolean("Skills.Salvage.ArcaneSalvage.EnchantDowngradeEnabled", true);
}
public boolean getArcaneSalvageEnchantLossEnabled() {
return config.getBoolean("Skills.Salvage.ArcaneSalvage.EnchantLossEnabled", true);
}
public double getArcaneSalvageExtractFullEnchantsChance(int rank) {
return config.getDouble("Skills.Salvage.ArcaneSalvage.ExtractFullEnchant.Rank_" + rank);
}
public double getArcaneSalvageExtractPartialEnchantsChance(int rank) {
return config.getDouble("Skills.Salvage.ArcaneSalvage.ExtractPartialEnchant.Rank_" + rank);
}
/* SMELTING */
public int getBurnModifierMaxLevel() {
if(mcMMO.isRetroModeEnabled())
if (mcMMO.isRetroModeEnabled())
return config.getInt("Skills.Smelting.FuelEfficiency.RetroMode.MaxBonusLevel", 1000);
else
return config.getInt("Skills.Smelting.FuelEfficiency.Standard.MaxBonusLevel", 100);
}
public double getFluxMiningChance() { return config.getDouble("Skills.Smelting.FluxMining.Chance", 33.0D); }
public double getFluxMiningChance() {
return config.getDouble("Skills.Smelting.FluxMining.Chance", 33.0D);
}
/* SWORDS */
public double getRuptureTickDamage(boolean isTargetPlayer, int rank) {
@@ -731,35 +873,68 @@ public class AdvancedConfig extends AutoUpdateConfigLoader {
return config.getDouble(root + rank, 33);
}
public double getCounterModifier() { return config.getDouble("Skills.Swords.CounterAttack.DamageModifier", 2.0D); }
public double getCounterModifier() {
return config.getDouble("Skills.Swords.CounterAttack.DamageModifier", 2.0D);
}
public double getSerratedStrikesModifier() { return config.getDouble("Skills.Swords.SerratedStrikes.DamageModifier", 4.0D); }
public int getSerratedStrikesTicks() { return config.getInt("Skills.Swords.SerratedStrikes.RuptureTicks", 5); }
public double getSerratedStrikesModifier() {
return config.getDouble("Skills.Swords.SerratedStrikes.DamageModifier", 4.0D);
}
public int getSerratedStrikesTicks() {
return config.getInt("Skills.Swords.SerratedStrikes.RuptureTicks", 5);
}
/* TAMING */
public double getGoreModifier() { return config.getDouble("Skills.Taming.Gore.Modifier", 2.0D); }
public double getGoreModifier() {
return config.getDouble("Skills.Taming.Gore.Modifier", 2.0D);
}
public double getFastFoodChance() { return config.getDouble("Skills.Taming.FastFoodService.Chance", 50.0D); }
public double getPummelChance() { return config.getDouble("Skills.Taming.Pummel.Chance", 10.0D); }
public double getFastFoodChance() {
return config.getDouble("Skills.Taming.FastFoodService.Chance", 50.0D);
}
public double getThickFurModifier() { return config.getDouble("Skills.Taming.ThickFur.Modifier", 2.0D); }
public double getPummelChance() {
return config.getDouble("Skills.Taming.Pummel.Chance", 10.0D);
}
public double getShockProofModifier() { return config.getDouble("Skills.Taming.ShockProof.Modifier", 6.0D); }
public double getThickFurModifier() {
return config.getDouble("Skills.Taming.ThickFur.Modifier", 2.0D);
}
public double getSharpenedClawsBonus() { return config.getDouble("Skills.Taming.SharpenedClaws.Bonus", 2.0D); }
public double getShockProofModifier() {
return config.getDouble("Skills.Taming.ShockProof.Modifier", 6.0D);
}
public double getMinHorseJumpStrength() { return config.getDouble("Skills.Taming.CallOfTheWild.MinHorseJumpStrength", 0.7D); }
public double getMaxHorseJumpStrength() { return config.getDouble("Skills.Taming.CallOfTheWild.MaxHorseJumpStrength", 2.0D); }
public double getSharpenedClawsBonus() {
return config.getDouble("Skills.Taming.SharpenedClaws.Bonus", 2.0D);
}
public double getMinHorseJumpStrength() {
return config.getDouble("Skills.Taming.CallOfTheWild.MinHorseJumpStrength", 0.7D);
}
public double getMaxHorseJumpStrength() {
return config.getDouble("Skills.Taming.CallOfTheWild.MaxHorseJumpStrength", 2.0D);
}
/* UNARMED */
public boolean isSteelArmDamageCustom() { return config.getBoolean("Skills.Unarmed.SteelArmStyle.Damage_Override", false); }
public boolean isSteelArmDamageCustom() {
return config.getBoolean("Skills.Unarmed.SteelArmStyle.Damage_Override", false);
}
public double getSteelArmOverride(int rank, double def) {
String key = "Rank_" + rank;
return config.getDouble("Skills.Unarmed.SteelArmStyle.Override." + key, def);
}
public boolean getDisarmProtected() { return config.getBoolean("Skills.Unarmed.Disarm.AntiTheft", false); }
public boolean getDisarmProtected() {
return config.getBoolean("Skills.Unarmed.Disarm.AntiTheft", false);
}
/* WOODCUTTING */
public boolean isKnockOnWoodXPOrbEnabled() { return config.getBoolean("Skills.Woodcutting.TreeFeller.Knock_On_Wood.Add_XP_Orbs_To_Drops", true); }
public boolean isKnockOnWoodXPOrbEnabled() {
return config.getBoolean("Skills.Woodcutting.TreeFeller.Knock_On_Wood.Add_XP_Orbs_To_Drops", true);
}
}

View File

@@ -1,167 +0,0 @@
package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;
public abstract class AutoUpdateConfigLoader extends ConfigLoader {
public AutoUpdateConfigLoader(String relativePath, String fileName, File dataFolder) {
super(relativePath, fileName, dataFolder);
}
public AutoUpdateConfigLoader(String fileName, File dataFolder) {
super(fileName, dataFolder);
}
@Deprecated
public AutoUpdateConfigLoader(String relativePath, String fileName) {
super(relativePath, fileName);
}
@Deprecated
public AutoUpdateConfigLoader(String fileName) {
super(fileName);
}
protected void saveConfig() {
try {
mcMMO.p.getLogger().info("Saving changes to config file - "+fileName);
config.save(configFile);
} catch (IOException e) {
e.printStackTrace();
}
}
protected @NotNull FileConfiguration getInternalConfig() {
return YamlConfiguration.loadConfiguration(mcMMO.p.getResourceAsReader(fileName));
}
@Override
protected void loadFile() {
super.loadFile();
FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(mcMMO.p.getResourceAsReader(fileName));
Set<String> configKeys = config.getKeys(true);
Set<String> internalConfigKeys = internalConfig.getKeys(true);
boolean needSave = false;
Set<String> oldKeys = new HashSet<>(configKeys);
oldKeys.removeAll(internalConfigKeys);
Set<String> newKeys = new HashSet<>(internalConfigKeys);
newKeys.removeAll(configKeys);
// Don't need a re-save if we have old keys sticking around?
// Would be less saving, but less... correct?
if (!newKeys.isEmpty() || !oldKeys.isEmpty()) {
needSave = true;
}
//
// for (String key : oldKeys) {
// mcMMO.p.debug("Detected potentially unused key: " + key);
// //config.set(key, null);
// }
for (String key : newKeys) {
mcMMO.p.debug("Adding new key: " + key + " = " + internalConfig.get(key));
config.set(key, internalConfig.get(key));
}
if (needSave) {
// Get Bukkit's version of an acceptable config with new keys, and no old keys
String output = config.saveToString();
// Convert to the superior 4 space indentation
output = output.replace(" ", " ");
// Rip out Bukkit's attempt to save comments at the top of the file
while (output.replaceAll("[//s]", "").startsWith("#")) {
output = output.substring(output.indexOf('\n', output.indexOf('#')) + 1);
}
// Read the internal config to get comments, then put them in the new one
try {
// Read internal
BufferedReader reader = new BufferedReader(new InputStreamReader(mcMMO.p.getResource(fileName)));
LinkedHashMap<String, String> comments = new LinkedHashMap<>();
StringBuilder temp = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("#")) {
temp.append(line).append("\n");
}
else if (line.contains(":")) {
line = line.substring(0, line.indexOf(":") + 1);
if (temp.length() > 0) {
if(comments.containsKey(line)) {
int index = 0;
while(comments.containsKey(line + index)) {
index++;
}
line = line + index;
}
comments.put(line, temp.toString());
temp = new StringBuilder();
}
}
}
// Dump to the new one
HashMap<String, Integer> indexed = new HashMap<>();
for (String key : comments.keySet()) {
String actualkey = key.substring(0, key.indexOf(":") + 1);
int index = 0;
if(indexed.containsKey(actualkey)) {
index = indexed.get(actualkey);
}
boolean isAtTop = !output.contains("\n" + actualkey);
index = output.indexOf((isAtTop ? "" : "\n") + actualkey, index);
if (index >= 0) {
output = output.substring(0, index) + "\n" + comments.get(key) + output.substring(isAtTop ? index : index + 1);
indexed.put(actualkey, index + comments.get(key).length() + actualkey.length() + 1);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
// Save it
if(dataFolder == null) {
mcMMO.p.getLogger().severe("Data folder should never be null!");
return;
}
try {
String saveName = fileName;
// At this stage we cannot guarantee that Config has been loaded, so we do the check directly here
if (!mcMMO.p.getConfig().getBoolean("General.Config_Update_Overwrite", true)) {
saveName += ".new";
}
File newSaveFile = new File(dataFolder, saveName);
FileWriter fileWriter = new FileWriter(newSaveFile.getAbsolutePath());
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(output);
writer.flush();
writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,106 @@
package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public abstract class AutoUpdateLegacyConfigLoader extends LegacyConfigLoader {
public AutoUpdateLegacyConfigLoader(String relativePath, String fileName, File dataFolder) {
super(relativePath, fileName, dataFolder);
}
public AutoUpdateLegacyConfigLoader(String fileName, File dataFolder) {
super(fileName, dataFolder);
}
@Deprecated
public AutoUpdateLegacyConfigLoader(String relativePath, String fileName) {
super(relativePath, fileName);
}
@Deprecated
public AutoUpdateLegacyConfigLoader(String fileName) {
super(fileName);
}
protected void saveConfig() {
try {
LogUtils.debug(mcMMO.p.getLogger(), "Saving changes to config file - " + fileName);
config.options().indent(2);
config.save(configFile);
} catch (IOException e) {
e.printStackTrace();
}
}
protected @NotNull FileConfiguration getInternalConfig() {
return YamlConfiguration.loadConfiguration(mcMMO.p.getResourceAsReader(fileName));
}
@Override
protected void loadFile() {
super.loadFile();
FileConfiguration internalConfig = YamlConfiguration.loadConfiguration(mcMMO.p.getResourceAsReader(fileName));
Set<String> configKeys = config.getKeys(true);
Set<String> internalConfigKeys = internalConfig.getKeys(true);
boolean needSave = false;
// keys present in current config file that are not in the template
Set<String> oldKeys = new HashSet<>(configKeys);
oldKeys.removeAll(internalConfigKeys);
if (!oldKeys.isEmpty()) {
LogUtils.debug(mcMMO.p.getLogger(), "old key(s) in \"" + fileName + "\"");
for (String key : oldKeys) {
LogUtils.debug(mcMMO.p.getLogger(), " old-key:" + key);
}
}
// keys present in template that are not in current file
Set<String> newKeys = new HashSet<>(internalConfigKeys);
newKeys.removeAll(configKeys);
if (!newKeys.isEmpty()) {
needSave = true;
}
for (String key : newKeys) {
LogUtils.debug(mcMMO.p.getLogger(), "Adding new key: " + key + " = " + internalConfig.get(key));
config.set(key, internalConfig.get(key));
}
if (needSave) {
// Save it
if (dataFolder == null) {
mcMMO.p.getLogger().severe("Data folder should never be null!");
return;
}
try {
String saveName = fileName;
// At this stage we cannot guarantee that Config has been loaded, so we do the check directly here
if (!mcMMO.p.getConfig().getBoolean("General.Config_Update_Overwrite", true)) {
saveName += ".new";
}
File newSaveFile = new File(dataFolder, saveName);
YamlConfiguration yamlConfiguration = config;
yamlConfiguration.options().indent(4);
yamlConfiguration.save(newSaveFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,181 @@
package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public abstract class BukkitConfig {
boolean copyDefaults = true;
protected final String fileName;
protected final File configFile;
protected YamlConfiguration defaultYamlConfig;
protected YamlConfiguration config;
protected @NotNull final File dataFolder;
private boolean savedDefaults = false;
public BukkitConfig(@NotNull String fileName, @NotNull File dataFolder, boolean copyDefaults) {
LogUtils.debug(mcMMO.p.getLogger(), "Initializing config: " + fileName);
this.copyDefaults = copyDefaults;
this.fileName = fileName;
this.dataFolder = dataFolder;
configFile = new File(dataFolder, fileName);
this.defaultYamlConfig = saveDefaultConfigToDisk();
this.config = initConfig();
updateFile();
LogUtils.debug(mcMMO.p.getLogger(), "Config initialized: " + fileName);
}
public BukkitConfig(@NotNull String fileName, @NotNull File dataFolder) {
this(fileName, dataFolder, true);
}
public BukkitConfig(@NotNull String fileName) {
this(fileName, mcMMO.p.getDataFolder());
}
public BukkitConfig(@NotNull String fileName, boolean copyDefaults) {
this(fileName, mcMMO.p.getDataFolder(), copyDefaults);
}
/**
* Update the file on the disk by copying out any new and missing defaults
*/
public void updateFile() {
try {
config.save(configFile);
if(copyDefaults && !savedDefaults) {
copyMissingDefaultsFromResource();
savedDefaults = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Copies missing keys and values from the internal resource config within the JAR
*/
private void copyMissingDefaultsFromResource() {
boolean updated = false;
for (String key : defaultYamlConfig.getKeys(true)) {
if (!config.contains(key)) {
config.set(key, defaultYamlConfig.get(key));
updated = true;
}
}
if (updated) {
updateFile();
}
}
/**
* Copies the config from the JAR to defaults/<fileName>
*/
YamlConfiguration saveDefaultConfigToDisk() {
LogUtils.debug(mcMMO.p.getLogger(), "Copying default config to disk: " + fileName + " to defaults/" + fileName);
try(InputStream inputStream = mcMMO.p.getResource(fileName)) {
if(inputStream == null) {
mcMMO.p.getLogger().severe("Unable to copy default config: " + fileName);
return null;
}
//Save default file into defaults/<fileName>
File defaultsFolder = new File(dataFolder, "defaults");
if (!defaultsFolder.exists()) {
defaultsFolder.mkdir();
}
File defaultFile = new File(defaultsFolder, fileName);
Path path = defaultFile.toPath();
Files.copy(inputStream, path, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
// Load file into YAML config
YamlConfiguration defaultYamlConfig = new YamlConfiguration();
defaultYamlConfig.load(defaultFile);
return defaultYamlConfig;
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
return null;
}
YamlConfiguration initConfig() {
if (!configFile.exists()) {
LogUtils.debug(mcMMO.p.getLogger(), "User config file not found, copying a default config to disk: " + fileName);
mcMMO.p.saveResource(fileName, false);
}
LogUtils.debug(mcMMO.p.getLogger(), "Loading config from disk: " + fileName);
YamlConfiguration config = new YamlConfiguration();
config.options().indent(4);
try {
config.options().parseComments(true);
} catch (NoSuchMethodError e) {
//e.printStackTrace();
// mcMMO.p.getLogger().severe("Your Spigot/CraftBukkit API is out of date, update your server software!");
}
config.options().copyDefaults(true);
try {
config.load(configFile);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
return config;
}
protected abstract void loadKeys();
protected boolean validateKeys() {
return true;
}
protected boolean noErrorsInConfig(List<String> issues) {
for (String issue : issues) {
mcMMO.p.getLogger().warning(issue);
}
return issues.isEmpty();
}
protected void validate() {
if (validateKeys()) {
LogUtils.debug(mcMMO.p.getLogger(), "No errors found in " + fileName + "!");
} else {
mcMMO.p.getLogger().warning("Errors were found in " + fileName + "! mcMMO was disabled!");
mcMMO.p.getServer().getPluginManager().disablePlugin(mcMMO.p);
mcMMO.p.noErrorsInConfigFiles = false;
}
}
public void backup() {
LogUtils.debug(mcMMO.p.getLogger(), "You are using an old version of the " + fileName + " file.");
LogUtils.debug(mcMMO.p.getLogger(), "Your old file has been renamed to " + fileName + ".old and has been replaced by an updated version.");
configFile.renameTo(new File(configFile.getPath() + ".old"));
if (mcMMO.p.getResource(fileName) != null) {
mcMMO.p.saveResource(fileName, true);
}
mcMMO.p.getLogger().warning("Reloading " + fileName + " with new values...");
initConfig();
loadKeys();
}
public File getFile() {
return configFile;
}
}

View File

@@ -4,7 +4,7 @@ import com.gmail.nossr50.datatypes.chat.ChatChannel;
import com.gmail.nossr50.util.text.StringUtils;
import org.jetbrains.annotations.NotNull;
public class ChatConfig extends AutoUpdateConfigLoader {
public class ChatConfig extends BukkitConfig {
private static ChatConfig instance;
private ChatConfig() {
@@ -40,8 +40,10 @@ public class ChatConfig extends AutoUpdateConfigLoader {
}
/**
* Whether or not to use display names for players in target {@link ChatChannel}
* Whether to use display names for players in target {@link ChatChannel}
*
* @param chatChannel target chat channel
*
* @return true if display names should be used
*/
public boolean useDisplayNames(@NotNull ChatChannel chatChannel) {

View File

@@ -4,28 +4,26 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill;
import com.gmail.nossr50.util.text.StringUtils;
public class CoreSkillsConfig extends AutoUpdateConfigLoader {
public class CoreSkillsConfig extends BukkitConfig {
private static CoreSkillsConfig instance;
public CoreSkillsConfig()
{
public CoreSkillsConfig() {
super("coreskills.yml");
validate();
}
public static CoreSkillsConfig getInstance() {
if (instance == null)
instance = new CoreSkillsConfig();
return instance;
}
@Override
protected void loadKeys() {
}
public static CoreSkillsConfig getInstance()
{
if(instance == null)
return new CoreSkillsConfig();
return instance;
}
@Override
protected boolean validateKeys() {
@@ -37,23 +35,25 @@ public class CoreSkillsConfig extends AutoUpdateConfigLoader {
*/
/**
* Whether or not a skill is enabled
* Whether a skill is enabled
* Defaults true
*
* @param abstractSubSkill SubSkill definition to check
*
* @return true if subskill is enabled
*/
public boolean isSkillEnabled(AbstractSubSkill abstractSubSkill)
{
return config.getBoolean(StringUtils.getCapitalized(abstractSubSkill.getPrimarySkill().toString())+"."+ abstractSubSkill.getConfigKeyName()+".Enabled", true);
public boolean isSkillEnabled(AbstractSubSkill abstractSubSkill) {
return config.getBoolean(StringUtils.getCapitalized(abstractSubSkill.getPrimarySkill().toString()) + "." + abstractSubSkill.getConfigKeyName() + ".Enabled", true);
}
/**
* Whether or not this primary skill is enabled
* Whether this primary skill is enabled
*
* @param primarySkillType target primary skill
*
* @return true if enabled
*/
public boolean isPrimarySkillEnabled(PrimarySkillType primarySkillType)
{
return config.getBoolean(StringUtils.getCapitalized(primarySkillType.toString())+".Enabled", true);
public boolean isPrimarySkillEnabled(PrimarySkillType primarySkillType) {
return config.getBoolean(StringUtils.getCapitalized(primarySkillType.toString()) + ".Enabled", true);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,27 +1,28 @@
package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO;
import org.bukkit.configuration.file.FileConfiguration;
import com.gmail.nossr50.util.LogUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.List;
public abstract class ConfigLoader {
protected String fileName;
@Deprecated
public abstract class LegacyConfigLoader {
protected final File configFile;
protected FileConfiguration config;
protected @NotNull final File dataFolder;
protected final @NotNull File dataFolder;
protected String fileName;
protected YamlConfiguration config;
public ConfigLoader(String relativePath, String fileName, @NotNull File dataFolder) {
public LegacyConfigLoader(String relativePath, String fileName, @NotNull File dataFolder) {
this.fileName = fileName;
this.dataFolder = dataFolder;
configFile = new File(dataFolder, relativePath + File.separator + fileName);
loadFile();
}
public ConfigLoader(String fileName, @NotNull File dataFolder) {
public LegacyConfigLoader(String fileName, @NotNull File dataFolder) {
this.fileName = fileName;
this.dataFolder = dataFolder;
configFile = new File(dataFolder, fileName);
@@ -29,7 +30,7 @@ public abstract class ConfigLoader {
}
@Deprecated
public ConfigLoader(String relativePath, String fileName) {
public LegacyConfigLoader(String relativePath, String fileName) {
this.fileName = fileName;
configFile = new File(mcMMO.p.getDataFolder(), relativePath + File.separator + fileName);
this.dataFolder = mcMMO.p.getDataFolder();
@@ -37,7 +38,7 @@ public abstract class ConfigLoader {
}
@Deprecated
public ConfigLoader(String fileName) {
public LegacyConfigLoader(String fileName) {
this.fileName = fileName;
configFile = new File(mcMMO.p.getDataFolder(), fileName);
this.dataFolder = mcMMO.p.getDataFolder();
@@ -46,17 +47,15 @@ public abstract class ConfigLoader {
protected void loadFile() {
if (!configFile.exists()) {
mcMMO.p.debug("Creating mcMMO " + fileName + " File...");
LogUtils.debug(mcMMO.p.getLogger(), "Creating mcMMO " + fileName + " File...");
try {
mcMMO.p.saveResource(fileName, false); // Normal files
}
catch (IllegalArgumentException ex) {
} catch (IllegalArgumentException ex) {
mcMMO.p.saveResource(configFile.getParentFile().getName() + File.separator + fileName, false); // Mod files
}
}
else {
mcMMO.p.debug("Loading mcMMO " + fileName + " File...");
} else {
LogUtils.debug(mcMMO.p.getLogger(), "Loading mcMMO " + fileName + " File...");
}
config = YamlConfiguration.loadConfiguration(configFile);
@@ -78,9 +77,8 @@ public abstract class ConfigLoader {
protected void validate() {
if (validateKeys()) {
mcMMO.p.debug("No errors found in " + fileName + "!");
}
else {
LogUtils.debug(mcMMO.p.getLogger(), "No errors found in " + fileName + "!");
} else {
mcMMO.p.getLogger().warning("Errors were found in " + fileName + "! mcMMO was disabled!");
mcMMO.p.getServer().getPluginManager().disablePlugin(mcMMO.p);
mcMMO.p.noErrorsInConfigFiles = false;

View File

@@ -1,8 +1,8 @@
package com.gmail.nossr50.config;
import com.gmail.nossr50.util.compat.layers.persistentdata.MobMetaFlagType;
import com.gmail.nossr50.metadata.MobMetaFlagType;
public class PersistentDataConfig extends AutoUpdateConfigLoader {
public class PersistentDataConfig extends BukkitConfig {
private static PersistentDataConfig instance;
private PersistentDataConfig() {

View File

@@ -3,35 +3,34 @@ package com.gmail.nossr50.config;
import com.gmail.nossr50.datatypes.skills.SubSkillType;
import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class RankConfig extends AutoUpdateConfigLoader {
public class RankConfig extends BukkitConfig {
private static RankConfig instance;
public RankConfig()
{
public RankConfig() {
super("skillranks.yml");
validate();
instance = this;
}
@Override
protected void loadKeys() {
}
public static RankConfig getInstance()
{
if(instance == null)
public static RankConfig getInstance() {
if (instance == null)
return new RankConfig();
return instance;
}
@Override
protected void loadKeys() {
}
@Override
protected boolean validateKeys() {
List<String> reason = new ArrayList<>();
@@ -46,12 +45,13 @@ public class RankConfig extends AutoUpdateConfigLoader {
/**
* Returns the unlock level for a subskill depending on the gamemode
*
* @param subSkillType target subskill
* @param rank the rank we are checking
* @param rank the rank we are checking
*
* @return the level requirement for a subskill at this particular rank
*/
public int getSubSkillUnlockLevel(SubSkillType subSkillType, int rank)
{
public int getSubSkillUnlockLevel(SubSkillType subSkillType, int rank) {
String key = subSkillType.getRankConfigAddress();
return findRankByRootAddress(rank, key);
@@ -59,33 +59,37 @@ public class RankConfig extends AutoUpdateConfigLoader {
/**
* Returns the unlock level for a subskill depending on the gamemode
*
* @param subSkillType target subskill
* @param rank the rank we are checking
* @param rank the rank we are checking
*
* @return the level requirement for a subskill at this particular rank
*/
public int getSubSkillUnlockLevel(SubSkillType subSkillType, int rank, boolean retroMode)
{
public int getSubSkillUnlockLevel(SubSkillType subSkillType, int rank, boolean retroMode) {
String key = getRankAddressKey(subSkillType, rank, retroMode);
return config.getInt(key, getInternalConfig().getInt(key));
return config.getInt(key, defaultYamlConfig.getInt(key));
}
/**
* Returns the unlock level for a subskill depending on the gamemode
*
* @param abstractSubSkill target subskill
* @param rank the rank we are checking
* @param rank the rank we are checking
*
* @return the level requirement for a subskill at this particular rank
*/
public int getSubSkillUnlockLevel(AbstractSubSkill abstractSubSkill, int rank)
{
String key = abstractSubSkill.getPrimaryKeyName()+"."+abstractSubSkill.getConfigKeyName();
public int getSubSkillUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) {
String key = abstractSubSkill.getPrimaryKeyName() + "." + abstractSubSkill.getConfigKeyName();
return findRankByRootAddress(rank, key);
}
/**
* Returns the unlock level for a subskill depending on the gamemode
* @param key root address of the subskill in the rankskills.yml file
*
* @param key root address of the subskill in the rankskills.yml file
* @param rank the rank we are checking
*
* @return the level requirement for a subskill at this particular rank
*/
private int findRankByRootAddress(int rank, String key) {
@@ -125,62 +129,57 @@ public class RankConfig extends AutoUpdateConfigLoader {
private void resetRankValue(@NotNull SubSkillType subSkillType, int rank, boolean retroMode) {
String key = getRankAddressKey(subSkillType, rank, retroMode);
int defaultValue = getInternalConfig().getInt(key);
int defaultValue = defaultYamlConfig.getInt(key);
config.set(key, defaultValue);
mcMMO.p.getLogger().info(key +" SET -> " + defaultValue);
LogUtils.debug(mcMMO.p.getLogger(), key + " SET -> " + defaultValue);
}
/**
* Checks for valid keys for subskill ranks
*/
private void checkKeys(@NotNull List<String> reasons)
{
private void checkKeys(@NotNull List<String> reasons) {
HashSet<SubSkillType> badSkillSetup = new HashSet<>();
//For now we will only check ranks of stuff I've overhauled
checkConfig(reasons, badSkillSetup, true);
checkConfig(reasons, badSkillSetup, false);
//Fix bad entries
if(badSkillSetup.isEmpty())
if (badSkillSetup.isEmpty())
return;
mcMMO.p.getLogger().info("(FIXING CONFIG) mcMMO is correcting a few mistakes found in your skill rank config setup");
LogUtils.debug(mcMMO.p.getLogger(), "(FIXING CONFIG) mcMMO is correcting a few mistakes found in your skill rank config setup");
for(SubSkillType subSkillType : badSkillSetup) {
mcMMO.p.getLogger().info("(FIXING CONFIG) Resetting rank config settings for skill named - "+subSkillType.toString());
for (SubSkillType subSkillType : badSkillSetup) {
LogUtils.debug(mcMMO.p.getLogger(), "(FIXING CONFIG) Resetting rank config settings for skill named - " + subSkillType.toString());
fixBadEntries(subSkillType);
}
}
private void checkConfig(@NotNull List<String> reasons, @NotNull HashSet<SubSkillType> badSkillSetup, boolean retroMode) {
for(SubSkillType subSkillType : SubSkillType.values())
{
for (SubSkillType subSkillType : SubSkillType.values()) {
//Keeping track of the rank requirements and making sure there are no logical errors
int curRank = 0;
int prevRank = 0;
for(int x = 0; x < subSkillType.getNumRanks(); x++)
{
int index = x+1;
for (int x = 0; x < subSkillType.getNumRanks(); x++) {
int index = x + 1;
if(curRank > 0)
if (curRank > 0)
prevRank = curRank;
curRank = getSubSkillUnlockLevel(subSkillType, index, retroMode);
//Do we really care if its below 0? Probably not
if(curRank < 0)
{
reasons.add("(CONFIG ISSUE) " + subSkillType.toString() + " should not have any ranks that require a negative level!");
if (curRank < 0) {
reasons.add("(CONFIG ISSUE) " + subSkillType + " should not have any ranks that require a negative level!");
badSkillSetup.add(subSkillType);
continue;
}
if(prevRank > curRank)
{
if (prevRank > curRank) {
//We're going to allow this but we're going to warn them
mcMMO.p.getLogger().info("(CONFIG ISSUE) You have the ranks for the subskill "+ subSkillType.toString()+" set up poorly, sequential ranks should have ascending requirements");
LogUtils.debug(mcMMO.p.getLogger(), "(CONFIG ISSUE) You have the ranks for the subskill " + subSkillType + " set up poorly, sequential ranks should have ascending requirements");
badSkillSetup.add(subSkillType);
}
}
@@ -188,9 +187,8 @@ public class RankConfig extends AutoUpdateConfigLoader {
}
private void fixBadEntries(@NotNull SubSkillType subSkillType) {
for(int x = 0; x < subSkillType.getNumRanks(); x++)
{
int index = x+1;
for (int x = 0; x < subSkillType.getNumRanks(); x++) {
int index = x + 1;
//Reset Retromode entries
resetRankValue(subSkillType, index, true);
@@ -198,6 +196,6 @@ public class RankConfig extends AutoUpdateConfigLoader {
resetRankValue(subSkillType, index, false);
}
saveConfig();
updateFile();
}
}

View File

@@ -1,47 +1,42 @@
package com.gmail.nossr50.config;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import com.gmail.nossr50.util.sounds.SoundType;
public class SoundConfig extends AutoUpdateConfigLoader {
public class SoundConfig extends BukkitConfig {
private static SoundConfig instance;
public SoundConfig()
{
public SoundConfig() {
super("sounds.yml");
validate();
instance = this;
}
public static SoundConfig getInstance() {
if (instance == null)
return new SoundConfig();
return instance;
}
@Override
protected void loadKeys() {
}
public static SoundConfig getInstance()
{
if(instance == null)
return new SoundConfig();
return instance;
}
@Override
protected boolean validateKeys() {
for(SoundType soundType : SoundType.values())
{
if(config.getDouble("Sounds."+soundType.toString()+".Volume") < 0)
{
mcMMO.p.getLogger().info("[mcMMO] Sound volume cannot be below 0 for "+soundType.toString());
for (SoundType soundType : SoundType.values()) {
if (config.getDouble("Sounds." + soundType.toString() + ".Volume") < 0) {
LogUtils.debug(mcMMO.p.getLogger(), "[mcMMO] Sound volume cannot be below 0 for " + soundType);
return false;
}
//Sounds with custom pitching don't use pitch values
if(!soundType.usesCustomPitch())
{
if(config.getDouble("Sounds."+soundType.toString()+".Pitch") < 0)
{
mcMMO.p.getLogger().info("[mcMMO] Sound pitch cannot be below 0 for "+soundType.toString());
if (!soundType.usesCustomPitch()) {
if (config.getDouble("Sounds." + soundType + ".Pitch") < 0) {
LogUtils.debug(mcMMO.p.getLogger(), "[mcMMO] Sound pitch cannot be below 0 for " + soundType);
return false;
}
}
@@ -49,23 +44,22 @@ public class SoundConfig extends AutoUpdateConfigLoader {
return true;
}
public float getMasterVolume() { return (float) config.getDouble("Sounds.MasterVolume", 1.0); }
public float getMasterVolume() {
return (float) config.getDouble("Sounds.MasterVolume", 1.0);
}
public float getVolume(SoundType soundType)
{
String key = "Sounds."+soundType.toString()+".Volume";
public float getVolume(SoundType soundType) {
String key = "Sounds." + soundType.toString() + ".Volume";
return (float) config.getDouble(key);
}
public float getPitch(SoundType soundType)
{
String key = "Sounds."+soundType.toString()+".Pitch";
public float getPitch(SoundType soundType) {
String key = "Sounds." + soundType.toString() + ".Pitch";
return (float) config.getDouble(key);
}
public boolean getIsEnabled(SoundType soundType)
{
String key = "Sounds."+soundType.toString()+".Enabled";
public boolean getIsEnabled(SoundType soundType) {
String key = "Sounds." + soundType.toString() + ".Enabled";
return config.getBoolean(key, true);
}
}

View File

@@ -15,20 +15,28 @@ public class WorldBlacklist {
private final String blackListFileName = "world_blacklist.txt";
public WorldBlacklist(mcMMO plugin)
{
public WorldBlacklist(mcMMO plugin) {
this.plugin = plugin;
blacklist = new ArrayList<>();
init();
}
public void init()
{
public static boolean isWorldBlacklisted(World world) {
for (String s : blacklist) {
if (world.getName().equalsIgnoreCase(s))
return true;
}
return false;
}
public void init() {
//Make the blacklist file if it doesn't exist
File blackListFile = new File(plugin.getDataFolder() + File.separator + blackListFileName);
try {
if(!blackListFile.exists())
if (!blackListFile.exists())
blackListFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
@@ -48,12 +56,11 @@ public class WorldBlacklist {
String currentLine;
while((currentLine = bufferedReader.readLine()) != null)
{
if(currentLine.length() == 0)
while ((currentLine = bufferedReader.readLine()) != null) {
if (currentLine.length() == 0)
continue;
if(!blacklist.contains(currentLine))
if (!blacklist.contains(currentLine))
blacklist.add(currentLine);
}
@@ -66,11 +73,12 @@ public class WorldBlacklist {
closeRead(fileReader);
}
plugin.getLogger().info(blacklist.size()+" entries in mcMMO World Blacklist");
if(blacklist.size() > 0)
plugin.getLogger().info(blacklist.size() + " entries in mcMMO World Blacklist");
}
private void closeRead(Reader reader) {
if(reader != null) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
@@ -78,16 +86,4 @@ public class WorldBlacklist {
}
}
}
public static boolean isWorldBlacklisted(World world)
{
for(String s : blacklist)
{
if(world.getName().equalsIgnoreCase(s))
return true;
}
return false;
}
}

View File

@@ -1,6 +1,6 @@
package com.gmail.nossr50.config.experience;
import com.gmail.nossr50.config.AutoUpdateConfigLoader;
import com.gmail.nossr50.config.BukkitConfig;
import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.datatypes.skills.MaterialType;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
@@ -13,12 +13,11 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.entity.EntityType;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class ExperienceConfig extends AutoUpdateConfigLoader {
public class ExperienceConfig extends BukkitConfig {
private static ExperienceConfig instance;
private ExperienceConfig() {
@@ -35,7 +34,8 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
@Override
protected void loadKeys() {}
protected void loadKeys() {
}
@Override
protected boolean validateKeys() {
@@ -140,81 +140,182 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
return noErrorsInConfig(reason);
}
public boolean isEarlyGameBoostEnabled() { return config.getBoolean("EarlyGameBoost.Enabled", true); }
public boolean isEarlyGameBoostEnabled() {
return config.getBoolean("EarlyGameBoost.Enabled", true);
}
/*
* FORMULA SETTINGS
*/
/* EXPLOIT TOGGLES */
public boolean isSnowExploitPrevented() { return config.getBoolean("ExploitFix.SnowGolemExcavation", true); }
public boolean isEndermanEndermiteFarmingPrevented() { return config.getBoolean("ExploitFix.EndermanEndermiteFarms", true); }
public boolean isPistonCheatingPrevented() { return config.getBoolean("ExploitFix.PistonCheating", true); }
public boolean isPistonExploitPrevented() { return config.getBoolean("ExploitFix.Pistons", false); }
public boolean allowUnsafeEnchantments() { return config.getBoolean("ExploitFix.UnsafeEnchantments", false); }
public boolean isCOTWBreedingPrevented() { return config.getBoolean("ExploitFix.COTWBreeding", true); }
public boolean isNPCInteractionPrevented() { return config.getBoolean("ExploitFix.PreventPluginNPCInteraction", true); }
public boolean isSnowExploitPrevented() {
return config.getBoolean("ExploitFix.SnowGolemExcavation", true);
}
public boolean isFishingExploitingPrevented() { return config.getBoolean("ExploitFix.Fishing", true); }
public boolean isAcrobaticsExploitingPrevented() { return config.getBoolean("ExploitFix.Acrobatics", true); }
public boolean isTreeFellerXPReduced() { return config.getBoolean("ExploitFix.TreeFellerReducedXP", true); }
public boolean isEndermanEndermiteFarmingPrevented() {
return config.getBoolean("ExploitFix.EndermanEndermiteFarms", true);
}
public boolean isPistonCheatingPrevented() {
return config.getBoolean("ExploitFix.PistonCheating", true);
}
public boolean isPistonExploitPrevented() {
return config.getBoolean("ExploitFix.Pistons", false);
}
public boolean allowUnsafeEnchantments() {
return config.getBoolean("ExploitFix.UnsafeEnchantments", false);
}
public boolean isCOTWBreedingPrevented() {
return config.getBoolean("ExploitFix.COTWBreeding", true);
}
public boolean isNPCInteractionPrevented() {
return config.getBoolean("ExploitFix.PreventPluginNPCInteraction", true);
}
public boolean isFishingExploitingPrevented() {
return config.getBoolean("ExploitFix.Fishing", true);
}
public int getFishingExploitingOptionMoveRange() {
return config.getInt("Fishing_ExploitFix_Options.MoveRange", 3);
}
public int getFishingExploitingOptionOverFishLimit() {
return config.getInt("Fishing_ExploitFix_Options.OverFishLimit", 10);
}
public boolean isAcrobaticsExploitingPrevented() {
return config.getBoolean("ExploitFix.Acrobatics", true);
}
public boolean isTreeFellerXPReduced() {
return config.getBoolean("ExploitFix.TreeFellerReducedXP", true);
}
/* Curve settings */
public FormulaType getFormulaType() { return FormulaType.getFormulaType(config.getString("Experience_Formula.Curve")); }
public boolean getCumulativeCurveEnabled() { return config.getBoolean("Experience_Formula.Cumulative_Curve", false); }
public FormulaType getFormulaType() {
return FormulaType.getFormulaType(config.getString("Experience_Formula.Curve"));
}
public boolean getCumulativeCurveEnabled() {
return config.getBoolean("Experience_Formula.Cumulative_Curve", false);
}
/* Curve values */
public double getMultiplier(FormulaType type) { return config.getDouble("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.multiplier"); }
public int getBase(FormulaType type) { return config.getInt("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.base"); }
public double getExponent(FormulaType type) { return config.getDouble("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.exponent"); }
public double getMultiplier(FormulaType type) {
return config.getDouble("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.multiplier");
}
public int getBase(FormulaType type) {
return config.getInt("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.base");
}
public double getExponent(FormulaType type) {
return config.getDouble("Experience_Formula." + StringUtils.getCapitalized(type.toString()) + "_Values.exponent");
}
/* Global modifier */
public double getExperienceGainsGlobalMultiplier() { return config.getDouble("Experience_Formula.Multiplier.Global", 1.0); }
public void setExperienceGainsGlobalMultiplier(double value) { config.set("Experience_Formula.Multiplier.Global", value); }
public double getExperienceGainsGlobalMultiplier() {
return config.getDouble("Experience_Formula.Multiplier.Global", 1.0);
}
public void setExperienceGainsGlobalMultiplier(double value) {
config.set("Experience_Formula.Multiplier.Global", value);
}
/* PVP modifier */
public double getPlayerVersusPlayerXP() { return config.getDouble("Experience_Formula.Multiplier.PVP", 1.0); }
public double getPlayerVersusPlayerXP() {
return config.getDouble("Experience_Formula.Multiplier.PVP", 1.0);
}
/* Spawned Mob modifier */
public double getSpawnedMobXpMultiplier() { return config.getDouble("Experience_Formula.Mobspawners.Multiplier", 0.0); }
public double getEggXpMultiplier() { return config.getDouble("Experience_Formula.Eggs.Multiplier", 0.0); }
public double getTamedMobXpMultiplier() { return config.getDouble("Experience_Formula.Player_Tamed.Multiplier", 0.0); }
public double getNetherPortalXpMultiplier() { return config.getDouble("Experience_Formula.Nether_Portal.Multiplier", 0.0); }
public double getBredMobXpMultiplier() { return config.getDouble("Experience_Formula.Breeding.Multiplier", 1.0); }
public double getSpawnedMobXpMultiplier() {
return config.getDouble("Experience_Formula.Mobspawners.Multiplier", 0.0);
}
public double getEggXpMultiplier() {
return config.getDouble("Experience_Formula.Eggs.Multiplier", 0.0);
}
public double getTamedMobXpMultiplier() {
return config.getDouble("Experience_Formula.Player_Tamed.Multiplier", 0.0);
}
public double getNetherPortalXpMultiplier() {
return config.getDouble("Experience_Formula.Nether_Portal.Multiplier", 0.0);
}
public double getBredMobXpMultiplier() {
return config.getDouble("Experience_Formula.Breeding.Multiplier", 1.0);
}
/* Skill modifiers */
public double getFormulaSkillModifier(PrimarySkillType skill) { return config.getDouble("Experience_Formula.Modifier." + StringUtils.getCapitalized(skill.toString())); }
public double getFormulaSkillModifier(PrimarySkillType skill) {
return config.getDouble("Experience_Formula.Modifier." + StringUtils.getCapitalized(skill.toString()));
}
/* Custom XP perk */
public double getCustomXpPerkBoost() { return config.getDouble("Experience_Formula.Custom_XP_Perk.Boost", 1.25); }
public double getCustomXpPerkBoost() {
return config.getDouble("Experience_Formula.Custom_XP_Perk.Boost", 1.25);
}
/* Diminished Returns */
public float getDiminishedReturnsCap() { return (float) config.getDouble("Dimished_Returns.Guaranteed_Minimum_Percentage", 0.05D); }
public boolean getDiminishedReturnsEnabled() { return config.getBoolean("Diminished_Returns.Enabled", false); }
public int getDiminishedReturnsThreshold(PrimarySkillType skill) { return config.getInt("Diminished_Returns.Threshold." + StringUtils.getCapitalized(skill.toString()), 20000); }
public int getDiminishedReturnsTimeInterval() { return config.getInt("Diminished_Returns.Time_Interval", 10); }
public float getDiminishedReturnsCap() {
return (float) config.getDouble("Dimished_Returns.Guaranteed_Minimum_Percentage", 0.05D);
}
public boolean getDiminishedReturnsEnabled() {
return config.getBoolean("Diminished_Returns.Enabled", false);
}
public int getDiminishedReturnsThreshold(PrimarySkillType skill) {
return config.getInt("Diminished_Returns.Threshold." + StringUtils.getCapitalized(skill.toString()), 20000);
}
public int getDiminishedReturnsTimeInterval() {
return config.getInt("Diminished_Returns.Time_Interval", 10);
}
/* Conversion */
public double getExpModifier() { return config.getDouble("Conversion.Exp_Modifier", 1); }
public double getExpModifier() {
return config.getDouble("Conversion.Exp_Modifier", 1);
}
/*
* XP SETTINGS
*/
/* General Settings */
public boolean getExperienceGainsPlayerVersusPlayerEnabled() { return config.getBoolean("Experience_Values.PVP.Rewards", true); }
public boolean getExperienceGainsPlayerVersusPlayerEnabled() {
return config.getBoolean("Experience_Values.PVP.Rewards", true);
}
/* Combat XP Multipliers */
public double getCombatXP(EntityType entity) { return config.getDouble("Experience_Values.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_")); }
public double getAnimalsXP(EntityType entity) { return config.getDouble("Experience_Values.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_"), getAnimalsXP()); }
public double getAnimalsXP() { return config.getDouble("Experience_Values.Combat.Multiplier.Animals", 1.0); }
public boolean hasCombatXP(EntityType entity) {return config.contains("Experience_Values.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_")); }
public double getCombatXP(EntityType entity) {
return config.getDouble("Experience_Values.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_"));
}
public double getAnimalsXP(EntityType entity) {
return config.getDouble("Experience_Values.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_"), getAnimalsXP());
}
public double getAnimalsXP() {
return config.getDouble("Experience_Values.Combat.Multiplier.Animals", 1.0);
}
public boolean hasCombatXP(EntityType entity) {
return config.contains("Experience_Values.Combat.Multiplier." + StringUtils.getPrettyEntityTypeString(entity).replace(" ", "_"));
}
/* Materials */
public int getXp(PrimarySkillType skill, Material material)
{
public int getXp(PrimarySkillType skill, Material material) {
//TODO: Temporary measure to fix an exploit caused by a yet to be fixed Spigot bug (as of 7/3/2020)
if(material.toString().equalsIgnoreCase("LILY_PAD"))
if (material.toString().equalsIgnoreCase("LILY_PAD"))
return 0;
String baseString = "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + ".";
@@ -231,8 +332,7 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
/* Materials */
public int getXp(PrimarySkillType skill, BlockState blockState)
{
public int getXp(PrimarySkillType skill, BlockState blockState) {
Material data = blockState.getType();
String baseString = "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + ".";
@@ -249,8 +349,7 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
/* Materials */
public int getXp(PrimarySkillType skill, Block block)
{
public int getXp(PrimarySkillType skill, Block block) {
Material data = block.getType();
String baseString = "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + ".";
@@ -267,8 +366,7 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
/* Materials */
public int getXp(PrimarySkillType skill, BlockData data)
{
public int getXp(PrimarySkillType skill, BlockData data) {
String baseString = "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + ".";
String explicitString = baseString + StringUtils.getExplicitConfigBlockDataString(data);
if (config.contains(explicitString))
@@ -282,8 +380,7 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
return 0;
}
public boolean doesBlockGiveSkillXP(PrimarySkillType skill, Material data)
{
public boolean doesBlockGiveSkillXP(PrimarySkillType skill, Material data) {
String baseString = "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + ".";
String explicitString = baseString + StringUtils.getExplicitConfigMaterialString(data);
if (config.contains(explicitString))
@@ -295,8 +392,7 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
return config.contains(wildcardString);
}
public boolean doesBlockGiveSkillXP(PrimarySkillType skill, BlockData data)
{
public boolean doesBlockGiveSkillXP(PrimarySkillType skill, BlockData data) {
String baseString = "Experience_Values." + StringUtils.getCapitalized(skill.toString()) + ".";
String explicitString = baseString + StringUtils.getExplicitConfigBlockDataString(data);
if (config.contains(explicitString))
@@ -312,47 +408,42 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
* Experience Bar Stuff
*/
public boolean isPartyExperienceBarsEnabled()
{
public boolean isPartyExperienceBarsEnabled() {
return config.getBoolean("Experience_Bars.Update.Party", true);
}
public boolean isPassiveGainsExperienceBarsEnabled()
{
public boolean isPassiveGainsExperienceBarsEnabled() {
return config.getBoolean("Experience_Bars.Update.Passive", true);
}
public boolean getDoExperienceBarsAlwaysUpdateTitle()
{
public boolean getDoExperienceBarsAlwaysUpdateTitle() {
return config.getBoolean("Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.Enable", false) || getAddExtraDetails();
}
public boolean getAddExtraDetails() { return config.getBoolean("Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.ExtraDetails", false);}
public boolean isExperienceBarsEnabled() { return config.getBoolean("Experience_Bars.Enable", true); }
public boolean isExperienceBarEnabled(PrimarySkillType primarySkillType) { return config.getBoolean("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.toString())+".Enable", true);}
public boolean isExperienceBarEnabled(@NotNull PrimarySkillType primarySkillType) { return config.getBoolean("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.getRawSkillName())+".Enable", true);}
public BarColor getExperienceBarColor(@NotNull PrimarySkillType primarySkillType)
{
String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.getRawSkillName())+".Color");
for(BarColor barColor : BarColor.values())
{
if(barColor.toString().equalsIgnoreCase(colorValueFromConfig))
return barColor;
}
//In case the value is invalid
return BarColor.WHITE;
public boolean getAddExtraDetails() {
return config.getBoolean("Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.ExtraDetails", false);
}
public boolean useCombatHPCeiling() {
return config.getBoolean("ExploitFix.Combat.XPCeiling.Enabled", true);
}
public BarColor getExperienceBarColor(PrimarySkillType primarySkillType)
{
String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.toString())+".Color");
public int getCombatHPCeiling() {
return config.getInt("ExploitFix.Combat.XPCeiling.HP_Modifier_Limit", 100);
}
for(BarColor barColor : BarColor.values())
{
if(barColor.toString().equalsIgnoreCase(colorValueFromConfig))
public boolean isExperienceBarsEnabled() {
return config.getBoolean("Experience_Bars.Enable", true);
}
public boolean isExperienceBarEnabled(PrimarySkillType primarySkillType) {
return config.getBoolean("Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + ".Enable", true);
}
public BarColor getExperienceBarColor(PrimarySkillType primarySkillType) {
String colorValueFromConfig = config.getString("Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + ".Color");
for (BarColor barColor : BarColor.values()) {
if (barColor.toString().equalsIgnoreCase(colorValueFromConfig))
return barColor;
}
@@ -361,24 +452,10 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
public BarStyle getExperienceBarStyle(PrimarySkillType primarySkillType) {
String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.toString())+".BarStyle");
String colorValueFromConfig = config.getString("Experience_Bars." + StringUtils.getCapitalized(primarySkillType.toString()) + ".BarStyle");
for(BarStyle barStyle : BarStyle.values())
{
if(barStyle.toString().equalsIgnoreCase(colorValueFromConfig))
return barStyle;
}
//In case the value is invalid
return BarStyle.SOLID;
}
public BarStyle getExperienceBarStyle(@NotNull PrimarySkillType primarySkillType) {
String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.getRawSkillName())+".BarStyle");
for(BarStyle barStyle : BarStyle.values())
{
if(barStyle.toString().equalsIgnoreCase(colorValueFromConfig))
for (BarStyle barStyle : BarStyle.values()) {
if (barStyle.toString().equalsIgnoreCase(colorValueFromConfig))
return barStyle;
}
@@ -387,29 +464,51 @@ public class ExperienceConfig extends AutoUpdateConfigLoader {
}
/* Acrobatics */
public int getDodgeXPModifier() { return config.getInt("Experience_Values.Acrobatics.Dodge", 120); }
public int getRollXPModifier() { return config.getInt("Experience_Values.Acrobatics.Roll", 80); }
public int getFallXPModifier() { return config.getInt("Experience_Values.Acrobatics.Fall", 120); }
public int getDodgeXPModifier() {
return config.getInt("Experience_Values.Acrobatics.Dodge", 120);
}
public double getFeatherFallXPModifier() { return config.getDouble("Experience_Values.Acrobatics.FeatherFall_Multiplier", 2.0); }
public int getRollXPModifier() {
return config.getInt("Experience_Values.Acrobatics.Roll", 80);
}
public int getFallXPModifier() {
return config.getInt("Experience_Values.Acrobatics.Fall", 120);
}
public double getFeatherFallXPModifier() {
return config.getDouble("Experience_Values.Acrobatics.FeatherFall_Multiplier", 2.0);
}
/* Alchemy */
public double getPotionXP(PotionStage stage) { return config.getDouble("Experience_Values.Alchemy.Potion_Stage_" + stage.toNumerical(), 10D); }
public double getPotionXP(PotionStage stage) {
return config.getDouble("Experience_Values.Alchemy.Potion_Stage_" + stage.toNumerical(), 10D);
}
/* Archery */
public double getArcheryDistanceMultiplier() { return config.getDouble("Experience_Values.Archery.Distance_Multiplier", 0.025); }
public double getArcheryDistanceMultiplier() {
return config.getDouble("Experience_Values.Archery.Distance_Multiplier", 0.025);
}
public int getFishingShakeXP() { return config.getInt("Experience_Values.Fishing.Shake", 50); }
public int getFishingShakeXP() {
return config.getInt("Experience_Values.Fishing.Shake", 50);
}
/* Repair */
public double getRepairXPBase() { return config.getDouble("Experience_Values.Repair.Base", 1000.0); }
public double getRepairXP(MaterialType repairMaterialType) { return config.getDouble("Experience_Values.Repair." + StringUtils.getCapitalized(repairMaterialType.toString())); }
public double getRepairXPBase() {
return config.getDouble("Experience_Values.Repair.Base", 1000.0);
}
public double getRepairXP(MaterialType repairMaterialType) {
return config.getDouble("Experience_Values.Repair." + StringUtils.getCapitalized(repairMaterialType.toString()));
}
/* Taming */
public int getTamingXP(EntityType type)
{
public int getTamingXP(EntityType type) {
return config.getInt("Experience_Values.Taming.Animal_Taming." + StringUtils.getPrettyEntityTypeString(type));
}
public boolean preventStoneLavaFarming() { return config.getBoolean("ExploitFix.LavaStoneAndCobbleFarming", true);}
public boolean preventStoneLavaFarming() {
return config.getBoolean("ExploitFix.LavaStoneAndCobbleFarming", true);
}
}

View File

@@ -29,7 +29,7 @@ public class ArmorConfigManager {
continue;
}
modManager.registerCustomArmor(new CustomArmorConfig(fileName));
modManager.registerCustomArmor(new CustomArmorLegacyConfig(fileName));
}
}
}

View File

@@ -29,7 +29,7 @@ public class BlockConfigManager {
continue;
}
modManager.registerCustomBlocks(new CustomBlockConfig(fileName));
modManager.registerCustomBlocks(new CustomBlockLegacyConfig(fileName));
}
}
}

View File

@@ -1,6 +1,6 @@
package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.LegacyConfigLoader;
import com.gmail.nossr50.datatypes.skills.ItemType;
import com.gmail.nossr50.datatypes.skills.MaterialType;
import com.gmail.nossr50.mcMMO;
@@ -13,17 +13,15 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class CustomArmorConfig extends ConfigLoader {
public class CustomArmorLegacyConfig extends LegacyConfigLoader {
public List<Material> customBoots = new ArrayList<>();
public List<Material> customChestplates = new ArrayList<>();
public List<Material> customHelmets = new ArrayList<>();
public List<Material> customLeggings = new ArrayList<>();
public List<Repairable> repairables = new ArrayList<>();
private boolean needsUpdate = false;
public List<Material> customBoots = new ArrayList<>();
public List<Material> customChestplates = new ArrayList<>();
public List<Material> customHelmets = new ArrayList<>();
public List<Material> customLeggings = new ArrayList<>();
public List<Repairable> repairables = new ArrayList<>();
protected CustomArmorConfig(String fileName) {
protected CustomArmorLegacyConfig(String fileName) {
super("mods", fileName);
loadKeys();
}

View File

@@ -1,6 +1,6 @@
package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.LegacyConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomBlock;
import com.gmail.nossr50.mcMMO;
import org.bukkit.Material;
@@ -11,20 +11,18 @@ import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class CustomBlockConfig extends ConfigLoader {
public class CustomBlockLegacyConfig extends LegacyConfigLoader {
public List<Material> customExcavationBlocks = new ArrayList<>();
public List<Material> customHerbalismBlocks = new ArrayList<>();
public List<Material> customMiningBlocks = new ArrayList<>();
public List<Material> customOres = new ArrayList<>();
public List<Material> customLogs = new ArrayList<>();
public List<Material> customLeaves = new ArrayList<>();
public List<Material> customAbilityBlocks = new ArrayList<>();
public HashMap<Material, CustomBlock> customBlockMap = new HashMap<>();
private boolean needsUpdate = false;
public List<Material> customExcavationBlocks = new ArrayList<>();
public List<Material> customHerbalismBlocks = new ArrayList<>();
public List<Material> customMiningBlocks = new ArrayList<>();
public List<Material> customOres = new ArrayList<>();
public List<Material> customLogs = new ArrayList<>();
public List<Material> customLeaves = new ArrayList<>();
public List<Material> customAbilityBlocks = new ArrayList<>();
public HashMap<Material, CustomBlock> customBlockMap = new HashMap<>();
protected CustomBlockConfig(String fileName) {
protected CustomBlockLegacyConfig(String fileName) {
super("mods", fileName);
loadKeys();
}
@@ -85,12 +83,10 @@ public class CustomBlockConfig extends ConfigLoader {
if (skillType.equals("Mining") && config.getBoolean(skillType + "." + blockName + ".Is_Ore")) {
customOres.add(blockMaterial);
smeltingXp = config.getInt(skillType + "." + blockName + ".Smelting_XP_Gain", xp / 10);
}
else if (skillType.equals("Woodcutting")) {
} else if (skillType.equals("Woodcutting")) {
if (config.getBoolean(skillType + "." + blockName + ".Is_Log")) {
customLogs.add(blockMaterial);
}
else {
} else {
customLeaves.add(blockMaterial);
xp = 0; // Leaves don't grant XP
}

View File

@@ -1,6 +1,6 @@
package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.LegacyConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomEntity;
import com.gmail.nossr50.mcMMO;
import org.apache.commons.lang.ClassUtils;
@@ -9,11 +9,11 @@ import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
public class CustomEntityConfig extends ConfigLoader {
public class CustomEntityLegacyConfig extends LegacyConfigLoader {
public HashMap<String, CustomEntity> customEntityClassMap = new HashMap<>();
public HashMap<String, CustomEntity> customEntityTypeMap = new HashMap<>();
public HashMap<String, CustomEntity> customEntityTypeMap = new HashMap<>();
protected CustomEntityConfig(String fileName) {
protected CustomEntityLegacyConfig(String fileName) {
super("mods", fileName);
loadKeys();
}
@@ -31,8 +31,7 @@ public class CustomEntityConfig extends ConfigLoader {
try {
clazz = ClassUtils.getClass(className);
}
catch (ClassNotFoundException e) {
} catch (ClassNotFoundException e) {
mcMMO.p.getLogger().warning("Invalid class (" + className + ") detected for " + entityName + ".");
mcMMO.p.getLogger().warning("This custom entity may not function properly.");
}

View File

@@ -1,6 +1,6 @@
package com.gmail.nossr50.config.mods;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.LegacyConfigLoader;
import com.gmail.nossr50.datatypes.mods.CustomTool;
import com.gmail.nossr50.datatypes.skills.ItemType;
import com.gmail.nossr50.datatypes.skills.MaterialType;
@@ -15,21 +15,18 @@ import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class CustomToolConfig extends ConfigLoader {
public class CustomToolLegacyConfig extends LegacyConfigLoader {
public List<Material> customAxes = new ArrayList<>();
public List<Material> customBows = new ArrayList<>();
public List<Material> customHoes = new ArrayList<>();
public List<Material> customPickaxes = new ArrayList<>();
public List<Material> customShovels = new ArrayList<>();
public List<Material> customSwords = new ArrayList<>();
public HashMap<Material, CustomTool> customToolMap = new HashMap<>();
public List<Repairable> repairables = new ArrayList<>();
private boolean needsUpdate = false;
public List<Material> customAxes = new ArrayList<>();
public List<Material> customBows = new ArrayList<>();
public List<Material> customHoes = new ArrayList<>();
public List<Material> customPickaxes = new ArrayList<>();
public List<Material> customShovels = new ArrayList<>();
public List<Material> customSwords = new ArrayList<>();
public HashMap<Material, CustomTool> customToolMap = new HashMap<>();
public List<Repairable> repairables = new ArrayList<>();
protected CustomToolConfig(String fileName) {
protected CustomToolLegacyConfig(String fileName) {
super("mods", fileName);
loadKeys();
}

View File

@@ -29,7 +29,7 @@ public class EntityConfigManager {
continue;
}
modManager.registerCustomEntities(new CustomEntityConfig(fileName));
modManager.registerCustomEntities(new CustomEntityLegacyConfig(fileName));
}
}
}

View File

@@ -29,7 +29,7 @@ public class ToolConfigManager {
continue;
}
modManager.registerCustomTools(new CustomToolConfig(fileName));
modManager.registerCustomTools(new CustomToolLegacyConfig(fileName));
}
}
}

View File

@@ -1,13 +1,13 @@
package com.gmail.nossr50.config.party;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.BukkitConfig;
import com.gmail.nossr50.util.text.StringUtils;
import org.bukkit.Material;
import java.util.HashSet;
import java.util.Locale;
public class ItemWeightConfig extends ConfigLoader {
public class ItemWeightConfig extends BukkitConfig {
private static ItemWeightConfig instance;
private ItemWeightConfig() {
@@ -40,5 +40,6 @@ public class ItemWeightConfig extends ConfigLoader {
}
@Override
protected void loadKeys() {}
protected void loadKeys() {
}
}

View File

@@ -1,8 +1,9 @@
package com.gmail.nossr50.config.skills.alchemy;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.LegacyConfigLoader;
import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
@@ -15,7 +16,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PotionConfig extends ConfigLoader {
public class PotionConfig extends LegacyConfigLoader {
private static PotionConfig instance;
private final List<ItemStack> concoctionsIngredientsTierOne = new ArrayList<>();
@@ -95,13 +96,12 @@ public class PotionConfig extends ConfigLoader {
if (potion != null) {
potionMap.put(potionName, potion);
pass++;
}
else {
} else {
fail++;
}
}
mcMMO.p.getLogger().info("Loaded " + pass + " Alchemy potions, skipped " + fail + ".");
LogUtils.debug(mcMMO.p.getLogger(), "Loaded " + pass + " Alchemy potions, skipped " + fail + ".");
}
/**
@@ -114,13 +114,13 @@ public class PotionConfig extends ConfigLoader {
*/
private AlchemyPotion loadPotion(ConfigurationSection potion_section) {
try {
String name = potion_section.getString("Name");
if (name != null) {
name = ChatColor.translateAlternateColorCodes('&', name);
}
PotionData data;
if (!potion_section.contains("PotionData")) { // Backwards config compatability
short dataValue = Short.parseShort(potion_section.getName());
@@ -130,7 +130,7 @@ public class PotionConfig extends ConfigLoader {
ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData");
data = new PotionData(PotionType.valueOf(potionData.getString("PotionType", "WATER")), potionData.getBoolean("Extended", false), potionData.getBoolean("Upgraded", false));
}
Material material = Material.POTION;
String mat = potion_section.getString("Material", null);
if (mat != null) {
@@ -155,18 +155,16 @@ public class PotionConfig extends ConfigLoader {
if (type != null) {
effects.add(new PotionEffect(type, duration, amplifier));
}
else {
} else {
mcMMO.p.getLogger().warning("Failed to parse effect for potion " + name + ": " + effect);
}
}
}
Color color;
if (potion_section.contains("Color")) {
color = Color.fromRGB(potion_section.getInt("Color"));
}
else {
} else {
color = this.generateColor(effects);
}
@@ -176,16 +174,14 @@ public class PotionConfig extends ConfigLoader {
ItemStack ingredient = loadIngredient(child);
if (ingredient != null) {
children.put(ingredient, potion_section.getConfigurationSection("Children").getString(child));
}
else {
} else {
mcMMO.p.getLogger().warning("Failed to parse child for potion " + name + ": " + child);
}
}
}
return new AlchemyPotion(material, data, name, lore, effects, color, children);
}
catch (Exception e) {
} catch (Exception e) {
mcMMO.p.getLogger().warning("Failed to load Alchemy potion: " + potion_section.getName());
return null;
}
@@ -243,7 +239,7 @@ public class PotionConfig extends ConfigLoader {
public AlchemyPotion getPotion(String name) {
return potionMap.get(name);
}
public AlchemyPotion getPotion(ItemStack item) {
for (AlchemyPotion potion : potionMap.values()) {
if (potion.isSimilar(item)) {
@@ -252,7 +248,7 @@ public class PotionConfig extends ConfigLoader {
}
return null;
}
public Color generateColor(List<PotionEffect> effects) {
if (effects != null && !effects.isEmpty()) {
List<Color> colors = new ArrayList<>();
@@ -270,7 +266,7 @@ public class PotionConfig extends ConfigLoader {
}
return null;
}
public Color calculateAverageColor(List<Color> colors) {
int red = 0;
int green = 0;
@@ -280,7 +276,7 @@ public class PotionConfig extends ConfigLoader {
green += color.getGreen();
blue += color.getBlue();
}
return Color.fromRGB(red/colors.size(), green/colors.size(), blue/colors.size());
return Color.fromRGB(red / colors.size(), green / colors.size(), blue / colors.size());
}
}

View File

@@ -1,24 +1,25 @@
package com.gmail.nossr50.config.skills.repair;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.BukkitConfig;
import com.gmail.nossr50.datatypes.skills.ItemType;
import com.gmail.nossr50.datatypes.skills.MaterialType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.repair.repairables.Repairable;
import com.gmail.nossr50.skills.repair.repairables.RepairableFactory;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.LogUtils;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import java.util.*;
public class RepairConfig extends ConfigLoader {
private List<Repairable> repairables;
public class RepairConfig extends BukkitConfig {
private final HashSet<String> notSupported;
private List<Repairable> repairables;
public RepairConfig(String fileName) {
super(fileName);
public RepairConfig(String fileName, boolean copyDefaults) {
super(fileName, copyDefaults);
notSupported = new HashSet<>();
loadKeys();
}
@@ -48,7 +49,7 @@ public class RepairConfig extends ConfigLoader {
Material itemMaterial = Material.matchMaterial(key);
if (itemMaterial == null) {
//mcMMO.p.getLogger().info("No support for repair item "+key+ " in this version of Minecraft, skipping.");
//LogUtils.debug(mcMMO.p.getLogger(), "No support for repair item "+key+ " in this version of Minecraft, skipping.");
notSupported.add(key); //Collect names of unsupported items
continue;
}
@@ -62,33 +63,25 @@ public class RepairConfig extends ConfigLoader {
if (ItemUtils.isWoodTool(repairItem)) {
repairMaterialType = MaterialType.WOOD;
}
else if (ItemUtils.isStoneTool(repairItem)) {
} else if (ItemUtils.isStoneTool(repairItem)) {
repairMaterialType = MaterialType.STONE;
}
else if (ItemUtils.isStringTool(repairItem)) {
} else if (ItemUtils.isStringTool(repairItem)) {
repairMaterialType = MaterialType.STRING;
}
else if (ItemUtils.isLeatherArmor(repairItem)) {
} else if (ItemUtils.isLeatherArmor(repairItem)) {
repairMaterialType = MaterialType.LEATHER;
}
else if (ItemUtils.isIronArmor(repairItem) || ItemUtils.isIronTool(repairItem)) {
} else if (ItemUtils.isIronArmor(repairItem) || ItemUtils.isIronTool(repairItem)) {
repairMaterialType = MaterialType.IRON;
}
else if (ItemUtils.isGoldArmor(repairItem) || ItemUtils.isGoldTool(repairItem)) {
} else if (ItemUtils.isGoldArmor(repairItem) || ItemUtils.isGoldTool(repairItem)) {
repairMaterialType = MaterialType.GOLD;
}
else if (ItemUtils.isDiamondArmor(repairItem) || ItemUtils.isDiamondTool(repairItem)) {
} else if (ItemUtils.isDiamondArmor(repairItem) || ItemUtils.isDiamondTool(repairItem)) {
repairMaterialType = MaterialType.DIAMOND;
} else if (ItemUtils.isNetheriteArmor(repairItem) || ItemUtils.isNetheriteTool(repairItem)) {
repairMaterialType = MaterialType.NETHERITE;
}
}
else {
} else {
try {
repairMaterialType = MaterialType.valueOf(repairMaterialTypeString);
}
catch (IllegalArgumentException ex) {
} catch (IllegalArgumentException ex) {
reason.add(key + " has an invalid MaterialType of " + repairMaterialTypeString);
}
}
@@ -122,16 +115,13 @@ public class RepairConfig extends ConfigLoader {
if (ItemUtils.isMinecraftTool(repairItem)) {
repairItemType = ItemType.TOOL;
}
else if (ItemUtils.isArmor(repairItem)) {
} else if (ItemUtils.isArmor(repairItem)) {
repairItemType = ItemType.ARMOR;
}
}
else {
} else {
try {
repairItemType = ItemType.valueOf(repairItemTypeString);
}
catch (IllegalArgumentException ex) {
} catch (IllegalArgumentException ex) {
reason.add(key + " has an invalid ItemType of " + repairItemTypeString);
}
}
@@ -146,7 +136,7 @@ public class RepairConfig extends ConfigLoader {
// Minimum Quantity
int minimumQuantity = config.getInt("Repairables." + key + ".MinimumQuantity");
if(minimumQuantity == 0) {
if (minimumQuantity == 0) {
minimumQuantity = -1;
}
@@ -158,21 +148,21 @@ public class RepairConfig extends ConfigLoader {
//Report unsupported
StringBuilder stringBuilder = new StringBuilder();
if(notSupported.size() > 0) {
if (notSupported.size() > 0) {
stringBuilder.append("mcMMO found the following materials in the Repair config that are not supported by the version of Minecraft running on this server: ");
for (Iterator<String> iterator = notSupported.iterator(); iterator.hasNext(); ) {
String unsupportedMaterial = iterator.next();
if(!iterator.hasNext()) {
if (!iterator.hasNext()) {
stringBuilder.append(unsupportedMaterial);
} else {
stringBuilder.append(unsupportedMaterial).append(", ");
}
}
mcMMO.p.getLogger().info(stringBuilder.toString());
mcMMO.p.getLogger().info("Items using materials that are not supported will simply be skipped.");
LogUtils.debug(mcMMO.p.getLogger(), stringBuilder.toString());
LogUtils.debug(mcMMO.p.getLogger(), "Items using materials that are not supported will simply be skipped.");
}
}

View File

@@ -1,28 +1,28 @@
package com.gmail.nossr50.config.skills.repair;
import com.gmail.nossr50.datatypes.database.UpgradeType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.repair.repairables.Repairable;
import com.gmail.nossr50.util.FixSpellingNetheriteUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import java.util.HashSet;
import java.util.regex.Pattern;
public class RepairConfigManager {
private final List<Repairable> repairables = new ArrayList<>();
public static final String REPAIR_VANILLA_YML = "repair.vanilla.yml";
private static final Collection<Repairable> repairables = new HashSet<>();
public RepairConfigManager(mcMMO plugin) {
Pattern pattern = Pattern.compile("repair\\.(?:.+)\\.yml");
File dataFolder = plugin.getDataFolder();
File vanilla = new File(dataFolder, "repair.vanilla.yml");
if (!vanilla.exists()) {
plugin.saveResource("repair.vanilla.yml", false);
}
RepairConfig mainRepairConfig = new RepairConfig(REPAIR_VANILLA_YML, true);
repairables.addAll(mainRepairConfig.getLoadedRepairables());
for (String fileName : dataFolder.list()) {
if(fileName.equals(REPAIR_VANILLA_YML))
continue;
if (!pattern.matcher(fileName).matches()) {
continue;
}
@@ -33,19 +33,12 @@ public class RepairConfigManager {
continue;
}
if(mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.FIX_SPELLING_NETHERITE_REPAIR)) {
//Check spelling mistakes (early versions of 1.16 support had Netherite misspelled)
plugin.getLogger().info("Checking for certain invalid material names in Repair config...");
FixSpellingNetheriteUtil.processFileCheck(mcMMO.p, fileName, UpgradeType.FIX_SPELLING_NETHERITE_REPAIR);
}
RepairConfig rConfig = new RepairConfig(fileName);
RepairConfig rConfig = new RepairConfig(fileName, false);
repairables.addAll(rConfig.getLoadedRepairables());
}
}
public List<Repairable> getLoadedRepairables() {
public Collection<Repairable> getLoadedRepairables() {
return repairables;
}
}

View File

@@ -1,6 +1,6 @@
package com.gmail.nossr50.config.skills.salvage;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.BukkitConfig;
import com.gmail.nossr50.datatypes.database.UpgradeType;
import com.gmail.nossr50.datatypes.skills.ItemType;
import com.gmail.nossr50.datatypes.skills.MaterialType;
@@ -8,6 +8,7 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.salvage.salvageables.Salvageable;
import com.gmail.nossr50.skills.salvage.salvageables.SalvageableFactory;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.LogUtils;
import com.gmail.nossr50.util.skills.SkillUtils;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
@@ -15,20 +16,21 @@ import org.bukkit.inventory.ItemStack;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
public class SalvageConfig extends ConfigLoader {
private List<Salvageable> salvageables;
public class SalvageConfig extends BukkitConfig {
private final HashSet<String> notSupported;
private Set<Salvageable> salvageables;
public SalvageConfig(String fileName) {
super(fileName);
public SalvageConfig(String fileName, boolean copyDefaults) {
super(fileName, copyDefaults);
notSupported = new HashSet<>();
loadKeys();
}
@Override
protected void loadKeys() {
salvageables = new ArrayList<>();
salvageables = new HashSet<>();
if (!config.isConfigurationSection("Salvageables")) {
mcMMO.p.getLogger().severe("Could not find Salvageables section in " + fileName);
@@ -40,18 +42,18 @@ public class SalvageConfig extends ConfigLoader {
//Original version of 1.16 support had maximum quantities that were bad, this fixes it
if(mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.FIX_NETHERITE_SALVAGE_QUANTITIES)) {
mcMMO.p.getLogger().info("Fixing incorrect Salvage quantities on Netherite gear, this will only run once...");
for(String namespacedkey : mcMMO.getMaterialMapStore().getNetheriteArmor()) {
if (mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.FIX_NETHERITE_SALVAGE_QUANTITIES)) {
mcMMO.p.getLogger().log(Level.INFO, "Fixing incorrect Salvage quantities on Netherite gear, this will only run once...");
for (String namespacedkey : mcMMO.getMaterialMapStore().getNetheriteArmor()) {
config.set("Salvageables." + namespacedkey.toUpperCase() + ".MaximumQuantity", 4); //TODO: Doesn't make sense to default to 4 for everything
}
try {
config.save(getFile());
mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.FIX_NETHERITE_SALVAGE_QUANTITIES);
mcMMO.p.getLogger().info("Fixed incorrect Salvage quantities for Netherite gear!");
LogUtils.debug(mcMMO.p.getLogger(), "Fixed incorrect Salvage quantities for Netherite gear!");
} catch (IOException e) {
mcMMO.p.getLogger().info("Unable to fix Salvage config, please delete the salvage yml file to generate a new one.");
LogUtils.debug(mcMMO.p.getLogger(), "Unable to fix Salvage config, please delete the salvage yml file to generate a new one.");
e.printStackTrace();
}
}
@@ -78,33 +80,25 @@ public class SalvageConfig extends ConfigLoader {
if (ItemUtils.isWoodTool(salvageItem)) {
salvageMaterialType = MaterialType.WOOD;
}
else if (ItemUtils.isStoneTool(salvageItem)) {
} else if (ItemUtils.isStoneTool(salvageItem)) {
salvageMaterialType = MaterialType.STONE;
}
else if (ItemUtils.isStringTool(salvageItem)) {
} else if (ItemUtils.isStringTool(salvageItem)) {
salvageMaterialType = MaterialType.STRING;
}
else if (ItemUtils.isLeatherArmor(salvageItem)) {
} else if (ItemUtils.isLeatherArmor(salvageItem)) {
salvageMaterialType = MaterialType.LEATHER;
}
else if (ItemUtils.isIronArmor(salvageItem) || ItemUtils.isIronTool(salvageItem)) {
} else if (ItemUtils.isIronArmor(salvageItem) || ItemUtils.isIronTool(salvageItem)) {
salvageMaterialType = MaterialType.IRON;
}
else if (ItemUtils.isGoldArmor(salvageItem) || ItemUtils.isGoldTool(salvageItem)) {
} else if (ItemUtils.isGoldArmor(salvageItem) || ItemUtils.isGoldTool(salvageItem)) {
salvageMaterialType = MaterialType.GOLD;
}
else if (ItemUtils.isDiamondArmor(salvageItem) || ItemUtils.isDiamondTool(salvageItem)) {
} else if (ItemUtils.isDiamondArmor(salvageItem) || ItemUtils.isDiamondTool(salvageItem)) {
salvageMaterialType = MaterialType.DIAMOND;
} else if (ItemUtils.isNetheriteTool(salvageItem) || ItemUtils.isNetheriteArmor(salvageItem)) {
salvageMaterialType = MaterialType.NETHERITE;
}
}
else {
} else {
try {
salvageMaterialType = MaterialType.valueOf(salvageMaterialTypeString.replace(" ", "_").toUpperCase(Locale.ENGLISH));
}
catch (IllegalArgumentException ex) {
} catch (IllegalArgumentException ex) {
reason.add(key + " has an invalid MaterialType of " + salvageMaterialTypeString);
}
}
@@ -130,16 +124,13 @@ public class SalvageConfig extends ConfigLoader {
if (ItemUtils.isMinecraftTool(salvageItem)) {
salvageItemType = ItemType.TOOL;
}
else if (ItemUtils.isArmor(salvageItem)) {
} else if (ItemUtils.isArmor(salvageItem)) {
salvageItemType = ItemType.ARMOR;
}
}
else {
} else {
try {
salvageItemType = ItemType.valueOf(salvageItemTypeString.replace(" ", "_").toUpperCase(Locale.ENGLISH));
}
catch (IllegalArgumentException ex) {
} catch (IllegalArgumentException ex) {
reason.add(key + " has an invalid ItemType of " + salvageItemTypeString);
}
}
@@ -176,26 +167,26 @@ public class SalvageConfig extends ConfigLoader {
//Report unsupported
StringBuilder stringBuilder = new StringBuilder();
if(notSupported.size() > 0) {
if (notSupported.size() > 0) {
stringBuilder.append("mcMMO found the following materials in the Salvage config that are not supported by the version of Minecraft running on this server: ");
for (Iterator<String> iterator = notSupported.iterator(); iterator.hasNext(); ) {
String unsupportedMaterial = iterator.next();
if(!iterator.hasNext()) {
if (!iterator.hasNext()) {
stringBuilder.append(unsupportedMaterial);
} else {
stringBuilder.append(unsupportedMaterial).append(", ");
}
}
mcMMO.p.getLogger().info(stringBuilder.toString());
mcMMO.p.getLogger().info("Items using materials that are not supported will simply be skipped.");
LogUtils.debug(mcMMO.p.getLogger(), stringBuilder.toString());
LogUtils.debug(mcMMO.p.getLogger(), "Items using materials that are not supported will simply be skipped.");
}
}
protected List<Salvageable> getLoadedSalvageables() {
return salvageables == null ? new ArrayList<>() : salvageables;
protected Collection<Salvageable> getLoadedSalvageables() {
return salvageables == null ? new HashSet<>() : salvageables;
}
private boolean noErrorsInSalvageable(List<String> issues) {

View File

@@ -1,9 +1,7 @@
package com.gmail.nossr50.config.skills.salvage;
import com.gmail.nossr50.datatypes.database.UpgradeType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.salvage.salvageables.Salvageable;
import com.gmail.nossr50.util.FixSpellingNetheriteUtil;
import java.io.File;
import java.util.ArrayList;
@@ -11,18 +9,21 @@ import java.util.List;
import java.util.regex.Pattern;
public class SalvageConfigManager {
private final List<Salvageable> salvageables = new ArrayList<>();
public static final String SALVAGE_VANILLA_YML = "salvage.vanilla.yml";
private final List<Salvageable> salvageables = new ArrayList<>(); //TODO: Collision checking, make the list a set
public SalvageConfigManager(mcMMO plugin) {
Pattern pattern = Pattern.compile("salvage\\.(?:.+)\\.yml");
File dataFolder = plugin.getDataFolder();
File vanilla = new File(dataFolder, "salvage.vanilla.yml");
if (!vanilla.exists()) {
plugin.saveResource("salvage.vanilla.yml", false);
}
SalvageConfig mainSalvageConfig = new SalvageConfig(SALVAGE_VANILLA_YML, true);
salvageables.addAll(mainSalvageConfig.getLoadedSalvageables());
for (String fileName : dataFolder.list()) {
if(fileName.equals(SALVAGE_VANILLA_YML))
continue;
if (!pattern.matcher(fileName).matches()) {
continue;
}
@@ -33,20 +34,12 @@ public class SalvageConfigManager {
continue;
}
if(mcMMO.getUpgradeManager().shouldUpgrade(UpgradeType.FIX_SPELLING_NETHERITE_SALVAGE)) {
//Check spelling mistakes (early versions of 1.16 support had Netherite misspelled)
plugin.getLogger().info("Checking for certain invalid material names in Salvage config...");
FixSpellingNetheriteUtil.processFileCheck(mcMMO.p, fileName, UpgradeType.FIX_SPELLING_NETHERITE_SALVAGE);
}
SalvageConfig salvageConfig = new SalvageConfig(fileName);
SalvageConfig salvageConfig = new SalvageConfig(fileName, false);
salvageables.addAll(salvageConfig.getLoadedSalvageables());
}
}
public List<Salvageable> getLoadedSalvageables() {
return salvageables;
return new ArrayList<>(salvageables);
}
}

View File

@@ -1,9 +1,10 @@
package com.gmail.nossr50.config.treasure;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.BukkitConfig;
import com.gmail.nossr50.datatypes.treasure.*;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.EnchantmentUtils;
import com.gmail.nossr50.util.LogUtils;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
@@ -18,17 +19,17 @@ import org.jetbrains.annotations.NotNull;
import java.util.*;
public class FishingTreasureConfig extends ConfigLoader {
public class FishingTreasureConfig extends BukkitConfig {
public static final String FILENAME = "fishing_treasures.yml";
private static FishingTreasureConfig instance;
public @NotNull HashMap<Rarity, List<FishingTreasure>> fishingRewards = new HashMap<>();
public @NotNull HashMap<Rarity, List<FishingTreasure>> fishingRewards = new HashMap<>();
public @NotNull HashMap<Rarity, List<EnchantmentTreasure>> fishingEnchantments = new HashMap<>();
public @NotNull HashMap<EntityType, List<ShakeTreasure>> shakeMap = new HashMap<>();
public @NotNull HashMap<EntityType, List<ShakeTreasure>> shakeMap = new HashMap<>();
private FishingTreasureConfig() {
super(FILENAME);
super(FILENAME, false);
loadKeys();
validate();
}
@@ -45,33 +46,39 @@ public class FishingTreasureConfig extends ConfigLoader {
protected boolean validateKeys() {
// Validate all the settings!
List<String> reason = new ArrayList<>();
for (String tier : config.getConfigurationSection("Enchantment_Drop_Rates").getKeys(false)) {
double totalEnchantDropRate = 0;
double totalItemDropRate = 0;
ConfigurationSection enchantment_drop_rates = config.getConfigurationSection("Enchantment_Drop_Rates");
for (Rarity rarity : Rarity.values()) {
double enchantDropRate = config.getDouble("Enchantment_Drop_Rates." + tier + "." + rarity.toString());
double itemDropRate = config.getDouble("Item_Drop_Rates." + tier + "." + rarity.toString());
if(enchantment_drop_rates != null) {
for (String tier : enchantment_drop_rates.getKeys(false)) {
double totalEnchantDropRate = 0;
double totalItemDropRate = 0;
if ((enchantDropRate < 0.0 || enchantDropRate > 100.0)) {
reason.add("The enchant drop rate for " + tier + " items that are " + rarity.toString() + "should be between 0.0 and 100.0!");
for (Rarity rarity : Rarity.values()) {
double enchantDropRate = config.getDouble("Enchantment_Drop_Rates." + tier + "." + rarity.toString());
double itemDropRate = config.getDouble("Item_Drop_Rates." + tier + "." + rarity);
if ((enchantDropRate < 0.0 || enchantDropRate > 100.0)) {
reason.add("The enchant drop rate for " + tier + " items that are " + rarity + "should be between 0.0 and 100.0!");
}
if (itemDropRate < 0.0 || itemDropRate > 100.0) {
reason.add("The item drop rate for " + tier + " items that are " + rarity + "should be between 0.0 and 100.0!");
}
totalEnchantDropRate += enchantDropRate;
totalItemDropRate += itemDropRate;
}
if (itemDropRate < 0.0 || itemDropRate > 100.0) {
reason.add("The item drop rate for " + tier + " items that are " + rarity.toString() + "should be between 0.0 and 100.0!");
if (totalEnchantDropRate < 0 || totalEnchantDropRate > 100.0) {
reason.add("The total enchant drop rate for " + tier + " should be between 0.0 and 100.0!");
}
totalEnchantDropRate += enchantDropRate;
totalItemDropRate += itemDropRate;
}
if (totalEnchantDropRate < 0 || totalEnchantDropRate > 100.0) {
reason.add("The total enchant drop rate for " + tier + " should be between 0.0 and 100.0!");
}
if (totalItemDropRate < 0 || totalItemDropRate > 100.0) {
reason.add("The total item drop rate for " + tier + " should be between 0.0 and 100.0!");
if (totalItemDropRate < 0 || totalItemDropRate > 100.0) {
reason.add("The total item drop rate for " + tier + " should be between 0.0 and 100.0!");
}
}
} else {
mcMMO.p.getLogger().warning("Your fishing treasures config is empty, is this intentional? Delete it to regenerate.");
}
return noErrorsInConfig(reason);
@@ -89,7 +96,7 @@ public class FishingTreasureConfig extends ConfigLoader {
for (EntityType entity : EntityType.values()) {
if (entity.isAlive()) {
loadTreasures("Shake." + entity.toString());
loadTreasures("Shake." + entity);
}
}
}
@@ -175,7 +182,7 @@ public class FishingTreasureConfig extends ConfigLoader {
if (isFishing) {
String rarityStr = config.getString(type + "." + treasureName + ".Rarity");
if(rarityStr != null) {
if (rarityStr != null) {
rarity = Rarity.getRarity(rarityStr);
} else {
mcMMO.p.getLogger().severe("Please edit your config and add a Rarity definition for - " + treasureName);
@@ -192,7 +199,7 @@ public class FishingTreasureConfig extends ConfigLoader {
String customName = null;
if(hasCustomName(type, treasureName)) {
if (hasCustomName(type, treasureName)) {
customName = config.getString(type + "." + treasureName + ".Custom_Name");
}
@@ -204,7 +211,7 @@ public class FishingTreasureConfig extends ConfigLoader {
item = new ItemStack(mat, amount, data);
PotionMeta itemMeta = (PotionMeta) item.getItemMeta();
if(itemMeta == null) {
if (itemMeta == null) {
mcMMO.p.getLogger().severe("Item meta when adding potion to fishing treasure was null, contact the mcMMO devs!");
continue;
}
@@ -232,7 +239,7 @@ public class FishingTreasureConfig extends ConfigLoader {
}
item.setItemMeta(itemMeta);
}
} else if(material == Material.ENCHANTED_BOOK) {
} else if (material == Material.ENCHANTED_BOOK) {
//If any whitelisted enchants exist we use whitelist-based matching
item = new ItemStack(material, 1);
ItemMeta itemMeta = item.getItemMeta();
@@ -276,7 +283,6 @@ public class FishingTreasureConfig extends ConfigLoader {
}
if (noErrorsInConfig(reason)) {
if (isFishing) {
addFishingTreasure(rarity, new FishingTreasure(item, xp));
@@ -307,26 +313,27 @@ public class FishingTreasureConfig extends ConfigLoader {
/**
* Matches enchantments on a list (user provided string) to known enchantments in the Spigot API
* Any matches are added to the passed set
*
* @param enchantListStr the users string list of enchantments
* @param permissiveList the permissive list of enchantments
*/
private void matchAndFillSet(@NotNull List<String> enchantListStr, @NotNull Set<Enchantment> permissiveList) {
if(enchantListStr.isEmpty()) {
if (enchantListStr.isEmpty()) {
return;
}
for(String str : enchantListStr) {
for (String str : enchantListStr) {
boolean foundMatch = false;
for(Enchantment enchantment : Enchantment.values()) {
if(enchantment.getKey().getKey().equalsIgnoreCase(str)) {
for (Enchantment enchantment : Enchantment.values()) {
if (enchantment.getKey().getKey().equalsIgnoreCase(str)) {
permissiveList.add(enchantment);
foundMatch = true;
break;
}
}
if(!foundMatch) {
mcMMO.p.getLogger().info("[Fishing Treasure Init] Could not find any enchantments which matched the user defined enchantment named: "+str);
if (!foundMatch) {
LogUtils.debug(mcMMO.p.getLogger(), "[Fishing Treasure Init] Could not find any enchantments which matched the user defined enchantment named: " + str);
}
}
}
@@ -344,7 +351,7 @@ public class FishingTreasureConfig extends ConfigLoader {
}
for (String enchantmentName : enchantmentSection.getKeys(false)) {
int level = config.getInt("Enchantments_Rarity." + rarity.toString() + "." + enchantmentName);
int level = config.getInt("Enchantments_Rarity." + rarity + "." + enchantmentName);
Enchantment enchantment = EnchantmentUtils.getByName(enchantmentName);
if (enchantment == null) {
@@ -374,10 +381,10 @@ public class FishingTreasureConfig extends ConfigLoader {
}
public double getItemDropRate(int tier, @NotNull Rarity rarity) {
return config.getDouble("Item_Drop_Rates.Tier_" + tier + "." + rarity.toString());
return config.getDouble("Item_Drop_Rates.Tier_" + tier + "." + rarity);
}
public double getEnchantmentDropRate(int tier, @NotNull Rarity rarity) {
return config.getDouble("Enchantment_Drop_Rates.Tier_" + tier + "." + rarity.toString());
return config.getDouble("Enchantment_Drop_Rates.Tier_" + tier + "." + rarity);
}
}

View File

@@ -1,9 +1,10 @@
package com.gmail.nossr50.config.treasure;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.BukkitConfig;
import com.gmail.nossr50.datatypes.treasure.ExcavationTreasure;
import com.gmail.nossr50.datatypes.treasure.HylianTreasure;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import com.gmail.nossr50.util.text.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.Material;
@@ -20,7 +21,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class TreasureConfig extends ConfigLoader {
public class TreasureConfig extends BukkitConfig {
public static final String FILENAME = "treasures.yml";
public static final String LEVEL_REQUIREMENT_RETRO_MODE = ".Level_Requirement.Retro_Mode";
@@ -32,10 +33,10 @@ public class TreasureConfig extends ConfigLoader {
private static TreasureConfig instance;
public HashMap<String, List<ExcavationTreasure>> excavationMap = new HashMap<>();
public HashMap<String, List<HylianTreasure>> hylianMap = new HashMap<>();
public HashMap<String, List<HylianTreasure>> hylianMap = new HashMap<>();
private TreasureConfig() {
super(FILENAME);
super(FILENAME, false);
loadKeys();
validate();
}
@@ -115,32 +116,32 @@ public class TreasureConfig extends ConfigLoader {
DropLevelKeyConversionType conversionType;
//Check for legacy drop level values and convert
if(getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.LEGACY) != -1) {
if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.LEGACY) != -1) {
//Legacy Drop level, needs to be converted
shouldWeUpdateFile = processAutomaticKeyConversion(type, shouldWeUpdateFile, treasureName, DropLevelKeyConversionType.LEGACY);
}
//Check for a bad key that was accidentally shipped out to some users
if(getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_STANDARD) != -1) {
if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_STANDARD) != -1) {
//Partially converted to the new system, I had a dyslexic moment so some configs have this
shouldWeUpdateFile = processAutomaticKeyConversion(type, shouldWeUpdateFile, treasureName, DropLevelKeyConversionType.WRONG_KEY_STANDARD);
}
//Check for a bad key that was accidentally shipped out to some users
if(getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_RETRO) != -1) {
if (getWrongKeyValue(type, treasureName, DropLevelKeyConversionType.WRONG_KEY_RETRO) != -1) {
//Partially converted to the new system, I had a dyslexic moment so some configs have this
shouldWeUpdateFile = processAutomaticKeyConversion(type, shouldWeUpdateFile, treasureName, DropLevelKeyConversionType.WRONG_KEY_RETRO);
}
int dropLevel = -1;
if(mcMMO.isRetroModeEnabled()) {
if (mcMMO.isRetroModeEnabled()) {
dropLevel = config.getInt(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, -1);
} else {
dropLevel = config.getInt(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, -1);
}
if(dropLevel == -1) {
if (dropLevel == -1) {
mcMMO.p.getLogger().severe("Could not find a Level_Requirement entry for treasure " + treasureName);
mcMMO.p.getLogger().severe("Skipping treasure");
continue;
@@ -258,7 +259,7 @@ public class TreasureConfig extends ConfigLoader {
}
//Apply our fix
if(shouldWeUpdateFile) {
if (shouldWeUpdateFile) {
try {
config.save(getFile());
} catch (IOException e) {
@@ -272,18 +273,18 @@ public class TreasureConfig extends ConfigLoader {
case LEGACY:
int legacyDropLevel = getWrongKeyValue(type, treasureName, conversionType); //Legacy only had one value, Retro Mode didn't have a setting
//Config needs to be updated to be more specific
mcMMO.p.getLogger().info("(" + treasureName + ") [Fixing bad address: Legacy] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format");
LogUtils.debug(mcMMO.p.getLogger(), "(" + treasureName + ") [Fixing bad address: Legacy] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format");
config.set(type + "." + treasureName + LEGACY_DROP_LEVEL, null); //Remove legacy entry
config.set(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, legacyDropLevel * 10); //Multiply by 10 for Retro
config.set(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, legacyDropLevel);
shouldWeUpdateTheFile = true;
break;
case WRONG_KEY_STANDARD:
mcMMO.p.getLogger().info("(" + treasureName + ") [Fixing bad address: STANDARD] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format");
LogUtils.debug(mcMMO.p.getLogger(), "(" + treasureName + ") [Fixing bad address: STANDARD] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format");
int wrongKeyValueStandard = getWrongKeyValue(type, treasureName, conversionType);
config.set(type + "." + treasureName + WRONG_KEY_ROOT, null); //We also kill the Retro key here as we have enough information for setting in values if needed
if(wrongKeyValueStandard != -1) {
if (wrongKeyValueStandard != -1) {
config.set(type + "." + treasureName + LEVEL_REQUIREMENT_STANDARD_MODE, wrongKeyValueStandard);
config.set(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, wrongKeyValueStandard * 10); //Multiply by 10 for Retro
}
@@ -291,11 +292,11 @@ public class TreasureConfig extends ConfigLoader {
shouldWeUpdateTheFile = true;
break;
case WRONG_KEY_RETRO:
mcMMO.p.getLogger().info("(" + treasureName + ") [Fixing bad address: RETRO] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format");
LogUtils.debug(mcMMO.p.getLogger(), "(" + treasureName + ") [Fixing bad address: RETRO] Converting Drop_Level to Level_Requirement in treasures.yml for treasure to match new expected format");
int wrongKeyValueRetro = getWrongKeyValue(type, treasureName, conversionType);
config.set(type + "." + treasureName + WRONG_KEY_ROOT, null); //We also kill the Retro key here as we have enough information for setting in values if needed
if(wrongKeyValueRetro != -1) {
if (wrongKeyValueRetro != -1) {
config.set(type + "." + treasureName + LEVEL_REQUIREMENT_RETRO_MODE, wrongKeyValueRetro);
}
@@ -306,22 +307,12 @@ public class TreasureConfig extends ConfigLoader {
}
private int getWrongKeyValue(String type, String treasureName, DropLevelKeyConversionType dropLevelKeyConversionType) {
switch (dropLevelKeyConversionType) {
case LEGACY:
return config.getInt(type + "." + treasureName + LEGACY_DROP_LEVEL, -1);
case WRONG_KEY_STANDARD:
return config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_STANDARD, -1);
case WRONG_KEY_RETRO:
return config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_RETRO, -1);
}
return switch (dropLevelKeyConversionType) {
case LEGACY -> config.getInt(type + "." + treasureName + LEGACY_DROP_LEVEL, -1);
case WRONG_KEY_STANDARD -> config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_STANDARD, -1);
case WRONG_KEY_RETRO -> config.getInt(type + "." + treasureName + WRONG_KEY_VALUE_RETRO, -1);
};
return -1;
}
private enum DropLevelKeyConversionType {
LEGACY,
WRONG_KEY_STANDARD,
WRONG_KEY_RETRO
}
private void AddHylianTreasure(String dropper, HylianTreasure treasure) {
@@ -329,4 +320,10 @@ public class TreasureConfig extends ConfigLoader {
hylianMap.put(dropper, new ArrayList<>());
hylianMap.get(dropper).add(treasure);
}
private enum DropLevelKeyConversionType {
LEGACY,
WRONG_KEY_STANDARD,
WRONG_KEY_RETRO
}
}

View File

@@ -3,8 +3,6 @@ package com.gmail.nossr50.database;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.datatypes.database.DatabaseType;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.MMODataSnapshot;
import com.gmail.nossr50.datatypes.player.PlayerData;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import org.bukkit.OfflinePlayer;
@@ -49,17 +47,10 @@ public interface DatabaseManager {
/**
* Save a user to the database.
*
* @param playerData target player data
* @param profile The profile of the player to save
* @return true if successful, false on failure
*/
boolean saveUser(@NotNull PlayerData playerData);
/**
*
* @param dataSnapshot target data snapshot
* @return true if successful, false on failure
*/
boolean saveUser(@NotNull MMODataSnapshot dataSnapshot);
boolean saveUser(PlayerProfile profile);
/**
* Retrieve leaderboard info.

View File

@@ -2,6 +2,7 @@ package com.gmail.nossr50.database;
import com.gmail.nossr50.datatypes.database.DatabaseType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -16,14 +17,14 @@ public class DatabaseManagerFactory {
return createDefaultCustomDatabaseManager();
}
catch (Exception e) {
mcMMO.p.getLogger().info("Could not create custom database manager");
LogUtils.debug(mcMMO.p.getLogger(), "Could not create custom database manager");
e.printStackTrace();
}
catch (Throwable e) {
mcMMO.p.getLogger().info("Failed to create custom database manager");
LogUtils.debug(mcMMO.p.getLogger(), "Failed to create custom database manager");
e.printStackTrace();
}
mcMMO.p.getLogger().info("Falling back on " + (mcMMO.p.getGeneralConfig().getUseMySQL() ? "SQL" : "Flatfile") + " database");
LogUtils.debug(mcMMO.p.getLogger(), "Falling back on " + (mcMMO.p.getGeneralConfig().getUseMySQL() ? "SQL" : "Flatfile") + " database");
}
return mcMMO.p.getGeneralConfig().getUseMySQL() ? new SQLDatabaseManager() : new FlatFileDatabaseManager(userFilePath, logger, purgeTime, startingLevel);
@@ -62,16 +63,16 @@ public class DatabaseManagerFactory {
public static @Nullable DatabaseManager createDatabaseManager(@NotNull DatabaseType type, @NotNull String userFilePath, @NotNull Logger logger, long purgeTime, int startingLevel) {
switch (type) {
case FLATFILE:
mcMMO.p.getLogger().info("Using FlatFile Database");
LogUtils.debug(mcMMO.p.getLogger(), "Using FlatFile Database");
return new FlatFileDatabaseManager(userFilePath, logger, purgeTime, startingLevel);
case SQL:
mcMMO.p.getLogger().info("Using SQL Database");
LogUtils.debug(mcMMO.p.getLogger(), "Using SQL Database");
return new SQLDatabaseManager();
case CUSTOM:
try {
mcMMO.p.getLogger().info("Attempting to use Custom Database");
LogUtils.debug(mcMMO.p.getLogger(), "Attempting to use Custom Database");
return createDefaultCustomDatabaseManager();
}
catch (Throwable e) {

View File

@@ -9,6 +9,7 @@ import com.gmail.nossr50.datatypes.player.UniqueDataType;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.LogUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.SkillTools;
import org.bukkit.OfflinePlayer;
@@ -25,7 +26,7 @@ import java.util.logging.Logger;
public final class FlatFileDatabaseManager implements DatabaseManager {
public static final String IGNORED = "IGNORED";
public static final String LEGACY_INVALID_OLD_USERNAME = "_INVALID_OLD_USERNAME_'";
private final @NotNull EnumMap<PrimarySkillType, List<PlayerStat>> playerStatHash = new EnumMap<PrimarySkillType, List<PlayerStat>>(PrimarySkillType.class);
private final @NotNull EnumMap<PrimarySkillType, List<PlayerStat>> playerStatHash = new EnumMap<>(PrimarySkillType.class);
private final @NotNull List<PlayerStat> powerLevels = new ArrayList<>();
private long lastUpdate = 0;
private final @NotNull String usersFilePath;
@@ -115,12 +116,11 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
public int purgePowerlessUsers() {
int purgedUsers = 0;
logger.info("Purging powerless users...");
LogUtils.debug(logger, "Purging powerless users...");
BufferedReader in = null;
FileWriter out = null;
// This code is O(n) instead of O(n²)
synchronized (fileWritingLock) {
try {
in = new BufferedReader(new FileReader(usersFilePath));
@@ -184,7 +184,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
int removedPlayers = 0;
long currentTime = System.currentTimeMillis();
logger.info("Purging old users...");
LogUtils.debug(logger, "Purging old users...");
BufferedReader in = null;
FileWriter out = null;
@@ -198,7 +198,8 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
while ((line = in.readLine()) != null) {
String[] character = line.split(":");
String name = character[USERNAME_INDEX];
String uuidString = character[UUID_INDEX];
UUID uuid = UUID.fromString(uuidString);
long lastPlayed = 0;
boolean rewrite = false;
@@ -209,7 +210,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
}
if (lastPlayed == -1) {
OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(name);
OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(uuid);
if(player.getLastPlayed() != 0) {
lastPlayed = player.getLastPlayed();
@@ -217,7 +218,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
}
}
if (lastPlayed != -1 && lastPlayed != 0 && currentTime - lastPlayed > purgeTime) {
if (lastPlayed < 1 && (currentTime - lastPlayed > purgeTime)) {
removedPlayers++;
} else {
if (rewrite) {
@@ -715,7 +716,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
boolean matchingName = dbPlayerName.equalsIgnoreCase(playerName);
if (!matchingName) {
logger.info("When loading user: "+playerName +" with UUID of (" + uuid.toString()
logger.warning("When loading user: "+playerName +" with UUID of (" + uuid.toString()
+") we found a mismatched name, the name in the DB will be replaced (DB name: "+dbPlayerName+")");
//logger.info("Name updated for player: " + rawSplitData[USERNAME_INDEX] + " => " + playerName);
rawSplitData[USERNAME_INDEX] = playerName;
@@ -840,7 +841,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
logger.severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e);
}
finally {
logger.info(i + " entries written while saving UUID for " + userName);
LogUtils.debug(logger, i + " entries written while saving UUID for " + userName);
if (in != null) {
try {
in.close();
@@ -898,7 +899,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
logger.severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e);
}
finally {
logger.info(i + " entries written while saving UUID batch");
LogUtils.debug(logger, i + " entries written while saving UUID batch");
if (in != null) {
try {
in.close();
@@ -1092,7 +1093,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
public @Nullable List<FlatFileDataFlag> checkFileHealthAndStructure() {
ArrayList<FlatFileDataFlag> flagsFound = null;
logger.info("(" + usersFile.getPath() + ") Validating database file..");
LogUtils.debug(logger, "(" + usersFile.getPath() + ") Validating database file..");
FlatFileDataProcessor dataProcessor = null;
if (usersFile.exists()) {
@@ -1127,7 +1128,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager {
//Only update the file if needed
if(dataProcessor.getFlatFileDataFlags().size() > 0) {
flagsFound = new ArrayList<>(dataProcessor.getFlatFileDataFlags());
logger.info("Saving the updated and or repaired FlatFile Database...");
logger.info("Updating FlatFile Database...");
fileWriter = new FileWriter(usersFilePath);
//Write data to file
if(dbCommentDate != null)

View File

@@ -1,77 +0,0 @@
package com.gmail.nossr50.database;
public class FlatFileMappings {
//Used to map out the split data in the FFDB
public static int USERNAME = 0;
public static int SKILLS_MINING = 1;
public static int EXP_MINING = 4;
public static int SKILLS_WOODCUTTING = 5;
public static int EXP_WOODCUTTING = 6;
public static int SKILLS_REPAIR = 7;
public static int SKILLS_UNARMED = 8;
public static int SKILLS_HERBALISM = 9;
public static int SKILLS_EXCAVATION = 10;
public static int SKILLS_ARCHERY = 11;
public static int SKILLS_SWORDS = 12;
public static int SKILLS_AXES = 13;
public static int SKILLS_ACROBATICS = 14;
public static int EXP_REPAIR = 15;
public static int EXP_UNARMED = 16;
public static int EXP_HERBALISM = 17;
public static int EXP_EXCAVATION = 18;
public static int EXP_ARCHERY = 19;
public static int EXP_SWORDS = 20;
public static int EXP_AXES = 21;
public static int EXP_ACROBATICS = 22;
public static int SKILLS_TAMING = 24;
public static int EXP_TAMING = 25;
public static int COOLDOWN_BERSERK = 26;
public static int COOLDOWN_GIGA_DRILL_BREAKER = 27;
public static int COOLDOWN_TREE_FELLER = 28;
public static int COOLDOWN_GREEN_TERRA = 29;
public static int COOLDOWN_SERRATED_STRIKES = 30;
public static int COOLDOWN_SKULL_SPLITTER = 31;
public static int COOLDOWN_SUPER_BREAKER = 32;
public static int SKILLS_FISHING = 34;
public static int EXP_FISHING = 35;
public static int COOLDOWN_BLAST_MINING = 36;
public static int LAST_LOGIN = 37;
public static int HEALTHBAR = 38;
public static int SKILLS_ALCHEMY = 39;
public static int EXP_ALCHEMY = 40;
public static int UUID_INDEX = 41;
public static int SCOREBOARD_TIPS = 42;
public static int COOLDOWN_CHIMAERA_WING = 43;
public static int SKILLS_TRIDENTS = 44;
public static int EXP_TRIDENTS = 45;
public static int SKILLS_CROSSBOWS = 46;
public static int EXP_CROSSBOWS = 47;
public static int BARSTATE_ACROBATICS = 48;
public static int BARSTATE_ALCHEMY = 49;
public static int BARSTATE_ARCHERY = 50;
public static int BARSTATE_AXES = 51;
public static int BARSTATE_EXCAVATION = 52;
public static int BARSTATE_FISHING = 53;
public static int BARSTATE_HERBALISM = 54;
public static int BARSTATE_MINING = 55;
public static int BARSTATE_REPAIR = 56;
public static int BARSTATE_SALVAGE = 57;
public static int BARSTATE_SMELTING = 58;
public static int BARSTATE_SWORDS = 59;
public static int BARSTATE_TAMING = 60;
public static int BARSTATE_UNARMED = 61;
public static int BARSTATE_WOODCUTTING = 62;
public static int BARSTATE_TRIDENTS = 63;
public static int BARSTATE_CROSSBOWS = 64;
public static int COOLDOWN_ARCHERY_SUPER_1 = 65;
public static int COOLDOWN_CROSSBOWS_SUPER_1 = 66;
public static int COOLDOWN_TRIDENTS_SUPER_1 = 67;
public static int CHATSPY_TOGGLE = 68;
public static int LEADERBOARD_IGNORED = 69;
//TODO: Always update this
public final static int LENGTH_OF_SPLIT_DATA_ARRAY = 69;
}

View File

@@ -1,25 +1,19 @@
package com.gmail.nossr50.database;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.database.DatabaseType;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.database.UpgradeType;
import com.gmail.nossr50.datatypes.player.MMODataBuilder;
import com.gmail.nossr50.datatypes.player.MMODataSnapshot;
import com.gmail.nossr50.datatypes.player.PlayerData;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.player.UniqueDataType;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.database.UUIDUpdateAsyncTask;
import com.gmail.nossr50.util.LogUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.util.skills.SkillUtils;
import com.neetgames.mcmmo.MobHealthBarType;
import com.neetgames.mcmmo.UniqueDataType;
import com.neetgames.mcmmo.database.PoolIdentifier;
import com.neetgames.mcmmo.exceptions.InvalidSkillException;
import com.neetgames.mcmmo.skill.SkillBossBarState;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.bukkit.OfflinePlayer;
@@ -58,7 +52,8 @@ public final class SQLDatabaseManager implements DatabaseManager {
String connectionString = "jdbc:mysql://" + mcMMO.p.getGeneralConfig().getMySQLServerName()
+ ":" + mcMMO.p.getGeneralConfig().getMySQLServerPort() + "/" + mcMMO.p.getGeneralConfig().getMySQLDatabaseName();
if(mcMMO.p.getGeneralConfig().getMySQLSSL())
if(!mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 17, 0) //Temporary hack for SQL and 1.17 support
&& mcMMO.p.getGeneralConfig().getMySQLSSL())
connectionString +=
"?verifyServerCertificate=false"+
"&useSSL=true"+
@@ -67,6 +62,11 @@ public final class SQLDatabaseManager implements DatabaseManager {
connectionString+=
"?useSSL=false";
if(mcMMO.p.getGeneralConfig().getMySQLPublicKeyRetrieval()) {
connectionString+=
"&allowPublicKeyRetrieval=true";
}
try {
// Force driver to load if not yet loaded
Class.forName(driverPath);
@@ -150,7 +150,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
+ "taming = 0 AND mining = 0 AND woodcutting = 0 AND repair = 0 "
+ "AND unarmed = 0 AND herbalism = 0 AND excavation = 0 AND "
+ "archery = 0 AND swords = 0 AND axes = 0 AND acrobatics = 0 "
+ "AND fishing = 0 AND alchemy = 0 AND tridents = 0 AND crossbows = 0;");
+ "AND fishing = 0 AND alchemy = 0;");
statement.executeUpdate("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "experience`.`user_id` = `s`.`user_id`)");
statement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "huds`.`user_id` = `s`.`user_id`)");
@@ -200,7 +200,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
mcMMO.p.getLogger().info("Purged " + purged + " users from the database.");
}
public boolean removeUser(@NotNull String playerName, @Nullable UUID uuid) {
public boolean removeUser(String playerName, UUID uuid) {
boolean success = false;
Connection connection = null;
PreparedStatement statement = null;
@@ -241,7 +241,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
cachedUserIDs.remove(uuid);
}
public boolean saveUser(@NotNull MMODataSnapshot dataSnapshot) {
public boolean saveUser(PlayerProfile profile) {
boolean success = true;
PreparedStatement statement = null;
Connection connection = null;
@@ -249,22 +249,22 @@ public final class SQLDatabaseManager implements DatabaseManager {
try {
connection = getConnection(PoolIdentifier.SAVE);
int id = getUserID(connection, dataSnapshot.getPlayerName(), dataSnapshot.getPlayerUUID());
int id = getUserID(connection, profile.getPlayerName(), profile.getUniqueId());
// if (id == -1) {
// id = newUser(connection, dataSnapshot.getPlayerName(), dataSnapshot.getPlayerUUID());
// if (id == -1) {
// mcMMO.p.getLogger().severe("Failed to create new account for " + dataSnapshot.getPlayerName());
// return false;
// }
// }
if (id == -1) {
id = newUser(connection, profile.getPlayerName(), profile.getUniqueId());
if (id == -1) {
mcMMO.p.getLogger().severe("Failed to create new account for " + profile.getPlayerName());
return false;
}
}
statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET lastlogin = UNIX_TIMESTAMP() WHERE id = ?");
statement.setInt(1, id);
success &= (statement.executeUpdate() != 0);
statement.close();
if (!success) {
mcMMO.p.getLogger().severe("Failed to update last login for " + dataSnapshot.getPlayerName());
mcMMO.p.getLogger().severe("Failed to update last login for " + profile.getPlayerName());
return false;
}
@@ -272,31 +272,29 @@ public final class SQLDatabaseManager implements DatabaseManager {
+ " taming = ?, mining = ?, repair = ?, woodcutting = ?"
+ ", unarmed = ?, herbalism = ?, excavation = ?"
+ ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
+ ", fishing = ?, alchemy = ?, tridents = ?, crossbows = ?, total = ? WHERE user_id = ?");
statement.setInt(1, dataSnapshot.getSkillLevel(PrimarySkillType.TAMING));
statement.setInt(2, dataSnapshot.getSkillLevel(PrimarySkillType.MINING));
statement.setInt(3, dataSnapshot.getSkillLevel(PrimarySkillType.REPAIR));
statement.setInt(4, dataSnapshot.getSkillLevel(PrimarySkillType.WOODCUTTING));
statement.setInt(5, dataSnapshot.getSkillLevel(PrimarySkillType.UNARMED));
statement.setInt(6, dataSnapshot.getSkillLevel(PrimarySkillType.HERBALISM));
statement.setInt(7, dataSnapshot.getSkillLevel(PrimarySkillType.EXCAVATION));
statement.setInt(8, dataSnapshot.getSkillLevel(PrimarySkillType.ARCHERY));
statement.setInt(9, dataSnapshot.getSkillLevel(PrimarySkillType.SWORDS));
statement.setInt(10, dataSnapshot.getSkillLevel(PrimarySkillType.AXES));
statement.setInt(11, dataSnapshot.getSkillLevel(PrimarySkillType.ACROBATICS));
statement.setInt(12, dataSnapshot.getSkillLevel(PrimarySkillType.FISHING));
statement.setInt(13, dataSnapshot.getSkillLevel(PrimarySkillType.ALCHEMY));
statement.setInt(14, dataSnapshot.getSkillLevel(PrimarySkillType.TRIDENTS));
statement.setInt(15, dataSnapshot.getSkillLevel(PrimarySkillType.CROSSBOWS));
+ ", fishing = ?, alchemy = ?, total = ? WHERE user_id = ?");
statement.setInt(1, profile.getSkillLevel(PrimarySkillType.TAMING));
statement.setInt(2, profile.getSkillLevel(PrimarySkillType.MINING));
statement.setInt(3, profile.getSkillLevel(PrimarySkillType.REPAIR));
statement.setInt(4, profile.getSkillLevel(PrimarySkillType.WOODCUTTING));
statement.setInt(5, profile.getSkillLevel(PrimarySkillType.UNARMED));
statement.setInt(6, profile.getSkillLevel(PrimarySkillType.HERBALISM));
statement.setInt(7, profile.getSkillLevel(PrimarySkillType.EXCAVATION));
statement.setInt(8, profile.getSkillLevel(PrimarySkillType.ARCHERY));
statement.setInt(9, profile.getSkillLevel(PrimarySkillType.SWORDS));
statement.setInt(10, profile.getSkillLevel(PrimarySkillType.AXES));
statement.setInt(11, profile.getSkillLevel(PrimarySkillType.ACROBATICS));
statement.setInt(12, profile.getSkillLevel(PrimarySkillType.FISHING));
statement.setInt(13, profile.getSkillLevel(PrimarySkillType.ALCHEMY));
int total = 0;
for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills())
total += dataSnapshot.getSkillLevel(primarySkillType);
statement.setInt(16, total);
statement.setInt(17, id);
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS)
total += profile.getSkillLevel(primarySkillType);
statement.setInt(14, total);
statement.setInt(15, id);
success &= (statement.executeUpdate() != 0);
statement.close();
if (!success) {
mcMMO.p.getLogger().severe("Failed to update skills for " + dataSnapshot.getPlayerName());
mcMMO.p.getLogger().severe("Failed to update skills for " + profile.getPlayerName());
return false;
}
@@ -304,112 +302,59 @@ public final class SQLDatabaseManager implements DatabaseManager {
+ " taming = ?, mining = ?, repair = ?, woodcutting = ?"
+ ", unarmed = ?, herbalism = ?, excavation = ?"
+ ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
+ ", fishing = ?, alchemy = ?, tridents = ?, crossbows = ?, WHERE user_id = ?");
statement.setInt(1, dataSnapshot.getSkillXpLevel(PrimarySkillType.TAMING));
statement.setInt(2, dataSnapshot.getSkillXpLevel(PrimarySkillType.MINING));
statement.setInt(3, dataSnapshot.getSkillXpLevel(PrimarySkillType.REPAIR));
statement.setInt(4, dataSnapshot.getSkillXpLevel(PrimarySkillType.WOODCUTTING));
statement.setInt(5, dataSnapshot.getSkillXpLevel(PrimarySkillType.UNARMED));
statement.setInt(6, dataSnapshot.getSkillXpLevel(PrimarySkillType.HERBALISM));
statement.setInt(7, dataSnapshot.getSkillXpLevel(PrimarySkillType.EXCAVATION));
statement.setInt(8, dataSnapshot.getSkillXpLevel(PrimarySkillType.ARCHERY));
statement.setInt(9, dataSnapshot.getSkillXpLevel(PrimarySkillType.SWORDS));
statement.setInt(10, dataSnapshot.getSkillXpLevel(PrimarySkillType.AXES));
statement.setInt(11, dataSnapshot.getSkillXpLevel(PrimarySkillType.ACROBATICS));
statement.setInt(12, dataSnapshot.getSkillXpLevel(PrimarySkillType.FISHING));
statement.setInt(13, dataSnapshot.getSkillXpLevel(PrimarySkillType.ALCHEMY));
statement.setInt(14, dataSnapshot.getSkillXpLevel(PrimarySkillType.TRIDENTS));
statement.setInt(15, dataSnapshot.getSkillXpLevel(PrimarySkillType.CROSSBOWS));
statement.setInt(16, id);
+ ", fishing = ?, alchemy = ? WHERE user_id = ?");
statement.setInt(1, profile.getSkillXpLevel(PrimarySkillType.TAMING));
statement.setInt(2, profile.getSkillXpLevel(PrimarySkillType.MINING));
statement.setInt(3, profile.getSkillXpLevel(PrimarySkillType.REPAIR));
statement.setInt(4, profile.getSkillXpLevel(PrimarySkillType.WOODCUTTING));
statement.setInt(5, profile.getSkillXpLevel(PrimarySkillType.UNARMED));
statement.setInt(6, profile.getSkillXpLevel(PrimarySkillType.HERBALISM));
statement.setInt(7, profile.getSkillXpLevel(PrimarySkillType.EXCAVATION));
statement.setInt(8, profile.getSkillXpLevel(PrimarySkillType.ARCHERY));
statement.setInt(9, profile.getSkillXpLevel(PrimarySkillType.SWORDS));
statement.setInt(10, profile.getSkillXpLevel(PrimarySkillType.AXES));
statement.setInt(11, profile.getSkillXpLevel(PrimarySkillType.ACROBATICS));
statement.setInt(12, profile.getSkillXpLevel(PrimarySkillType.FISHING));
statement.setInt(13, profile.getSkillXpLevel(PrimarySkillType.ALCHEMY));
statement.setInt(14, id);
success &= (statement.executeUpdate() != 0);
statement.close();
if (!success) {
mcMMO.p.getLogger().severe("Failed to update experience for " + dataSnapshot.getPlayerName());
mcMMO.p.getLogger().severe("Failed to update experience for " + profile.getPlayerName());
return false;
}
statement = connection.prepareStatement("UPDATE " + tablePrefix + "cooldowns SET "
+ " mining = ?, woodcutting = ?, unarmed = ?"
+ ", herbalism = ?, excavation = ?, swords = ?"
+ ", axes = ?, blast_mining = ?, chimaera_wing = ?, archery = ?, tridents = ?, crossbows = ? WHERE user_id = ?");
statement.setLong(1, dataSnapshot.getAbilityDATS(SuperAbilityType.SUPER_BREAKER));
statement.setLong(2, dataSnapshot.getAbilityDATS(SuperAbilityType.TREE_FELLER));
statement.setLong(3, dataSnapshot.getAbilityDATS(SuperAbilityType.BERSERK));
statement.setLong(4, dataSnapshot.getAbilityDATS(SuperAbilityType.GREEN_TERRA));
statement.setLong(5, dataSnapshot.getAbilityDATS(SuperAbilityType.GIGA_DRILL_BREAKER));
statement.setLong(6, dataSnapshot.getAbilityDATS(SuperAbilityType.SERRATED_STRIKES));
statement.setLong(7, dataSnapshot.getAbilityDATS(SuperAbilityType.SKULL_SPLITTER));
statement.setLong(8, dataSnapshot.getAbilityDATS(SuperAbilityType.BLAST_MINING));
statement.setLong(9, dataSnapshot.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS));
statement.setLong(10, dataSnapshot.getAbilityDATS(SuperAbilityType.ARCHERY_SUPER));
statement.setLong(11, dataSnapshot.getAbilityDATS(SuperAbilityType.TRIDENT_SUPER));
statement.setLong(12, dataSnapshot.getAbilityDATS(SuperAbilityType.SUPER_SHOTGUN));
statement.setInt(13, id);
+ ", axes = ?, blast_mining = ?, chimaera_wing = ? WHERE user_id = ?");
statement.setLong(1, profile.getAbilityDATS(SuperAbilityType.SUPER_BREAKER));
statement.setLong(2, profile.getAbilityDATS(SuperAbilityType.TREE_FELLER));
statement.setLong(3, profile.getAbilityDATS(SuperAbilityType.BERSERK));
statement.setLong(4, profile.getAbilityDATS(SuperAbilityType.GREEN_TERRA));
statement.setLong(5, profile.getAbilityDATS(SuperAbilityType.GIGA_DRILL_BREAKER));
statement.setLong(6, profile.getAbilityDATS(SuperAbilityType.SERRATED_STRIKES));
statement.setLong(7, profile.getAbilityDATS(SuperAbilityType.SKULL_SPLITTER));
statement.setLong(8, profile.getAbilityDATS(SuperAbilityType.BLAST_MINING));
statement.setLong(9, profile.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS));
statement.setInt(10, id);
success = (statement.executeUpdate() != 0);
statement.close();
if (!success) {
mcMMO.p.getLogger().severe("Failed to update cooldowns for " + dataSnapshot.getPlayerName());
mcMMO.p.getLogger().severe("Failed to update cooldowns for " + profile.getPlayerName());
return false;
}
statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ?, scoreboardtips = ? WHERE user_id = ?");
statement.setString(1, MobHealthbarType.HEARTS.name());
statement.setInt(2, dataSnapshot.getScoreboardTipsShown());
statement.setInt(2, profile.getScoreboardTipsShown());
statement.setInt(3, id);
success = (statement.executeUpdate() != 0);
statement.close();
if (!success) {
mcMMO.p.getLogger().severe("Failed to update hud settings for " + dataSnapshot.getPlayerName());
mcMMO.p.getLogger().severe("Failed to update hud settings for " + profile.getPlayerName());
return false;
}
//XP BAR STUFF
statement = connection.prepareStatement("UPDATE " + tablePrefix + "xpbar SET "
+ " view_taming = ?, view_mining = ?, view_repair = ?, view_woodcutting = ?"
+ ", view_unarmed = ?, view_herbalism = ?, view_excavation = ?"
+ ", view_archery = ?, view_swords = ?, view_axes = ?, view_acrobatics = ?"
+ ", view_fishing = ?, view_alchemy = ?, view_salvage = ?, view_smelting = ?, view_tridents = ?, view_crossbows = ? WHERE user_id = ?");
statement.setString(1, dataSnapshot.getBarStateMap().get(PrimarySkillType.TAMING).toString());
statement.setString(2, dataSnapshot.getBarStateMap().get(PrimarySkillType.MINING).toString());
statement.setString(3, dataSnapshot.getBarStateMap().get(PrimarySkillType.REPAIR).toString());
statement.setString(4, dataSnapshot.getBarStateMap().get(PrimarySkillType.WOODCUTTING).toString());
statement.setString(5, dataSnapshot.getBarStateMap().get(PrimarySkillType.UNARMED).toString());
statement.setString(6, dataSnapshot.getBarStateMap().get(PrimarySkillType.HERBALISM).toString());
statement.setString(7, dataSnapshot.getBarStateMap().get(PrimarySkillType.EXCAVATION).toString());
statement.setString(8, dataSnapshot.getBarStateMap().get(PrimarySkillType.ARCHERY).toString());
statement.setString(9, dataSnapshot.getBarStateMap().get(PrimarySkillType.SWORDS).toString());
statement.setString(10, dataSnapshot.getBarStateMap().get(PrimarySkillType.AXES).toString());
statement.setString(11, dataSnapshot.getBarStateMap().get(PrimarySkillType.ACROBATICS).toString());
statement.setString(12, dataSnapshot.getBarStateMap().get(PrimarySkillType.FISHING).toString());
statement.setString(13, dataSnapshot.getBarStateMap().get(PrimarySkillType.ALCHEMY).toString());
statement.setString(14, dataSnapshot.getBarStateMap().get(PrimarySkillType.SALVAGE).toString());
statement.setString(15, dataSnapshot.getBarStateMap().get(PrimarySkillType.SMELTING).toString());
statement.setString(16, dataSnapshot.getBarStateMap().get(PrimarySkillType.TRIDENTS).toString());
statement.setString(17, dataSnapshot.getBarStateMap().get(PrimarySkillType.CROSSBOWS).toString());
statement.setInt(18, id);
success &= (statement.executeUpdate() != 0);
statement.close();
if (!success) {
mcMMO.p.getLogger().severe("Failed to update XP bar views for " + dataSnapshot.getPlayerName());
return false;
}
//TOGGLES
statement = connection.prepareStatement("UPDATE " + tablePrefix + "toggle SET "
+ " chatspy = ?, rankless = ? WHERE user_id = ?");
statement.setBoolean(1, dataSnapshot.getPartyChatSpying());
statement.setBoolean(2, dataSnapshot.isLeaderBoardExcluded());
statement.setInt(3, id);
success &= (statement.executeUpdate() != 0);
statement.close();
if (!success) {
mcMMO.p.getLogger().severe("Failed to update user toggles for " + dataSnapshot.getPlayerName());
return false;
}
}
catch (SQLException ex) {
printErrors(ex);
@@ -422,26 +367,24 @@ public final class SQLDatabaseManager implements DatabaseManager {
return success;
}
public @NotNull List<PlayerStat> readLeaderboard(@Nullable PrimarySkillType primarySkillType, int pageNumber, int statsPerPage) throws InvalidSkillException {
public @NotNull List<PlayerStat> readLeaderboard(@Nullable PrimarySkillType skill, int pageNumber, int statsPerPage) throws InvalidSkillException {
List<PlayerStat> stats = new ArrayList<>();
//Fix for a plugin that people are using that is throwing SQL errors
if(primarySkillType != null && SkillTools.isChildSkill(primarySkillType)) {
if(skill != null && SkillTools.isChildSkill(skill)) {
mcMMO.p.getLogger().severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!");
throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!");
}
String query = primarySkillType == null ? ALL_QUERY_VERSION : primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH);
String query = skill == null ? ALL_QUERY_VERSION : skill.name().toLowerCase(Locale.ENGLISH);
ResultSet resultSet = null;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = getConnection(PoolIdentifier.MISC);
statement = connection.prepareStatement("SELECT " + query + ", user FROM " + tablePrefix + "users JOIN " + tablePrefix
+ "skills ON (user_id = id) WHERE " + query + " > 0 AND NOT user = '\\_INVALID\\_OLD\\_USERNAME\\_' ORDER BY "
+ query + " DESC, user LIMIT ?, ?");
statement = connection.prepareStatement("SELECT " + query + ", user FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 AND NOT user = '\\_INVALID\\_OLD\\_USERNAME\\_' ORDER BY " + query + " DESC, user LIMIT ?, ?");
statement.setInt(1, (pageNumber * statsPerPage) - statsPerPage);
statement.setInt(2, statsPerPage);
resultSet = statement.executeQuery();
@@ -468,7 +411,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
return stats;
}
public @NotNull Map<PrimarySkillType, Integer> readRank(@NotNull String playerName) {
public Map<PrimarySkillType, Integer> readRank(String playerName) {
Map<PrimarySkillType, Integer> skills = new HashMap<>();
ResultSet resultSet = null;
@@ -477,8 +420,8 @@ public final class SQLDatabaseManager implements DatabaseManager {
try {
connection = getConnection(PoolIdentifier.MISC);
for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills()) {
String skillName = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH);
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
String skillName = primarySkillType.name().toLowerCase(Locale.ENGLISH);
// Get count of all users with higher skill level than player
String sql = "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
"AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
@@ -664,17 +607,13 @@ public final class SQLDatabaseManager implements DatabaseManager {
throw new RuntimeException("Error looking up player, both UUID and playerName are null and one must not be.");
}
return loadPlayerProfile(null, playerName, uuid);
}
private @Nullable PlayerData loadPlayerProfile(@Nullable Player player, @NotNull String playerName, @Nullable UUID playerUUID) {
PreparedStatement statement = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection = getConnection(PoolIdentifier.LOAD);
int id = getUserID(connection, playerName, playerUUID);
int id = getUserID(connection, playerName, uuid);
if (id == -1) {
// There is no such user
@@ -683,14 +622,25 @@ public final class SQLDatabaseManager implements DatabaseManager {
// There is such a user
writeMissingRows(connection, id);
statement = getUserData(connection);
statement = connection.prepareStatement(
"SELECT "
+ "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
+ "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
+ "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, "
+ "h.mobhealthbar, h.scoreboardtips, u.uuid, u.user "
+ "FROM " + tablePrefix + "users u "
+ "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
+ "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
+ "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
+ "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
+ "WHERE u.id = ?");
statement.setInt(1, id);
resultSet = statement.executeQuery();
if (resultSet.next()) {
try {
PlayerData mmoPlayerData = loadFromResult(playerName, resultSet);
PlayerProfile profile = loadFromResult(playerName, resultSet);
String name = resultSet.getString(42); // TODO: Magic Number, make sure it stays updated
resultSet.close();
statement.close();
@@ -698,7 +648,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
if (playerName != null
&& !playerName.isEmpty()
&& !playerName.equalsIgnoreCase(name)
&& playerUUID != null) {
&& uuid != null) {
statement = connection.prepareStatement(
"UPDATE `" + tablePrefix + "users` "
+ "SET user = ? "
@@ -712,13 +662,13 @@ public final class SQLDatabaseManager implements DatabaseManager {
+ "SET user = ?, uuid = ? "
+ "WHERE id = ?");
statement.setString(1, playerName);
statement.setString(2, playerUUID.toString());
statement.setString(2, uuid.toString());
statement.setInt(3, id);
statement.executeUpdate();
statement.close();
}
return mmoPlayerData;
return profile;
}
catch (SQLException e) {
printErrors(e);
@@ -746,7 +696,18 @@ public final class SQLDatabaseManager implements DatabaseManager {
try {
connection = getConnection(PoolIdentifier.MISC);
statement = getUserData(connection);
statement = connection.prepareStatement(
"SELECT "
+ "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
+ "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
+ "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, "
+ "h.mobhealthbar, h.scoreboardtips, u.uuid "
+ "FROM " + tablePrefix + "users u "
+ "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
+ "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
+ "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
+ "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
+ "WHERE u.user = ?");
List<String> usernames = getStoredUsers();
int convertedUsers = 0;
long startMillis = System.currentTimeMillis();
@@ -755,10 +716,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
try {
resultSet = statement.executeQuery();
resultSet.next();
//TODO: Optimize, probably needless to make a snapshot here, brain tired
PlayerData mmoPlayerData = loadFromResult(playerName, resultSet);
MMODataSnapshot mmoDataSnapshot = UserManager.createPlayerDataSnapshot(mmoPlayerData);
destination.saveUser(mmoDataSnapshot);
destination.saveUser(loadFromResult(playerName, resultSet));
resultSet.close();
}
catch (SQLException e) {
@@ -780,27 +738,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
}
private @NotNull PreparedStatement getUserData(@NotNull Connection connection) throws SQLException {
return connection.prepareStatement(
"SELECT "
+ "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, s.tridents, s.crossbows, "
+ "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, e.tridents, e.crossbows, "
+ "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, c.tridents, c.crossbows, "
+ "h.mobhealthbar, h.scoreboardtips, u.uuid "
+ "x.view_taming, x.view_mining, x.view_repair, x.view_woodcutting, x.view_unarmed, x.view_herbalism, x.view_excavation, x.view_archery, x.view_swords, x.view_axes, x.view_acrobatics, x.view_salvage, x.view_smelting, x.view_tridents, x.view_crossbows, "
+ "t.chatspy, t.rankless, "
+ "FROM " + tablePrefix + "users u "
+ "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
+ "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
+ "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
+ "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
+ "JOIN " + tablePrefix + "xpbar x ON (u.id = x.user_id) "
+ "JOIN " + tablePrefix + "toggle t ON (u.id = t.user_id) "
+ "WHERE u.user = ?");
}
public boolean saveUserUUID(@NotNull String userName, @NotNull UUID uuid) {
public boolean saveUserUUID(String userName, UUID uuid) {
PreparedStatement statement = null;
Connection connection = null;
@@ -824,47 +762,47 @@ public final class SQLDatabaseManager implements DatabaseManager {
}
}
// public boolean saveUserUUIDs(Map<String, UUID> fetchedUUIDs) {
// PreparedStatement statement = null;
// int count = 0;
//
// Connection connection = null;
//
// try {
// connection = getConnection(PoolIdentifier.MISC);
// statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET uuid = ? WHERE user = ?");
//
// for (Map.Entry<String, UUID> entry : fetchedUUIDs.entrySet()) {
// statement.setString(1, entry.getValue().toString());
// statement.setString(2, entry.getKey());
//
// statement.addBatch();
//
// count++;
//
// if ((count % 500) == 0) {
// statement.executeBatch();
// count = 0;
// }
// }
//
// if (count != 0) {
// statement.executeBatch();
// }
//
// return true;
// }
// catch (SQLException ex) {
// printErrors(ex);
// return false;
// }
// finally {
// tryClose(statement);
// tryClose(connection);
// }
// }
public boolean saveUserUUIDs(Map<String, UUID> fetchedUUIDs) {
PreparedStatement statement = null;
int count = 0;
public @NotNull List<String> getStoredUsers() {
Connection connection = null;
try {
connection = getConnection(PoolIdentifier.MISC);
statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET uuid = ? WHERE user = ?");
for (Map.Entry<String, UUID> entry : fetchedUUIDs.entrySet()) {
statement.setString(1, entry.getValue().toString());
statement.setString(2, entry.getKey());
statement.addBatch();
count++;
if ((count % 500) == 0) {
statement.executeBatch();
count = 0;
}
}
if (count != 0) {
statement.executeBatch();
}
return true;
}
catch (SQLException ex) {
printErrors(ex);
return false;
}
finally {
tryClose(statement);
tryClose(connection);
}
}
public List<String> getStoredUsers() {
ArrayList<String> users = new ArrayList<>();
Statement statement = null;
@@ -956,8 +894,6 @@ public final class SQLDatabaseManager implements DatabaseManager {
+ "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`chimaera_wing` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`tridents` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`crossbows` int(32) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=" + CHARSET_SQL + ";");
tryClose(createStatement);
@@ -972,22 +908,20 @@ public final class SQLDatabaseManager implements DatabaseManager {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`alchemy` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`tridents` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`crossbows` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`total` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`taming` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`mining` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`repair` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`excavation` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`archery` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`swords` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`axes` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`fishing` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`alchemy` int(10) unsigned NOT NULL DEFAULT "+startingLevel+","
+ "`total` int(10) unsigned NOT NULL DEFAULT "+totalLevel+","
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=" + CHARSET_SQL + ";");
tryClose(createStatement);
@@ -1013,55 +947,6 @@ public final class SQLDatabaseManager implements DatabaseManager {
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`alchemy` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`tridents` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`crossbows` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
tryClose(createStatement);
}
tryClose(resultSet);
tryClose(statement);
//Toggle Table
statement.setString(1, Config.getInstance().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "toggle");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "toggle` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`chatspy` bit NOT NULL DEFAULT '0',"
+ "`rankless` bit NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=latin1;");
tryClose(createStatement);
}
tryClose(resultSet);
tryClose(statement);
//XP Bar Table
statement.setString(1, Config.getInstance().getMySQLDatabaseName());
statement.setString(2, tablePrefix + "xpbar");
resultSet = statement.executeQuery();
if (!resultSet.next()) {
createStatement = connection.createStatement();
createStatement.executeUpdate("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "xpbar` ("
+ "`user_id` int(10) unsigned NOT NULL,"
+ "`view_taming` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_mining` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_woodcutting` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_repair` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_unarmed` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_herbalism` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_excavation` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_archery` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_swords` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_axes` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_acrobatics` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_salvage` varchar(40) NOT NULL DEFAULT 'DISABLED',"
+ "`view_smelting` varchar(40) NOT NULL DEFAULT 'DISABLED',"
+ "`view_tridents` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "`view_crossbows` varchar(40) NOT NULL DEFAULT 'NORMAL',"
+ "PRIMARY KEY (`user_id`)) "
+ "DEFAULT CHARSET=" + CHARSET_SQL + ";");
tryClose(createStatement);
@@ -1074,12 +959,10 @@ public final class SQLDatabaseManager implements DatabaseManager {
}
if (mcMMO.p.getGeneralConfig().getTruncateSkills()) {
for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills()) {
int cap = mcMMO.p.getSkillTools().getLevelCap(primarySkillType);
for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) {
int cap = mcMMO.p.getSkillTools().getLevelCap(skill);
if (cap != Integer.MAX_VALUE) {
statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `"
+ primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `"
+ primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` > " + cap);
statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `" + skill.name().toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `" + skill.name().toLowerCase(Locale.ENGLISH) + "` > " + cap);
statement.executeUpdate();
tryClose(statement);
}
@@ -1092,8 +975,6 @@ public final class SQLDatabaseManager implements DatabaseManager {
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "huds`.`user_id` = `u`.`id`)");
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "cooldowns` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "cooldowns`.`user_id` = `u`.`id`)");
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "skills` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "skills`.`user_id` = `u`.`id`)");
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "toggle` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "skills`.`user_id` = `u`.`id`)");
createStatement.executeUpdate("DELETE FROM `" + tablePrefix + "xpbar` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "skills`.`user_id` = `u`.`id`)");
}
catch (SQLException ex) {
printErrors(ex);
@@ -1133,7 +1014,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
*/
private void checkDatabaseStructure(Connection connection, UpgradeType upgrade) {
if (!mcMMO.getUpgradeManager().shouldUpgrade(upgrade)) {
mcMMO.p.getLogger().info("Skipping " + upgrade.name() + " upgrade (unneeded)");
LogUtils.debug(mcMMO.p.getLogger(), "Skipping " + upgrade.name() + " upgrade (unneeded)");
return;
}
@@ -1174,6 +1055,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
case ADD_UUIDS:
checkUpgradeAddUUIDs(statement);
return;
case ADD_SCOREBOARD_TIPS:
checkUpgradeAddScoreboardTips(statement);
return;
@@ -1193,9 +1075,6 @@ public final class SQLDatabaseManager implements DatabaseManager {
updateCharacterSet(statement);
break;
case ADD_SQL_2_2:
checkUpgradeAddTridentsAndCrossbowsSQL(statement);
break;
default:
break;
@@ -1244,22 +1123,19 @@ public final class SQLDatabaseManager implements DatabaseManager {
}
private PlayerProfile loadFromResult(String playerName, ResultSet result) throws SQLException {
Map<PrimarySkillType, Integer> skills = new EnumMap<PrimarySkillType, Integer>(PrimarySkillType.class); // Skill & Level
Map<PrimarySkillType, Float> skillsXp = new EnumMap<PrimarySkillType, Float>(PrimarySkillType.class); // Skill & XP
Map<PrimarySkillType, Integer> skills = new EnumMap<>(PrimarySkillType.class); // Skill & Level
Map<PrimarySkillType, Float> skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP
Map<SuperAbilityType, Integer> skillsDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown
Map<UniqueDataType, Integer> uniqueData = new EnumMap<>(UniqueDataType.class); //Chimaera wing cooldown and other misc info
MobHealthbarType mobHealthbarType;
UUID uuid;
int scoreboardTipsShown;
final int parentSkills = 15, allSkills = 17, cooldownCount = 17, toggleCount = 2, otherCount = 4;
final int OFFSET_SKILLS = 0; // TODO update these numbers when the query
// changes (a new skill is added)
final int OFFSET_EXPERIENCE = OFFSET_SKILLS + parentSkills;
final int OFFSET_COOLDOWNS = OFFSET_EXPERIENCE + parentSkills;
final int OFFSET_OTHER = OFFSET_COOLDOWNS + cooldownCount;
final int OFFSET_XPBAR = OFFSET_OTHER + otherCount;
final int OFFSET_TOGGLE = OFFSET_XPBAR + allSkills;
final int OFFSET_XP = 13;
final int OFFSET_DATS = 26;
final int OFFSET_OTHER = 39;
skills.put(PrimarySkillType.TAMING, result.getInt(OFFSET_SKILLS + 1));
skills.put(PrimarySkillType.MINING, result.getInt(OFFSET_SKILLS + 2));
@@ -1274,42 +1150,34 @@ public final class SQLDatabaseManager implements DatabaseManager {
skills.put(PrimarySkillType.ACROBATICS, result.getInt(OFFSET_SKILLS + 11));
skills.put(PrimarySkillType.FISHING, result.getInt(OFFSET_SKILLS + 12));
skills.put(PrimarySkillType.ALCHEMY, result.getInt(OFFSET_SKILLS + 13));
skills.put(PrimarySkillType.TRIDENTS, result.getInt(OFFSET_SKILLS + 14));
skills.put(PrimarySkillType.CROSSBOWS, result.getInt(OFFSET_SKILLS + 15));
skillsXp.put(PrimarySkillType.TAMING, result.getFloat(OFFSET_EXPERIENCE + 1));
skillsXp.put(PrimarySkillType.MINING, result.getFloat(OFFSET_EXPERIENCE + 2));
skillsXp.put(PrimarySkillType.REPAIR, result.getFloat(OFFSET_EXPERIENCE + 3));
skillsXp.put(PrimarySkillType.WOODCUTTING, result.getFloat(OFFSET_EXPERIENCE + 4));
skillsXp.put(PrimarySkillType.UNARMED, result.getFloat(OFFSET_EXPERIENCE + 5));
skillsXp.put(PrimarySkillType.HERBALISM, result.getFloat(OFFSET_EXPERIENCE + 6));
skillsXp.put(PrimarySkillType.EXCAVATION, result.getFloat(OFFSET_EXPERIENCE + 7));
skillsXp.put(PrimarySkillType.ARCHERY, result.getFloat(OFFSET_EXPERIENCE + 8));
skillsXp.put(PrimarySkillType.SWORDS, result.getFloat(OFFSET_EXPERIENCE + 9));
skillsXp.put(PrimarySkillType.AXES, result.getFloat(OFFSET_EXPERIENCE + 10));
skillsXp.put(PrimarySkillType.ACROBATICS, result.getFloat(OFFSET_EXPERIENCE + 11));
skillsXp.put(PrimarySkillType.FISHING, result.getFloat(OFFSET_EXPERIENCE + 12));
skillsXp.put(PrimarySkillType.ALCHEMY, result.getFloat(OFFSET_EXPERIENCE + 13));
skillsXp.put(PrimarySkillType.TRIDENTS, result.getFloat(OFFSET_EXPERIENCE + 14));
skillsXp.put(PrimarySkillType.CROSSBOWS, result.getFloat(OFFSET_EXPERIENCE + 15));
skillsXp.put(PrimarySkillType.TAMING, result.getFloat(OFFSET_XP + 1));
skillsXp.put(PrimarySkillType.MINING, result.getFloat(OFFSET_XP + 2));
skillsXp.put(PrimarySkillType.REPAIR, result.getFloat(OFFSET_XP + 3));
skillsXp.put(PrimarySkillType.WOODCUTTING, result.getFloat(OFFSET_XP + 4));
skillsXp.put(PrimarySkillType.UNARMED, result.getFloat(OFFSET_XP + 5));
skillsXp.put(PrimarySkillType.HERBALISM, result.getFloat(OFFSET_XP + 6));
skillsXp.put(PrimarySkillType.EXCAVATION, result.getFloat(OFFSET_XP + 7));
skillsXp.put(PrimarySkillType.ARCHERY, result.getFloat(OFFSET_XP + 8));
skillsXp.put(PrimarySkillType.SWORDS, result.getFloat(OFFSET_XP + 9));
skillsXp.put(PrimarySkillType.AXES, result.getFloat(OFFSET_XP + 10));
skillsXp.put(PrimarySkillType.ACROBATICS, result.getFloat(OFFSET_XP + 11));
skillsXp.put(PrimarySkillType.FISHING, result.getFloat(OFFSET_XP + 12));
skillsXp.put(PrimarySkillType.ALCHEMY, result.getFloat(OFFSET_XP + 13));
// Taming - Unused - result.getInt(OFFSET_COOLDOWNS + 1)
skillsDATS.put(SuperAbilityType.SUPER_BREAKER, result.getInt(OFFSET_COOLDOWNS + 2));
// Repair - Unused - result.getInt(OFFSET_COOLDOWNS + 3)
skillsDATS.put(SuperAbilityType.TREE_FELLER, result.getInt(OFFSET_COOLDOWNS + 4));
skillsDATS.put(SuperAbilityType.BERSERK, result.getInt(OFFSET_COOLDOWNS + 5));
skillsDATS.put(SuperAbilityType.GREEN_TERRA, result.getInt(OFFSET_COOLDOWNS + 6));
skillsDATS.put(SuperAbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_COOLDOWNS + 7));
skillsDATS.put(SuperAbilityType.ARCHERY_SUPER, result.getInt(OFFSET_COOLDOWNS + 8));
skillsDATS.put(SuperAbilityType.SERRATED_STRIKES, result.getInt(OFFSET_COOLDOWNS + 9));
skillsDATS.put(SuperAbilityType.SKULL_SPLITTER, result.getInt(OFFSET_COOLDOWNS + 10));
// Acrobatics - Unused - result.getInt(OFFSET_COOLDOWNS + 11)
skillsDATS.put(SuperAbilityType.BLAST_MINING, result.getInt(OFFSET_COOLDOWNS + 12));
uniqueData.put(UniqueDataType.CHIMAERA_WING_DATS, result.getInt(OFFSET_COOLDOWNS + 13));
skillsDATS.put(SuperAbilityType.TRIDENT_SUPER, result.getInt(OFFSET_COOLDOWNS + 14));
skillsDATS.put(SuperAbilityType.SUPER_SHOTGUN, result.getInt(OFFSET_COOLDOWNS + 15));
//
// Taming - Unused - result.getInt(OFFSET_DATS + 1)
skillsDATS.put(SuperAbilityType.SUPER_BREAKER, result.getInt(OFFSET_DATS + 2));
// Repair - Unused - result.getInt(OFFSET_DATS + 3)
skillsDATS.put(SuperAbilityType.TREE_FELLER, result.getInt(OFFSET_DATS + 4));
skillsDATS.put(SuperAbilityType.BERSERK, result.getInt(OFFSET_DATS + 5));
skillsDATS.put(SuperAbilityType.GREEN_TERRA, result.getInt(OFFSET_DATS + 6));
skillsDATS.put(SuperAbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_DATS + 7));
// Archery - Unused - result.getInt(OFFSET_DATS + 8)
skillsDATS.put(SuperAbilityType.SERRATED_STRIKES, result.getInt(OFFSET_DATS + 9));
skillsDATS.put(SuperAbilityType.SKULL_SPLITTER, result.getInt(OFFSET_DATS + 10));
// Acrobatics - Unused - result.getInt(OFFSET_DATS + 11)
skillsDATS.put(SuperAbilityType.BLAST_MINING, result.getInt(OFFSET_DATS + 12));
uniqueData.put(UniqueDataType.CHIMAERA_WING_DATS, result.getInt(OFFSET_DATS + 13));
try {
scoreboardTipsShown = result.getInt(OFFSET_OTHER + 2);
@@ -1322,52 +1190,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
uuid = UUID.fromString(result.getString(OFFSET_OTHER + 3));
}
catch (Exception e) {
return null;
}
//XPBAR
xpBarStateMap.put(PrimarySkillType.TAMING, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 1)));
xpBarStateMap.put(PrimarySkillType.MINING, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 2)));
xpBarStateMap.put(PrimarySkillType.REPAIR, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 3)));
xpBarStateMap.put(PrimarySkillType.WOODCUTTING, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 4)));
xpBarStateMap.put(PrimarySkillType.UNARMED, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 5)));
xpBarStateMap.put(PrimarySkillType.HERBALISM, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 6)));
xpBarStateMap.put(PrimarySkillType.EXCAVATION, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 7)));
xpBarStateMap.put(PrimarySkillType.ARCHERY, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 8)));
xpBarStateMap.put(PrimarySkillType.SWORDS, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 9)));
xpBarStateMap.put(PrimarySkillType.AXES, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 10)));
xpBarStateMap.put(PrimarySkillType.ACROBATICS, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 11)));
xpBarStateMap.put(PrimarySkillType.FISHING, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 12)));
xpBarStateMap.put(PrimarySkillType.ALCHEMY, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 13)));
xpBarStateMap.put(PrimarySkillType.SALVAGE, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 14)));
xpBarStateMap.put(PrimarySkillType.SMELTING, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 15)));
xpBarStateMap.put(PrimarySkillType.TRIDENTS, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 16)));
xpBarStateMap.put(PrimarySkillType.CROSSBOWS, SkillUtils.asBarState(result.getString(OFFSET_XPBAR + 17)));
//TOGGLE
boolean chatSpy = result.getBoolean(OFFSET_TOGGLE+1);
boolean rankLess = result.getBoolean(OFFSET_TOGGLE+2);
//Build
MMODataBuilder mmoDataBuilder = new MMODataBuilder();
mmoDataBuilder.setSkillLevelValues(skills)
.setSkillExperienceValues(skillsXp)
.setAbilityDeactivationTimestamps(skillsDATS)
.setUniquePlayerData(uniqueData)
.setBarStateMap(xpBarStateMap)
.setPlayerUUID(uuid)
.setPlayerName(playerName)
.setPartyChatSpying(chatSpy)
.setLastLogin(0) //TODO: Program this in properly
.setScoreboardTipsShown(scoreboardTipsShown)
.setLeaderBoardExemption(rankLess);
try {
return mmoDataBuilder.build();
} catch (Exception e) {
e.printStackTrace();
return null;
uuid = null;
}
return new PlayerProfile(playerName, uuid, skills, skillsXp, skillsDATS, scoreboardTipsShown, uniqueData, null);
@@ -1385,7 +1208,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
}
public @NotNull DatabaseType getDatabaseType() {
public DatabaseType getDatabaseType() {
return DatabaseType.SQL;
}
@@ -1412,23 +1235,6 @@ public final class SQLDatabaseManager implements DatabaseManager {
}
}
private void checkUpgradeAddTridentsAndCrossbowsSQL(final Statement statement) throws SQLException {
try {
statement.executeQuery("SELECT 'tridents' FROM `" + tablePrefix +"cooldowns` LIMIT 1");
} catch (SQLException ex) {
mcMMO.p.getLogger().info("Updating SQL DB tables for 2.2 Update....");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `tridents` int(10) NOT NULL DEFAULT '0'");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `crossbows` int(10) NOT NULL DEFAULT '0'");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `tridents` int(10) NOT NULL DEFAULT '0'");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD `crossbows` int(10) NOT NULL DEFAULT '0'");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `tridents` int(10) NOT NULL DEFAULT '0'");
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "experience` ADD `crossbows` int(10) NOT NULL DEFAULT '0'");
}
}
private void checkUpgradeAddAlchemy(final Statement statement) throws SQLException {
try {
statement.executeQuery("SELECT `alchemy` FROM `" + tablePrefix + "skills` LIMIT 1");
@@ -1504,11 +1310,11 @@ public final class SQLDatabaseManager implements DatabaseManager {
resultSet = statement.executeQuery("SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'");
resultSet.last();
if (resultSet.getRow() != SkillTools.getNonChildSkills().size()) {
if (resultSet.getRow() != SkillTools.NON_CHILD_SKILLS.size()) {
mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
for (PrimarySkillType primarySkillType : SkillTools.getNonChildSkills()) {
String skill_name = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH);
for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) {
String skill_name = skill.name().toLowerCase(Locale.ENGLISH);
try {
statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + skill_name + "` (`" + skill_name + "`) USING BTREE");
@@ -1772,7 +1578,7 @@ public final class SQLDatabaseManager implements DatabaseManager {
@Override
public void onDisable() {
mcMMO.p.getLogger().info("Releasing connection pool resource...");
LogUtils.debug(mcMMO.p.getLogger(), "Releasing connection pool resource...");
miscPool.close();
loadPool.close();
savePool.close();
@@ -1865,9 +1671,4 @@ public final class SQLDatabaseManager implements DatabaseManager {
" CHARACTER SET utf8mb4\n" +
" COLLATE utf8mb4_unicode_ci;";
}
@Override
public void removeCache(@NotNull UUID uuid) {
cachedUserIDs.remove(uuid);
}
}

View File

@@ -29,8 +29,7 @@ public class FlatFileDataUtil {
/*
* First fix the bad data values if they exist
*/
if(dataContainer instanceof BadCategorizedFlatFileData) {
BadCategorizedFlatFileData badData = (BadCategorizedFlatFileData) dataContainer;
if(dataContainer instanceof BadCategorizedFlatFileData badData) {
splitData = repairBadData(dataContainer.getSplitData(), badData.getBadDataIndexes());
} else {
splitData = dataContainer.getSplitData();

View File

@@ -37,8 +37,7 @@ public class LevelUpBroadcastPredicate<T extends CommandSender> implements Predi
return false;
}
if(t instanceof Player) {
Player listeningPlayer = (Player) t;
if(t instanceof Player listeningPlayer) {
//Party Member Check
if(mcMMO.p.getGeneralConfig().isLevelUpBroadcastsPartyMembersOnly()) {
@@ -75,7 +74,7 @@ public class LevelUpBroadcastPredicate<T extends CommandSender> implements Predi
}
//Visibility checks
if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer())) {
if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) {
return false; //Player who leveled should be invisible to this player so don't send the message
}

View File

@@ -0,0 +1,7 @@
package com.gmail.nossr50.datatypes;
public enum MobHealthbarType {
HEARTS,
BAR,
DISABLED
}

View File

@@ -37,8 +37,7 @@ public class PowerLevelUpBroadcastPredicate<T extends CommandSender> implements
return false;
}
if(t instanceof Player) {
Player listeningPlayer = (Player) t;
if(t instanceof Player listeningPlayer) {
//Party Member Check
if(mcMMO.p.getGeneralConfig().isPowerLevelUpBroadcastsPartyMembersOnly()) {
@@ -75,7 +74,7 @@ public class PowerLevelUpBroadcastPredicate<T extends CommandSender> implements
}
//Visibility checks
if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer())) {
if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) {
return false; //Player who leveled should be invisible to this player so don't send the message
}

View File

@@ -14,7 +14,6 @@ public enum UpgradeType {
DROP_NAME_UNIQUENESS,
ADD_SKILL_TOTAL,
ADD_UNIQUE_PLAYER_DATA,
ADD_SQL_2_2,
FIX_SPELLING_NETHERITE_SALVAGE,
FIX_SPELLING_NETHERITE_REPAIR,
FIX_NETHERITE_SALVAGE_QUANTITIES,

View File

@@ -1,9 +0,0 @@
package com.gmail.nossr50.datatypes.experience;
import com.neetgames.mcmmo.experience.ExperienceProcessor;
//TODO: T&C Write implementation, this should be the exact same way OnlineExperienceProcessor handles stuff but without sending player messages or sounds and stuff like that
//TODO: Is this needed? Maybe just make OnlineExperienceProcessor handle both in a clean way
public class OfflineExperienceProcessor implements ExperienceProcessor {
}

View File

@@ -1,345 +0,0 @@
package com.gmail.nossr50.datatypes.experience;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.player.PlayerData;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.party.ShareHandler;
import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.experience.ExperienceUtils;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.skills.PerksUtils;
import com.gmail.nossr50.util.sounds.SoundManager;
import com.gmail.nossr50.util.sounds.SoundType;
import com.neetgames.mcmmo.exceptions.UnknownSkillException;
import com.neetgames.mcmmo.experience.ExperienceProcessor;
import com.neetgames.mcmmo.experience.XPGainReason;
import com.neetgames.mcmmo.experience.XPGainSource;
import com.neetgames.mcmmo.party.Party;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Set;
public class OnlineExperienceProcessor implements ExperienceProcessor {
private boolean isUsingUnarmed = false; //Gross but it works
private final @NotNull Player playerRef;
private final @NotNull PlayerData mmoPlayerData;
public OnlineExperienceProcessor(@NotNull Player playerRef, @NotNull PlayerData playerData) {
this.playerRef = playerRef;
this.mmoPlayerData = playerData;
}
public int getPowerLevel() {
int powerLevel = 0;
Map<PrimarySkillType, Integer> primarySkillTypeLevelMap = mmoPlayerData.getSkillLevelMap();
for (PrimarySkillType primarySkillType : primarySkillTypeLevelMap.keySet()) {
powerLevel += primarySkillTypeLevelMap.get(primarySkillType);
}
return powerLevel;
}
public float getSkillXpLevelRaw(@NotNull PrimarySkillType primarySkillType) {
return mmoPlayerData.getSkillsExperienceMap().get(primarySkillType);
}
public int getSkillXpValue(@NotNull PrimarySkillType primarySkillType) {
if(primarySkillType.isChildSkill()) {
return 0;
}
return (int) Math.floor(getSkillXpLevelRaw(primarySkillType));
}
public void setSkillXpValue(@NotNull PrimarySkillType primarySkillType, float xpLevel) {
if (primarySkillType.isChildSkill()) {
return;
}
mmoPlayerData.getSkillsExperienceMap().put(primarySkillType, xpLevel);
}
public float levelUp(@NotNull PrimarySkillType primarySkillType) {
float xpRemoved = getExperienceToNextLevel(primarySkillType);
setSkillLevel(primarySkillType, getSkillLevel(primarySkillType) + 1);
setSkillXpValue(primarySkillType, getSkillXpValue(primarySkillType) - xpRemoved);
return xpRemoved;
}
public boolean hasReachedLevelCap(@NotNull PrimarySkillType primarySkillType) {
if(hasReachedPowerLevelCap())
return true;
return getSkillLevel(primarySkillType) >= Config.getInstance().getLevelCap(primarySkillType);
}
public boolean hasReachedPowerLevelCap() {
return this.getPowerLevel() >= Config.getInstance().getPowerLevelCap();
}
public void beginXpGain(@NotNull PrimarySkillType primarySkillType, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) {
if (xp <= 0.0) {
return;
}
if (PrimarySkillType.isChildSkill(primarySkillType)) {
Set<RootSkill> parentSkills = FamilyTree.getParentSkills(primarySkillType);
float splitXp = xp / parentSkills.size();
for (RootSkill parentSkill : parentSkills) {
beginXpGain(parentSkill, splitXp, xpGainReason, xpGainSource);
}
return;
}
//TODO: The logic here is so stupid... rewrite later
// Return if the experience has been shared
if (mmoPlayer.getParty() != null && ShareHandler.handleXpShare(xp, mmoPlayer, mmoPlayer.getParty(), primarySkillType, ShareHandler.getSharedXpGainReason(xpGainReason))) {
return;
}
beginUnsharedXpGain(primarySkillType, xp, xpGainReason, xpGainSource);
}
public void beginUnsharedXpGain(@NotNull PrimarySkillType primarySkillType, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) {
if(Misc.adaptPlayer(mmoPlayer).getGameMode() == GameMode.CREATIVE)
return;
ExperienceUtils.applyXpGain(mmoPlayer, primarySkillType, modifyXpGain(primarySkillType, xp), xpGainReason, xpGainSource);
Party party = mmoPlayer.getParty();
if (party != null) {
if (!Config.getInstance().getPartyXpNearMembersNeeded() || !mcMMO.getPartyManager().getNearMembers(mmoPlayer).isEmpty()) {
party.getPartyExperienceManager().applyXpGain(modifyXpGain(primarySkillType, xp));
}
}
}
public int getSkillLevel(@NotNull PrimarySkillType primarySkillType) {
return PrimarySkillType.isChildSkill(primarySkillType) ? getChildSkillLevel(primarySkillType) : getSkillLevel(primarySkillType);
}
public int getExperienceToNextLevel(@NotNull PrimarySkillType primarySkillType) {
if(PrimarySkillType.isChildSkill(primarySkillType)) {
return 0;
}
int level = (ExperienceConfig.getInstance().getCumulativeCurveEnabled()) ? getPowerLevel() : getSkillLevel(primarySkillType);
FormulaType formulaType = ExperienceConfig.getInstance().getFormulaType();
return mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType);
}
public int getChildSkillLevel(@NotNull PrimarySkillType primarySkillType) {
Set<RootSkill> parents = FamilyTree.getParentSkills(primarySkillType);
int sum = 0;
for (RootSkill parentIdentity : parents) {
sum += getSkillLevel(parentIdentity);
}
return sum / parents.size();
}
public void removeXp(@NotNull PrimarySkillType skill, int xp) {
if (skill.isChildSkill()) {
return;
}
setSkillXpValue(skill, getSkillXpValue(skill) - xp);
}
public void removeXp(PrimarySkillType skill, float xp) {
if (skill.isChildSkill()) {
return;
}
setSkillXpValue(skill, getSkillXpValue(skill) - xp);
}
public void setSkillLevel(@NotNull PrimarySkillType primarySkillType, int level) {
if (primarySkillType.isChildSkill()) {
return;
}
//Don't allow levels to be negative
if(level < 0)
level = 0;
setSkillLevel(primarySkillType, level);
setSkillXpValue(primarySkillType, 0F);
}
public void addLevels(@NotNull PrimarySkillType primarySkillType, int levels) {
setSkillLevel(primarySkillType, getSkillLevel(primarySkillType) + levels);
}
public void addXp(@NotNull PrimarySkillType primarySkillType, float xp) {
if (primarySkillType.isChildSkill()) {
Set<RootSkill> parentSkills = FamilyTree.getParents(primarySkillType);
float dividedXP = (xp / parentSkills.size());
for (RootSkill parentSkill : parentSkills) {
setSkillXpValue(parentSkill, getSkillXpValue(parentSkill) + dividedXP);
}
}
else {
setSkillXpValue(primarySkillType, getSkillXpValue(primarySkillType) + xp);
}
}
public float getRegisteredXpGain(@NotNull PrimarySkillType primarySkillType) {
float xp = 0F;
if (get(primarySkillType) != null) { //??
xp = rollingSkillsXp.get(primarySkillType);
}
return xp;
}
public void registerXpGain(@NotNull PrimarySkillType primarySkillType, float xp) {
gainedSkillsXp.add(new SkillXpGain(primarySkillType, xp));
rollingSkillsXp.put(primarySkillType, getRegisteredXpGain(primarySkillType) + xp);
}
public void purgeExpiredXpGains() {
SkillXpGain gain;
while ((gain = gainedSkillsXp.poll()) != null) {
rollingSkillsXp.put(gain.getSkill(), getRegisteredXpGain(gain.getSkill()) - gain.getXp());
}
}
private float modifyXpGain(@NotNull PrimarySkillType primarySkillType, float xp) {
if ((primarySkillType.getMaxLevel() <= getSkillLevel(primarySkillType)) || (Config.getInstance().getPowerLevelCap() <= getPowerLevel())) {
return 0;
}
xp = (float) (xp / primarySkillType.getXpModifier() * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier());
return PerksUtils.handleXpPerks(Misc.adaptPlayer(mmoPlayer), xp, primarySkillType);
}
public double getProgressInCurrentSkillLevel(@NotNull PrimarySkillType primarySkillType) throws UnknownSkillException
{
if(PrimarySkillType.isChildSkill(primarySkillType)) {
return 1.0D;
}
double currentXP = getSkillXpValue(primarySkillType);
double maxXP = getExperienceToNextLevel(primarySkillType);
return (currentXP / maxXP);
}
public void setUsingUnarmed(boolean bool) {
isUsingUnarmed = bool;
}
public void applyXpGain(@NotNull PrimarySkillType primarySkillType, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) {
//Only check for permissions if the player is online, otherwise just assume a command is being executed by an admin or some other means and add the XP
if (!Permissions.skillEnabled(mmoPlayer.getPlayer(), PrimarySkillType.getSkill(primarySkillType))) {
return;
}
if (PrimarySkillType.isChildSkill(primarySkillType)) {
Set<RootSkill> parentSkills = FamilyTree.getParentSkills(primarySkillType);
for (RootSkill parentSkill : parentSkills) {
applyXpGain(parentSkill, xp / parentSkills.size(), xpGainReason, xpGainSource);
}
return;
}
if (!EventUtils.handleXpGainEvent(Misc.adaptPlayer(mmoPlayer), primarySkillType, xp, xpGainReason)) {
return;
}
setUsingUnarmed(primarySkillType == PrimarySkillType.UNARMED);
updateLevelStats(primarySkillType, xpGainReason, xpGainSource);
}
public void processPostXpEvent(@NotNull PrimarySkillType primarySkillType, @NotNull XPGainSource xpGainSource)
{
/*
* Everything in this method requires an online player, so if they aren't online we don't waste our time
*/
if(mmoPlayer == null)
return;
//Check if they've reached the power level cap just now
if(hasReachedPowerLevelCap()) {
NotificationManager.sendPlayerInformationChatOnly(Misc.adaptPlayer(mmoPlayer), "LevelCap.PowerLevel", String.valueOf(Config.getInstance().getPowerLevelCap()));
} else if(hasReachedLevelCap(primarySkillType)) {
NotificationManager.sendPlayerInformationChatOnly(Misc.adaptPlayer(mmoPlayer), "LevelCap.Skill", String.valueOf(Config.getInstance().getLevelCap(primarySkillType)), primarySkillType.getRawSkillName());
}
//Updates from Party sources
if(xpGainSource == XPGainSource.PARTY_MEMBERS && !ExperienceConfig.getInstance().isPartyExperienceBarsEnabled())
return;
//Updates from passive sources (Alchemy, Smelting, etc...)
if(xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled())
return;
mmoPlayer.updateXPBar(primarySkillType);
}
public void updateLevelStats(@NotNull PrimarySkillType primarySkillType, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) {
if(hasReachedLevelCap(primarySkillType))
return;
if (getSkillXpLevelRaw(primarySkillType) < getExperienceToNextLevel(primarySkillType)) {
processPostXpEvent(primarySkillType, xpGainSource);
return;
}
int levelsGained = 0;
float xpRemoved = 0;
while (getSkillXpLevelRaw(primarySkillType) >= getExperienceToNextLevel(primarySkillType)) {
if (hasReachedLevelCap(primarySkillType)) {
setSkillXpValue(primarySkillType, 0);
break;
}
xpRemoved += levelUp(primarySkillType);
levelsGained++;
}
if (EventUtils.tryLevelChangeEvent(Misc.adaptPlayer(mmoPlayer), primarySkillType, levelsGained, xpRemoved, true, xpGainReason)) {
return;
}
if (Config.getInstance().getLevelUpSoundsEnabled()) {
SoundManager.sendSound(Misc.adaptPlayer(mmoPlayer), Misc.adaptPlayer(mmoPlayer).getLocation(), SoundType.LEVEL_UP);
}
/*
* Check to see if the player unlocked any new skills
*/
NotificationManager.sendPlayerLevelUpNotification(mmoPlayer, primarySkillType, levelsGained, getSkillLevel(primarySkillType));
//UPDATE XP BARS
processPostXpEvent(primarySkillType, xpGainSource);
}
}

View File

@@ -0,0 +1,21 @@
package com.gmail.nossr50.datatypes.experience;
public enum XPGainReason {
PVP,
PVE,
VAMPIRISM,
SHARED_PVP,
SHARED_PVE,
COMMAND,
UNKNOWN;
public static XPGainReason getXPGainReason(String reason) {
for (XPGainReason type : values()) {
if (type.name().equalsIgnoreCase(reason)) {
return type;
}
}
return null;
}
}

View File

@@ -0,0 +1,10 @@
package com.gmail.nossr50.datatypes.experience;
public enum XPGainSource {
SELF,
VAMPIRISM, //From Vampirism kills
PASSIVE, //Smelting, Brewing, etc...
PARTY_MEMBERS, //From other members of a party
COMMAND,
CUSTOM, //Outside Sources
}

View File

@@ -1,5 +1,7 @@
package com.gmail.nossr50.datatypes.interactions;
import org.jetbrains.annotations.NotNull;
/**
* This class helps define the types of information interactions we will have with players
*/
@@ -23,14 +25,14 @@ public enum NotificationType {
CHAT_ONLY("ChatOnly"),
PARTY_MESSAGE("PartyMessage");
final String niceName;
private final String niceName;
NotificationType(String niceName)
{
NotificationType(@NotNull String niceName) {
this.niceName = niceName;
}
@Override
public String toString() {
public @NotNull String toString() {
return niceName;
}}
}
}

View File

@@ -4,8 +4,8 @@ public class McMMOUrl {
public static final String urlWebsite = "https://www.mcmmo.org";
public static final String urlDiscord = "https://discord.gg/bJ7pFS9";
public static final String urlPatreon = "https://www.patreon.com/nossr50";
public static final String urlWiki = "https://www.mcmmo.org/wiki/";
public static final String urlSpigot = "http://spigot.mcmmo.org";
public static final String urlWiki = "https://wiki.mcmmo.org/";
public static final String urlSpigot = "https://spigot.mcmmo.org";
public static final String urlTranslate = "https://translate.mcmmo.org/";
public static String getUrl(McMMOWebLinks webLinks)

View File

@@ -1,17 +0,0 @@
package com.gmail.nossr50.datatypes.meta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
public class ProjectileOriginMeta extends FixedMetadataValue {
/**
* Initializes a FixedMetadataValue with an Object
*
* @param owningPlugin the {@link Plugin} that created this metadata value
* @param value the value assigned to this metadata value
*/
public ProjectileOriginMeta(@NotNull Plugin owningPlugin, int value) {
super(owningPlugin, value);
}
}

Some files were not shown because too many files have changed in this diff Show More