diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index f3e796fc..a68ab4d8 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -8,13 +8,9 @@ name: Java CI with Gradle on: - push: - branches: [ "v2.x.x" ] - pull_request: - branches: [ "v2.x.x" ] release: types: [published] - branches: [ "v2.x.x" ] + branches: [ "v1.x.x" ] concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} @@ -27,7 +23,7 @@ jobs: contents: write env: - MODRINTH_VERSIONS: '["1.21.x", "26.1.x", "26.2.x"]' + MODRINTH_VERSIONS: '["1.18.x", "1.19.x", "1.20.x"]' MODRINTH_PLATFORMS: '["spigot", "paper", "purpur", "folia"]' steps: @@ -107,27 +103,6 @@ jobs: build/libs/${{ env.ONLINE_JAR_NAME }} build/libs/${{ env.OFFLINE_JAR_NAME }} - - name: Hangar release - if: ${{ (github.event_name == 'release' || github.event_name == 'push') && github.repository_owner == 'alexcrea' && success() }} - env: - HANGAR_API_TOKEN: ${{ secrets.HANGAR_API_TOKEN }} - RELEASE_CHANGELOG: ${{ github.event.release.body }} - run: ./gradlew publishAllPublicationsToHangar --stacktrace - - - name: Modrinth publish alpha - if: ${{ github.event_name == 'push' && github.repository_owner == 'alexcrea' && success() }} - uses: cloudnode-pro/modrinth-publish@v2 - with: - token: ${{ secrets.MODRINTH_TOKEN }} - project: S75Ueiq9 - name: dev-${{ env.SMALL_COMMIT_HASH }} - version: dev-${{ env.SMALL_COMMIT_HASH }} - loaders: ${{ env.MODRINTH_PLATFORMS }} - game-versions: ${{ env.MODRINTH_VERSIONS }} - channel: alpha - files: build/libs/${{ env.ONLINE_JAR_NAME }} - changelog: ${{ github.event.head_commit.message }} - - name: Modrinth publish release if: ${{ github.event_name == 'release' && github.repository_owner == 'alexcrea' && success() }} uses: cloudnode-pro/modrinth-publish@v2 @@ -148,8 +123,7 @@ jobs: with: webhook-url: ${{ secrets.RELEASE_WEBHOOK_URL }} content: | - ${{ github.event.release.prerelease == false && '<@&1338546156325568642>' || '<@&1352296092989001768>' }} - # New ${{ github.event.release.prerelease && 'beta ' || '' }}version of custom anvil ! <:CustomAnvil:1262550667986342001>([Modrinth](https://modrinth.com/plugin/customanvil), [Hangar](https://hangar.papermc.io/alexcrea/CustomAnvil) and [GitHub](${{ github.event.release.html_url }}) links) - -# note: automated release. spigot is not uploaded yet. + <@&1525259349423947867> + # New bugfix for CustomAnvil v1 ! <:CustomAnvil:1262550667986342001> [Modrinth](https://modrinth.com/plugin/customanvil) and [GitHub](${{ github.event.release.html_url }}) links ${{ github.event.release.body }} diff --git a/README.md b/README.md index d568fde1..27d08fac 100644 --- a/README.md +++ b/README.md @@ -73,9 +73,10 @@ See the [Compatibility list](https://github.com/alexcrea/CustomAnvil/blob/v1.x.x One of the configurations allow displaying price about 40 and removing Too Expensive. \ By how the minecraft client work: price above 40 can only be displayed green, even if the player does not own enough experience level. -You do not need Protocolib unless you are using spigot above in 26.1 or above \ - -But you should wait for update or announcement for new version containing new enchantable item or new enchantments. +spigot version 1.18 to 1.21.11 do not need any ProtocoLib dependency. (26.1.0 or above requires it) \ +Any recent paper version also are supported for this feature. +But you should wait for update for new version containing new enchantable item or new enchantments if any of this got added. +Else it is, likely, fine to use the current version you are ussing on a new paper version ### For custom enchantment plugin developers For information about the API, please refer to [the Wiki](https://github.com/alexcrea/CustomAnvil/wiki) \ diff --git a/build.gradle.kts b/build.gradle.kts index 2cc60a02..fcde08c8 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,24 +5,23 @@ import groovy.util.NodeList import io.papermc.hangarpublishplugin.model.HangarPublication import io.papermc.hangarpublishplugin.model.Platforms import org.jetbrains.kotlin.gradle.dsl.JvmTarget -import java.io.ByteArrayOutputStream plugins { - kotlin("jvm") version "2.3.0" + kotlin("jvm") version "2.4.0" java - id("org.jetbrains.dokka").version("1.9.20") - id("com.gradleup.shadow").version("9.3.0") + id("org.jetbrains.dokka").version("2.2.0") + id("com.gradleup.shadow").version("9.6.1") // Maven publish `maven-publish` signing - id("cn.lalaki.central").version("1.2.8") + id("cn.lalaki.central").version("2.0.8") // Paper - id("io.papermc.paperweight.userdev") version "2.0.0-beta.17" apply false - id("io.papermc.hangar-publish-plugin") version "0.1.2" + id("io.papermc.paperweight.userdev") version "2.0.0-beta.21" apply false + id("io.papermc.hangar-publish-plugin") version "0.1.4" } group = "xyz.alexcrea" -version = "2.0.0" +version = "1.20.1" val isDevBuild = System.getenv("SMALL_COMMIT_HASH") != null val isPreRelease = System.getenv("IS_GITHUB_PRERELEASE") == "true" @@ -52,7 +51,7 @@ val reobfNMS = providers.gradleProperty("subprojects.reobfnms") dependencies { // Spigot api - compileOnly("org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT") + compileOnly("org.spigotmc:spigot-api:1.18-R0.1-SNAPSHOT") // fast stats implementation("dev.faststats.metrics:bukkit:0.29.0") @@ -166,7 +165,7 @@ allprojects { kotlin { compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) jvmTarget.set(JvmTarget.JVM_16) } } @@ -178,7 +177,10 @@ tasks { fun ShadowJar.configureBaseShadow(suffix: String, libraries: Array) { val processedSuffix = if(suffix.isEmpty()) "" else "-$suffix" - val name = "${rootProject.name}-${effectiveVersion}${processedSuffix}.jar" + val version = effectiveVersion + val name = "${rootProject.name}-${version}${processedSuffix}.jar" + val librariesExpendTo = libraries.joinToString(transform = { "\"$it\"" }) + archiveFileName.set(name) // Shadow necessary dependency @@ -187,8 +189,8 @@ tasks { filesMatching("plugin.yml") { expand( - "version" to effectiveVersion + processedSuffix, - "libraries" to libraries.joinToString(transform = { "\"$it\"" }), + "version" to version + processedSuffix, + "libraries" to librariesExpendTo, ) } @@ -200,7 +202,7 @@ tasks { shadowJar { configureBaseShadow("", arrayOf( - "org.jetbrains.kotlin:kotlin-stdlib:2.3.0", + "org.jetbrains.kotlin:kotlin-stdlib:2.4.0", "net.kyori:adventure-text-minimessage:4.25.0", "net.kyori:adventure-text-serializer-plain:4.25.0", "net.kyori:adventure-text-serializer-legacy:4.25.0", @@ -212,7 +214,7 @@ tasks { exclude("net/kyori/**") } - val offlineJar by registering(ShadowJar::class) { + val offlineJar = register("offlineJar") { configureBaseShadow("offline", emptyArray()) from(sourceSets.main.get().output) @@ -226,12 +228,12 @@ tasks { } -val sourcesJar by tasks.registering(Jar::class) { +val sourcesJar = tasks.register("sourcesJar") { archiveClassifier.set("sources") from(kotlin.sourceSets.main.get().kotlin) } -val javadocJar by tasks.registering(Jar::class, fun Jar.() { +val javadocJar = tasks.register("javadocJar", fun Jar.() { group = JavaBasePlugin.DOCUMENTATION_GROUP description = "Assembles Javadoc JAR" archiveClassifier.set("javadoc") @@ -355,51 +357,39 @@ publishing { } // hangar publish - -fun executeGitCommand(vararg command: String): String { - val byteOut = ByteArrayOutputStream() - exec { - commandLine = listOf("git", *command) - standardOutput = byteOut - } - return byteOut.toString(Charsets.UTF_8.name()).trim() +fun latestCommitMessage(): Provider { + return providers.exec { + commandLine("git", "log", "-1", "--pretty=%B") + }.standardOutput.asText.map(String::trim) } - -fun latestCommitMessage(): String { - return executeGitCommand("log", "-1", "--pretty=%B") -} - -fun changelog(isOnline: Boolean): String { - var changelog = if(isDevBuild) latestCommitMessage() - else System.getenv("RELEASE_CHANGELOG") - - if(!isOnline) { - changelog = "This is an offline version of the plugin. \\\n" + - "This mean that this plugin libraries are shaded into this plugin \\\n" + - "You likely want to use the normal version of this plugin\n\n" + changelog - } - - if(changelog == null || changelog.isEmpty()) { - changelog = "empty changelog" - } +fun changelog(isOnline: Boolean): Provider { + val changelog = if(isDevBuild) latestCommitMessage() + else providers.environmentVariable("RELEASE_CHANGELOG") return changelog + .filter{!it.isEmpty()} + .map { + if(!isOnline) + return@map "This is an offline version of the plugin. \\\n" + + "This mean that this plugin libraries are shaded into this plugin \\\n" + + "You likely want to use the normal version of this plugin\n\n" + it + else return@map it + }.orElse("empty changelog") } hangarPublish { - fun HangarPublication.configure(isOnline: Boolean, devChannel: String?, releaseChannel: String) { + fun HangarPublication.configure(isOnline: Boolean, devChannel: String, releaseChannel: String) { var versionName = effectiveVersion if(isPreRelease) versionName+= "-pre" if(!isOnline) versionName+= "-offline" version.set(versionName) - var releaseChannel = if (isDevBuild || isPreRelease) devChannel else releaseChannel - if(releaseChannel == null) return - channel.set(releaseChannel) + channel.set(if (isDevBuild || isPreRelease) devChannel else releaseChannel) changelog.set(changelog(isOnline)) + id.set("CustomAnvil") apiKey.set(System.getenv("HANGAR_API_TOKEN")) @@ -448,10 +438,8 @@ hangarPublish { configure(true, "DevSnapshot", "Release") } - if(!isDevBuild) { - publications.register("offline") { - configure(false, null, "OfflineRelease") - } + publications.register("offline") { + configure(false, "OfflineSnapshot", "OfflineRelease") } } diff --git a/defaultconfigs/1.18/README.md b/defaultconfigs/1.18/README.md new file mode 100644 index 00000000..d390f3f5 --- /dev/null +++ b/defaultconfigs/1.18/README.md @@ -0,0 +1,6 @@ +### Default Plugin's Configurations For 1.18 to 1.20.6 +- [config.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/config.yml) +- [enchant_conflict.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/enchant_conflict.yml) +- [item_groups.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/item_groups.yml) +- [unit_repair_item.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/unit_repair_item.yml) +- [custom_recipes.yml](https://github.com/alexcrea/CustomAnvil/blob/master/defaultconfigs/1.18/custom_recipes.yml) diff --git a/defaultconfigs/1.18/config.yml b/defaultconfigs/1.18/config.yml new file mode 100644 index 00000000..7574edd8 --- /dev/null +++ b/defaultconfigs/1.18/config.yml @@ -0,0 +1,472 @@ +# +# It is recommended that you use /ca config to edit theses config. +# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! +# + +# What service of metric should custom anvil use +# Custom anvil collect generic information like server minecraft version, type, etc... +# It can also collect error information if error is happening (currently faststats only) +# It can also be disabled +# Please refer to README for public metric link +# Possible options: auto, bstat, faststats, disabled (auto by default) +metric_type: auto + +# Allow to report errors made caused by this plugin (only for faststats) +# This allows me to fix potentials issue that I'm not aware of +# Accept true or false (true by default) +metric_collect_errors: true + +# All anvil cost will be capped to limit_repair_value if enabled. +# +# In other words: +# For any anvil cost greater than limit_repair_value, Cost will be set to limit_repair_value. +limit_repair_cost: false + +# Max cost value the Anvil can get to. +# +# Valid values include 0 to 1000. +# Cost will be displayed as "Too Expensive": +# - If Cost is above 39 +# - And replace_too_expensive is disabled (false) +limit_repair_value: 39 + +# Whether the anvil's cost limit should be removed entirely. +# +# The anvil will still visually display "Too Expensive" if "replace_too_expensive" is disabled +# However, the action will be completable if xp requirement is meet. +remove_repair_limit: false + +# Whenever anvil cost is above 39 should display the true price and not "Too Expensive". +# +# However, when bypassing "Too Expensive", anvil price will be displayed as Green. +# If the action is not completable, the cost will still be displayed as "Too expensive". +# That mean you also need to change other settings like remove_repair_limit or limit_repair_cost. +# +# Require ProtocoLib. +replace_too_expensive: false + +# XP Level amount added to the anvil when the item is repaired by another item of the same type +# +# Valid values include 0 to 1000 +item_repair_cost: 2 + +# XP Level amount added to the anvil when the item is renamed +# +# Valid values include 0 to 1000 +item_rename_cost: 1 + +# XP Level amount added to the anvil when the item is repaired by an "unit" +# For example: a Diamond on a Diamond Sword +# What's considered unit for what can be edited on the unit repair configuration. +# +# Valid values include 0 to 1000 +unit_repair_cost: 1 + +# XP Level amount added to the anvil when a sacrifice enchantment +# conflict with one of the left item enchantment +# +# Valid values include 0 to 1000 +sacrifice_illegal_enchant_cost: 1 + +# Allow using color code and hexadecimal color. +# +# Color code are prefixed by "&" and hexadecimal color by "#". +# Color code will not be applied if it colors nothing. "&&" can be used to write "&". +# For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/ +allow_color_code: false +allow_hexadecimal_color: false +allow_minimessage: false + +# This enables restricting color code for player having specific permission +# It requires allow_color_code enabled for... obvious reasons +# +# For example: if player want to use "&aHello" it will be required that the player has +# the permission "ca.color.code.a" as he used the color code "a" +# In general permission to give to the player is "ca.color.code.[code]" +# where [code] is the color code you wish to allow the player +# +# It is kinda of useless when minimessage is supported as players would be able to bypass +# that using the equivalent minimessage tag +per_color_code_permission: false + +# Toggle if color should only be applicable if the player a certain permission. +# +# permission are "ca.color.code" for use of color code and "ca.color.hex" for use of hexadecimal color. +permission_needed_for_color: true + +# Xp cost if the player use color in the items name on rename. +# +# Valid values include 0 to 1000. +use_of_color_cost: 0 + +# Dialogue rename menu make use of dialog menu to allow bigger rename +# You can also change the maximum size and set it to -1 or less for maximum +# +# This feature only work on paper 1.21.7 or later +# +# At the moment only english is available for this menu... sorry ! +# +# CustomAnvil use "ca.rename.dialog" when permission +enable_dialog_rename: false +dialog_rename_max_size: 256 +permission_needed_for_dialog_rename: false + +# This allows custom anvil to not "guess" the text used for rename but store it in the item +# It will make item stackable only and only if it had used the same rename text +# +# For practical reason. this only work when dialog rename is enabled +dialog_rename_keep_user_text: true + +# Also count left item enchantments for the final price +include_left_enchantment_for_cost: false + +# Override limits for specific enchants +# +# Enchantments not listed here will use the value of default_limit +# +# Overrides provided default from aqua_affinity to depth_strider won't change effect with extra levels +# +# Valid range of 0 - 255 for each enchantment +# -1 mean keep default +enchant_limits: + minecraft:aqua_affinity: 1 + minecraft:binding_curse: 1 + minecraft:channeling: 1 + minecraft:flame: 1 + minecraft:infinity: 1 + minecraft:mending: 1 + minecraft:multishot: 1 + minecraft:silk_touch: 1 + minecraft:vanishing_curse: 1 + minecraft:depth_strider: 3 # anything more than 3 is treated as 3 by the game + minecraft:protection: 4 + minecraft:fire_protection: 4 + minecraft:blast_protection: 4 + minecraft:projectile_protection: 4 + minecraft:feather_falling: 4 + minecraft:thorns: 3 + minecraft:respiration: 3 + minecraft:sharpness: 5 + minecraft:smite: 5 + minecraft:bane_of_arthropods: 5 + minecraft:knockback: 2 + minecraft:fire_aspect: 2 + minecraft:looting: 3 + minecraft:sweeping: 3 + minecraft:sweeping_edge: 3 + minecraft:efficiency: 5 + minecraft:unbreaking: 3 + minecraft:fortune: 3 + minecraft:power: 5 + minecraft:punch: 2 + minecraft:luck_of_the_sea: 3 + minecraft:lure: 3 + minecraft:frost_walker: 2 + minecraft:impaling: 5 + minecraft:riptide: 3 + minecraft:loyalty: 3 + minecraft:piercing: 4 + minecraft:quick_charge: 3 + minecraft:soul_speed: 3 + minecraft:swift_sneak: 3 + +# Multipliers used to calculate the enchantment's value in repair/combining +# +# Values here are pulled from the minecraft wiki: +# https://minecraft.wiki/w/Anvil_mechanics#Costs_for_combining_enchantments +# +# If an enchantment is missing values here, or is less than 0, it will default to 0 +# +# Calculated as: [Enchantment lvl] * [multiplier] +# +# With default values protection 4 would have a value of 4 when +# coming from either a book (4 * 1) or an item (4 * 1) +enchant_values: + minecraft:aqua_affinity: + item: 4 + book: 2 + minecraft:bane_of_arthropods: + item: 2 + book: 1 + minecraft:binding_curse: + item: 8 + book: 4 + minecraft:blast_protection: + item: 4 + book: 2 + minecraft:channeling: + item: 8 + book: 4 + minecraft:depth_strider: + item: 4 + book: 2 + minecraft:efficiency: + item: 1 + book: 1 + minecraft:flame: + item: 4 + book: 2 + minecraft:feather_falling: + item: 2 + book: 1 + minecraft:fire_aspect: + item: 4 + book: 2 + minecraft:fire_protection: + item: 2 + book: 1 + minecraft:fortune: + item: 4 + book: 2 + minecraft:frost_walker: + item: 4 + book: 2 + minecraft:impaling: + item: 4 + book: 2 + minecraft:infinity: + item: 8 + book: 4 + minecraft:knockback: + item: 2 + book: 1 + minecraft:looting: + item: 4 + book: 2 + minecraft:loyalty: + item: 1 + book: 1 + minecraft:luck_of_the_sea: + item: 4 + book: 2 + minecraft:lure: + item: 4 + book: 2 + minecraft:mending: + item: 4 + book: 2 + minecraft:multishot: + item: 4 + book: 2 + minecraft:piercing: + item: 1 + book: 1 + minecraft:power: + item: 1 + book: 1 + minecraft:projectile_protection: + item: 2 + book: 1 + minecraft:protection: + item: 1 + book: 1 + minecraft:punch: + item: 4 + book: 2 + minecraft:quick_charge: + item: 2 + book: 1 + minecraft:respiration: + item: 4 + book: 2 + minecraft:riptide: + item: 4 + book: 2 + minecraft:silk_touch: + item: 8 + book: 4 + minecraft:sharpness: + item: 1 + book: 1 + minecraft:smite: + item: 2 + book: 1 + minecraft:soul_speed: + item: 8 + book: 4 + minecraft:swift_sneak: + item: 8 + book: 4 + minecraft:sweeping: + item: 4 + book: 2 + minecraft:sweeping_edge: + item: 4 + book: 2 + minecraft:thorns: + item: 8 + book: 4 + minecraft:unbreaking: + item: 2 + book: 1 + minecraft:vanishing_curse: + item: 8 + book: 4 + +# Disable enchantment merging for level above the set value +# Enchantment merging is when, for example, 2 unbreaking II book combine to give sharpness III +# But Enchantment above this value can still be applied. following the previous example, we could still apply a unbreaking III book to a sword +# Even if disable-merge-over of unbreaking is set to 2 +# -1 mean enchantment merge for this enchantment is not disabled. default to -1 if absent. +disable-merge-over: + # Sharpness is set to -1. it equivalent to it not being set to anything (and work as vanilla on default configuration) + minecraft:sharpness: -1 + # If uncommented. 2 unbreaking II book would not give an unbreaking III book. but unbreaking III book can still be applied + #minecraft:unbreaking: 2 + +# The maximum number of enchantment an item can get. -1 for infinity +# Use eco enchant enchant_limit if present by default unless "default" is not equal to -1 +enchantment_count_limit: + default: -1 + # Limit for specific items. example bellow is an example with stick + # Per item enchantment limit override eco enchant enchant_limit and default limit + items: + stick: -1 + +# Settings for lore modification +lore_edit: + book_and_quil: + # Permission is ca.lore_edit.book + use_permission: true + append: + # If adding lore using book & quil is enabled + enabled: false + # Cost used every time + fixed_cost: 1 + # Cost used for every lore line added + per_line_cost: 0 + # Use left item vanilla cost penalty if any + shared_increase: false + # Increase shared left item cost penalty + shared_additive: false + # If adding the lore consume the book & quil + do_consume: false + # Allow using color code and hexadecimal color when editing lore via book & quil + # + # Color code are prefixed by "&" and hexadecimal color by "#" + # Color code will not be applied if it colors nothing. "&&" can be used to write "&" + # For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/ + # + # Note that currently minimessage would disable hex code when adding color + allow_color_code: true + allow_hexadecimal_color: false + allow_minimessage: true + + remove: + # If removing lore using book & quil is enabled + enabled: false + # Cost used every time + fixed_cost: 1 + # Cost used for every lore line removed + per_line_cost: 0 + # Use left item vanilla cost penalty if any + shared_increase: false + # Increase shared left item cost penalty + shared_additive: false + # If removing the lore consume the book & quil + do_consume: false + # Cost of replacing colors + remove_color_cost: 0 + # Allowed some color and tags to be reverted to plain text + # Custom anvil will prioritise format that result is a smaller resulting text + # Note that not allowing certain format will lead to some lost of color or tags. + # If configuration are exact as append appending this book should result in the exact same color + # + # Color code will be prefixed by "&" and hexadecimal color by "#". + # If color code is allowed, "&" in the text will get converted to "&&" + # For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/ + allow_color_code: true + allow_hexadecimal_color: false + allow_minimessage: true + + paper: + # Permission is ca.lore_edit.paper + use_permission: true + # what order should the lines should get added/removed (start/end, if invalid or not present will be end) + order: end + + append_line: + # If adding lore line using paper is enabled + enabled: false + # Cost used every time + fixed_cost: 1 + # Use left item vanilla cost penalty if any + shared_increase: false + # Increase shared left item cost penalty + shared_additive: false + # If adding the lore line consume the paper + do_consume: false + # Allow using color code and hexadecimal color when editing lore via book & quil + # + # Color code are prefixed by "&" and hexadecimal color by "#" + # Color code will not be applied if it colors nothing. "&&" can be used to write "&" + # For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/ + # + # Note that currently minimessage would disable hex code when adding color + allow_color_code: true + allow_hexadecimal_color: false + allow_minimessage: true + color_use_cost: 0 + + remove_line: + # If removing lore line using paper is enabled + enabled: false + # Cost used every time + fixed_cost: 1 + # Use left item vanilla cost penalty if any + shared_increase: false + # Increase shared left item cost penalty + shared_additive: false + # If removing the lore line consume the paper + do_consume: false + # Cost of replacing colors + remove_color_cost: 0 + # Allowed some color and tags to be reverted to plain text + # Custom anvil will prioritise format that result is a smaller resulting text + # Note that not allowing certain format will lead to some lost of color or tags. + # If configuration are exact as append appending this paper should result in the exact same color + # + # Color code will be prefixed by "&" and hexadecimal color by "#". + # If color code is allowed, "&" in the text will get converted to "&&" + # For minimessage see minimessage formating https://docs.papermc.io/adventure/minimessage/format/ + allow_color_code: true + allow_hexadecimal_color: false + allow_minimessage: true + +# Allow to replace the xp cost by a monetary cost +# If enabled it will not be bound to the experience level limits +# +# It also requires to enable dialog rename (set "enable_dialog_rename: false" a bit higher) +# If dialog rename permission is enabled and player do not have the permission merge will fall back to vanilla xp cost +# +# If you are using custom craft I recommend using Linear Xp Cost with Exact Linear Xp as normal Xp Cost will act "weird" +# But Linear Xp will act as 1$ time global multiplier. In other word: like you expect +# +# As this feature require dialog rename, it can only be enabled starting with paper 1.21.6 and later +monetary_cost: + enabled: false + # If using vault unlocked this allow to specify what currency should be used for anvil usage + # default being the default currency + currency: default + # multiply the anvil cost by a value to allow to have price a big bigger than like 40 + multipliers: + # global multipliers. all usage type will be multiplied by this value + global: 1.0 + # usage specific type. it will only apply for specific xp "reason" + enchantment: 1.0 # related to enchantments level + repair: 1.0 # for repairing via unit repair (per unit) + rename: 1.0 # for renaming the item + lore_edit: 1.0 # for changing the lore of the item (only if lore edit is enabled) + work_penalty: 1.0 # for work penalty (aka use penalty) + recipe: 1.0 # for custom anvil recipe cost + +# Whether to show debug logging +debug_log: false + +# Whether to show verbose debug logging +debug_log_verbose: false + +# Whether to show inside the console or require to run /ca debug get +display_debug_in_console: false + +configVersion: 1.11.0 diff --git a/defaultconfigs/1.18/custom_recipes.yml b/defaultconfigs/1.18/custom_recipes.yml new file mode 100644 index 00000000..57c2220c --- /dev/null +++ b/defaultconfigs/1.18/custom_recipes.yml @@ -0,0 +1,5 @@ +# ---------------------------------------------------- +# This config file is to store custom craft +# It is recommended to use the in game config editor for this configuration. +# /customanvilconfig With ca.config.edit permission +# ---------------------------------------------------- diff --git a/defaultconfigs/1.18/enchant_conflict.yml b/defaultconfigs/1.18/enchant_conflict.yml new file mode 100644 index 00000000..047b1b26 --- /dev/null +++ b/defaultconfigs/1.18/enchant_conflict.yml @@ -0,0 +1,240 @@ +# +# It is recommended that you use /ca config to edit theses config. +# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! +# + +# material conflicts +# +# If you want to edit this file: +# - A conflict will apply to every item except if in one of the notAffectedGroups group +# - the conflict will count only if the user try to combine at least as +# many conflicting enchantment as "maxEnchantmentBeforeConflict" +# +# +# ---------------------------------------------------- +# These restriction are about not allowing enchantment +# on illegal items +# ---------------------------------------------------- + +restriction_aqua_affinity: + enchantments: [ minecraft:aqua_affinity ] + notAffectedGroups: [ enchanted_book, helmets ] + +restriction_bane_of_arthropods: + enchantments: [ minecraft:bane_of_arthropods ] + notAffectedGroups: [ enchanted_book, melee_weapons ] + +restriction_blast_protection: + enchantments: [ minecraft:blast_protection ] + notAffectedGroups: [ enchanted_book, armors ] + +restriction_channeling: + enchantments: [ minecraft:channeling ] + notAffectedGroups: [ enchanted_book, trident ] + +restriction_binding_curse: + enchantments: [ minecraft:binding_curse ] + notAffectedGroups: [ enchanted_book, wearable ] + +restriction_vanishing_curse: + enchantments: [ minecraft:vanishing_curse ] + notAffectedGroups: [ enchanted_book, can_vanish ] + +restriction_depth_strider: + enchantments: [ minecraft:depth_strider ] + notAffectedGroups: [ enchanted_book, boots ] + +restriction_efficiency: + enchantments: [ minecraft:efficiency ] + notAffectedGroups: [ enchanted_book, tools, shears ] + +restriction_feather_falling: + enchantments: [ minecraft:feather_falling ] + notAffectedGroups: [ enchanted_book, boots ] + +restriction_fire_aspect: + enchantments: [ minecraft:fire_aspect ] + notAffectedGroups: [ enchanted_book, swords ] + +restriction_fire_protection: + enchantments: [ minecraft:fire_protection ] + notAffectedGroups: [ enchanted_book, armors ] + +restriction_flame: + enchantments: [ minecraft:flame ] + notAffectedGroups: [ enchanted_book, bow ] + +restriction_fortune: + enchantments: [ minecraft:fortune ] + notAffectedGroups: [ enchanted_book, tools ] + +restriction_frost_walker: + enchantments: [ minecraft:frost_walker ] + notAffectedGroups: [ enchanted_book, boots ] + +restriction_impaling: + enchantments: [ minecraft:impaling ] + notAffectedGroups: [ enchanted_book, trident ] + +restriction_infinity: + enchantments: [ minecraft:infinity ] + notAffectedGroups: [ enchanted_book, bow ] + +restriction_knockback: + enchantments: [ minecraft:knockback ] + notAffectedGroups: [ enchanted_book, swords ] + +restriction_looting: + enchantments: [ minecraft:looting ] + notAffectedGroups: [ enchanted_book, swords ] + +restriction_loyalty: + enchantments: [ minecraft:loyalty ] + notAffectedGroups: [ enchanted_book, trident ] + +restriction_luck_of_the_sea: + enchantments: [ minecraft:luck_of_the_sea ] + notAffectedGroups: [ enchanted_book, fishing_rod ] + +restriction_lure: + enchantments: [ minecraft:lure ] + notAffectedGroups: [ enchanted_book, fishing_rod ] + +restriction_mending: + enchantments: [ minecraft:mending ] + notAffectedGroups: [ enchanted_book, can_unbreak ] + +restriction_minecraft_multishot: + enchantments: [ minecraft:multishot ] + notAffectedGroups: [ enchanted_book, crossbow ] + +restriction_piercing: + enchantments: [ minecraft:piercing ] + notAffectedGroups: [ enchanted_book, crossbow ] + +restriction_power: + enchantments: [ minecraft:power ] + notAffectedGroups: [ enchanted_book, bow ] + +restriction_projectile_protection: + enchantments: [ minecraft:projectile_protection ] + notAffectedGroups: [ enchanted_book, armors ] + +restriction_protection: + enchantments: [ minecraft:protection ] + notAffectedGroups: [ enchanted_book, armors ] + +restriction_punch: + enchantments: [ minecraft:punch ] + notAffectedGroups: [ enchanted_book, bow ] + +restriction_quick_charge: + enchantments: [ minecraft:quick_charge ] + notAffectedGroups: [ enchanted_book, crossbow ] + +restriction_respiration: + enchantments: [ minecraft:respiration ] + notAffectedGroups: [ enchanted_book, helmets ] + +restriction_riptide: + enchantments: [ minecraft:riptide ] + notAffectedGroups: [ enchanted_book, trident ] + +restriction_sharpness: + enchantments: [ minecraft:sharpness ] + notAffectedGroups: [ enchanted_book, melee_weapons ] + +restriction__silk_touch: + enchantments: [ minecraft:silk_touch ] + notAffectedGroups: [ enchanted_book, tools ] + +restriction_smite: + enchantments: [ minecraft:smite ] + notAffectedGroups: [ enchanted_book, melee_weapons ] + +restriction_soul_speed: + enchantments: [ minecraft:soul_speed ] + notAffectedGroups: [ enchanted_book, boots ] + +restriction_sweeping_edge: + enchantments: [ minecraft:sweeping, minecraft:sweeping_edge ] + notAffectedGroups: [ enchanted_book, swords ] + +restriction_thorns: + enchantments: [ minecraft:thorns ] + notAffectedGroups: [ enchanted_book, armors ] + +restriction__unbreaking: + enchantments: [ minecraft:unbreaking ] + notAffectedGroups: [ enchanted_book, can_unbreak ] + +# ---------------------------------------------------- +# Now we have conflicts about enchantment Incompatibility +# We just filtered what item enchantments can be applied +# notAffectedGroups is empty as we don't want anything to not respect theses rules +# maxEnchantmentBeforeConflict is set to 1 to only have 1 on those enchantment available +# ---------------------------------------------------- + +sword_enchant_conflict: + enchantments: + - minecraft:bane_of_arthropods + - minecraft:smite + - minecraft:sharpness + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +protection_enchant_conflict: + enchantments: + - minecraft:blast_protection + - minecraft:fire_protection + - minecraft:projectile_protection + - minecraft:protection + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +trident_conflict1: + enchantments: + - minecraft:channeling + - minecraft:riptide + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +trident_conflict2: + enchantments: + - minecraft:loyalty + - minecraft:riptide + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +boot_conflict: + enchantments: + - minecraft:depth_strider + - minecraft:frost_walker + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +tool_conflict: + enchantments: + - minecraft:fortune + - minecraft:silk_touch + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +bow_conflict: + enchantments: + - minecraft:mending + - minecraft:infinity + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +crossbow_conflict: + enchantments: + - minecraft:multishot + - minecraft:piercing + notAffectedGroups: [ ] + maxEnchantmentBeforeConflict: 1 + +# ---------------------------------------------------- +# Bellow is for custom conflicts. +# This is also where conflict create from the gui will be placed. +# ---------------------------------------------------- diff --git a/defaultconfigs/1.18/item_groups.yml b/defaultconfigs/1.18/item_groups.yml new file mode 100644 index 00000000..7956fb61 --- /dev/null +++ b/defaultconfigs/1.18/item_groups.yml @@ -0,0 +1,210 @@ +# +# It is recommended that you use /ca config to edit theses config. +# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! +# + +# Please note this config use spigot material names. +# It should match minecraft name in most case, maybe every case, but I can't be sure +# In case there an issue with material name, you can found them here: +# https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html + +# An empty Exclude group exclude nothing, so it contain everything +everything: + type: exclude + +# An empty include group will include nothing +nothing: + type: include + +# This group is an example of a group including only stone and polished granite +example_include: + type: include + items: + - stone + - polished_granite + +# This group contain everything except polished granite and elements of example_include +example_exclude: + type: exclude + items: + - polished_granite + groups: + - example_include + +# Default configuration should be vanilla enchantment conflict group +# there may have error, if you find one you can fix it ! +# https://minecraft.fandom.com/wiki/Enchanting + +swords: + type: include + items: + - wooden_sword + - stone_sword + - iron_sword + - diamond_sword + - golden_sword + - netherite_sword + +axes: + type: include + items: + - wooden_axe + - stone_axe + - iron_axe + - diamond_axe + - golden_axe + - netherite_axe + +melee_weapons: + type: include + groups: + - swords + - axes + +helmets: + type: include + items: + - leather_helmet + - chainmail_helmet + - iron_helmet + - diamond_helmet + - golden_helmet + - netherite_helmet + - turtle_helmet + +chestplate: + type: include + items: + - leather_chestplate + - chainmail_chestplate + - iron_chestplate + - diamond_chestplate + - golden_chestplate + - netherite_chestplate + +leggings: + type: include + items: + - leather_leggings + - chainmail_leggings + - iron_leggings + - diamond_leggings + - golden_leggings + - netherite_leggings + +boots: + type: include + items: + - leather_boots + - chainmail_boots + - iron_boots + - diamond_boots + - golden_boots + - netherite_boots + +armors: + type: include + groups: + - helmets + - chestplate + - leggings + - boots + +wearable: + type: include + items: + - elytra + - carved_pumpkin + - skeleton_skull + - wither_skeleton_skull + - zombie_head + - player_head + - creeper_head + - dragon_head + # do not exist in 1.18 but exist in future update + - piglin_head + groups: + - armors + +tools: + type: include + items: + - wooden_pickaxe + - stone_pickaxe + - iron_pickaxe + - diamond_pickaxe + - golden_pickaxe + - netherite_pickaxe + - wooden_shovel + - stone_shovel + - iron_shovel + - diamond_shovel + - golden_shovel + - netherite_shovel + - wooden_hoe + - stone_hoe + - iron_hoe + - diamond_hoe + - golden_hoe + - netherite_hoe + groups: + - axes + +enchanted_book: + type: include + items: + - enchanted_book + +trident: + type: include + items: + - trident + +bow: + type: include + items: + - bow + +crossbow: + type: include + items: + - crossbow + +fishing_rod: + type: include + items: + - fishing_rod + +shears: + type: include + items: + - shears + +can_unbreak: + type: include + items: + - elytra + - flint_and_steel + - shield + - carrot_on_a_stick + - warped_fungus_on_a_stick + # do not exist in 1.18 but exist in future update + - brush + groups: + - melee_weapons + - tools + - armors + - trident + - bow + - crossbow + - fishing_rod + - shears + +can_vanish: + type: include + items: + - compass + groups: + - wearable + - can_unbreak + diff --git a/defaultconfigs/1.18/unit_repair_item.yml b/defaultconfigs/1.18/unit_repair_item.yml new file mode 100644 index 00000000..a8bbcbe3 --- /dev/null +++ b/defaultconfigs/1.18/unit_repair_item.yml @@ -0,0 +1,190 @@ +# +# It is recommended that you use /ca config to edit theses config. +# You can still manually edit here if you like to. but if you do, don't forget to /ca reload after you changes ! +# + +# Unit repair configuration +# +# This configuration is to make custom unit repair +# A unit repair is, for example, a diamond to repair a diamond sword +# In vanilla, a unit repair 25% of object durability +# you can make a custom value here +# +# Item name should NOT combine caps and no caps (example: Stone) + +# Default value if the config is an invalid value (value <= 0 ) +# If value > 1 it will be treated as being = 1 +default_repair_amount: 0.25 + +# You can add custom unit repair +# The example bellow make a shield repaired by 10% by sticks + +#stick: +# shield: 0.10 + + +# Vanilla unit repair group is bellow +diamond: + diamond_helmet: 0.25 + diamond_chestplate: 0.25 + diamond_leggings: 0.25 + diamond_boots: 0.25 + diamond_sword: 0.25 + diamond_pickaxe: 0.25 + diamond_axe: 0.25 + diamond_shovel: 0.25 + diamond_hoe: 0.25 + +netherite_ingot: + netherite_helmet: 0.25 + netherite_chestplate: 0.25 + netherite_leggings: 0.25 + netherite_boots: 0.25 + netherite_sword: 0.25 + netherite_pickaxe: 0.25 + netherite_axe: 0.25 + netherite_shovel: 0.25 + netherite_hoe: 0.25 + +gold_ingot: + golden_helmet: 0.25 + golden_chestplate: 0.25 + golden_leggings: 0.25 + golden_boots: 0.25 + golden_sword: 0.25 + golden_pickaxe: 0.25 + golden_axe: 0.25 + golden_shovel: 0.25 + golden_hoe: 0.25 + +iron_ingot: + iron_helmet: 0.25 + iron_chestplate: 0.25 + iron_leggings: 0.25 + iron_boots: 0.25 + iron_sword: 0.25 + iron_pickaxe: 0.25 + iron_axe: 0.25 + iron_shovel: 0.25 + iron_hoe: 0.25 + +cobblestone: + stone_sword: 0.25 + stone_pickaxe: 0.25 + stone_axe: 0.25 + stone_shovel: 0.25 + stone_hoe: 0.25 + +cobbled_deepslate: + stone_sword: 0.25 + stone_pickaxe: 0.25 + stone_axe: 0.25 + stone_shovel: 0.25 + stone_hoe: 0.25 + +blackstone: + stone_sword: 0.25 + stone_pickaxe: 0.25 + stone_axe: 0.25 + stone_shovel: 0.25 + stone_hoe: 0.25 + +leather: + leather_helmet: 0.25 + leather_chestplate: 0.25 + leather_leggings: 0.25 + leather_boots: 0.25 + +phantom_membrane: + elytra: 0.25 + +scute: + turtle_helmet: 0.25 + +oak_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +spruce_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +birch_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +jungle_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +acacia_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +dark_oak_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +mangrove_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +cherry_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +bamboo_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +crimson_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 + +warped_planks: + wooden_sword: 0.25 + wooden_pickaxe: 0.25 + wooden_axe: 0.25 + wooden_shovel: 0.25 + wooden_hoe: 0.25 + shield: 0.25 diff --git a/defaultconfigs/README.md b/defaultconfigs/README.md index e4f40d22..daa20882 100644 --- a/defaultconfigs/README.md +++ b/defaultconfigs/README.md @@ -1,4 +1,5 @@ ### Default Plugin's Configurations +From 1.18 to 1.20.6 use [1.18 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.18) \ From 1.21 to 1.21.8 use [1.21 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21) \ From 1.21.9 to 1.21.10 use [1.21.9 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21.9) \ From 1.21.11 use [1.21.11 configurations](https://github.com/alexcrea/CustomAnvil/tree/master/defaultconfigs/1.21.11) diff --git a/gradle.properties b/gradle.properties index 8bf9e80a..b9c47c92 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,5 @@ kotlin.code.style=official +org.gradle.configuration-cache=true # Signing signing.secretKeyRingFile=~/.gnupg/secring.gpg @@ -6,8 +7,8 @@ signing.secretKeyRingFile=~/.gnupg/secring.gpg kotlin.daemon.jvmargs=-Xmx8G # list of nms -subprojects.reobfnms=v1_21R1,v1_21R2,v1_21R3,v1_21R4,v1_21R5,v1_21R6,v1_21R7 +subprojects.reobfnms=v1_17R1,v1_18R1,v1_18R2 # list of version for hangar release -paperVersion=1.18-26.2 +paperVersion=1.18-1.20.5 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0b55a3bd..8bf5ce26 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.0-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/impl/ExcellentEnchant5_4/build.gradle.kts b/impl/ExcellentEnchant5_4/build.gradle.kts index 9fe598b1..e624d159 100644 --- a/impl/ExcellentEnchant5_4/build.gradle.kts +++ b/impl/ExcellentEnchant5_4/build.gradle.kts @@ -2,7 +2,7 @@ group = rootProject.group version = rootProject.version plugins { - kotlin("jvm") version "2.3.0" + kotlin("jvm") version "2.4.0" } repositories { diff --git a/impl/LegacyEcoEnchant/build.gradle.kts b/impl/LegacyEcoEnchant/build.gradle.kts index 3c3f1aeb..00ecd1b8 100644 --- a/impl/LegacyEcoEnchant/build.gradle.kts +++ b/impl/LegacyEcoEnchant/build.gradle.kts @@ -2,12 +2,12 @@ group = rootProject.group version = rootProject.version plugins { - kotlin("jvm") version "2.3.0" + kotlin("jvm") version "2.4.0" } // Imitate needed class and method to support legacy version of EcoEnchant dependencies { // Spigot api - compileOnly("org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT") + compileOnly("org.spigotmc:spigot-api:1.18-R0.1-SNAPSHOT") } \ No newline at end of file diff --git a/nms/nms-common/build.gradle.kts b/nms/nms-common/build.gradle.kts index 46f684d7..a75f9477 100644 --- a/nms/nms-common/build.gradle.kts +++ b/nms/nms-common/build.gradle.kts @@ -21,15 +21,15 @@ repositories { // Set target version tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" + sourceCompatibility = "16" + targetCompatibility = "16" options.encoding = "UTF-8" } kotlin { compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_16) } } diff --git a/nms/nms-common/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/util/PaperSpigotUtil.kt b/nms/nms-common/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/util/PlatformUtil.kt similarity index 89% rename from nms/nms-common/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/util/PaperSpigotUtil.kt rename to nms/nms-common/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/util/PlatformUtil.kt index 20972bfa..aaa218fa 100644 --- a/nms/nms-common/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/util/PaperSpigotUtil.kt +++ b/nms/nms-common/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/util/PlatformUtil.kt @@ -67,14 +67,7 @@ object PlatformUtil { } } - // Display name - private val useCustomName = hasMethod(ItemMeta::class.java, "customName") - fun ItemMeta.componentDisplayName(): Component? { - if (useCustomName) { - if (!this.hasCustomName()) return null - return this.customName() - } if (!this.hasDisplayName()) return null return if (isPaper) { @@ -85,9 +78,7 @@ object PlatformUtil { } fun ItemMeta.setComponentDisplayName(component: Component?, fallback: String? = null) { - if (useCustomName) { - this.customName(component) - } else if (isPaper) { + if (isPaper) { this.displayName(component) } else { if (component == null) { diff --git a/nms/nms-paper/build.gradle.kts b/nms/nms-paper/build.gradle.kts index 19033be7..85a5537e 100644 --- a/nms/nms-paper/build.gradle.kts +++ b/nms/nms-paper/build.gradle.kts @@ -21,15 +21,15 @@ repositories { // Set target version tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" + sourceCompatibility = "18" + targetCompatibility = "18" options.encoding = "UTF-8" } kotlin { compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_18) } } diff --git a/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/datapack/DataPackTester.kt b/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/datapack/DataPackTester.kt index 221dd2fa..4ec2349b 100644 --- a/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/datapack/DataPackTester.kt +++ b/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/datapack/DataPackTester.kt @@ -1,20 +1,42 @@ +@file:Suppress("DEPRECATION", "removal") package xyz.alexcrea.cuanvil.dependency.datapack import io.papermc.paper.datapack.Datapack import org.bukkit.Bukkit +import org.bukkit.packs.DataPack import java.util.* object DataPackTester { + val legacyNames: List + get() = Bukkit.getDataPackManager().dataPacks + .stream().filter { obj -> obj.isEnabled } + .map { pack -> pack.key.key } + .toList() val enabledPacks: List get() { - return try { - Bukkit.getDatapackManager().enabledPacks + try { + // will throw error if do not exist + Bukkit::class.java.getDeclaredMethod("getDatapackManager") + + return Bukkit.getDatapackManager().enabledPacks .stream().map { obj: Datapack -> obj.name } .toList() + } catch (_: NoSuchMethodException) { + try { + DataPack::class.java.getDeclaredMethod("getKey") + } catch (_: NoSuchMethodException) { + System.err.println("Could not find compatible datapack manager") + System.err.println("If you are using a datapack that should be compatible with CustomAnvil. It will not get detected...") + return emptyList() + } + return legacyNames } catch (_: Exception){ // Assume cause UnimplementedOperationException on mock server - Collections.emptyList() + return Collections.emptyList() + } catch(_: NoSuchMethodError) { + // Idk newer spigot may not have that ? + return Collections.emptyList() } } } diff --git a/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dialog/AnvilRenameDialogImpl.kt b/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dialog/AnvilRenameDialogImpl.kt index 7761cd57..e210daa9 100644 --- a/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dialog/AnvilRenameDialogImpl.kt +++ b/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/dialog/AnvilRenameDialogImpl.kt @@ -18,8 +18,8 @@ import org.bukkit.craftbukkit.inventory.CraftInventoryView import org.bukkit.craftbukkit.inventory.view.CraftAnvilView import org.bukkit.entity.HumanEntity import org.bukkit.event.inventory.PrepareAnvilEvent +import org.bukkit.inventory.InventoryView import org.bukkit.inventory.ItemStack -import org.bukkit.inventory.view.AnvilView import org.bukkit.persistence.PersistentDataType import org.bukkit.plugin.Plugin import java.util.* @@ -121,7 +121,7 @@ class AnvilRenameDialogImpl( } } - private fun setResult(player: HumanEntity, view: AnvilView, result: String?) { + private fun setResult(player: HumanEntity, view: InventoryView, result: String?) { val defaultName = itemDefaultName(view.getItem(0)) if (defaultName == result) { setName(player, view, "", null) @@ -129,7 +129,7 @@ class AnvilRenameDialogImpl( } else setName(player, view, result, result) } - private fun setName(player: HumanEntity, view: AnvilView, name: String?, rename: String?) { + private fun setName(player: HumanEntity, view: InventoryView, name: String?, rename: String?) { val menu = (containerField.get(view) as AnvilMenu) val isSameName = menu.itemName == name menu.itemName = rename diff --git a/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/util/AnvilTitleUtil.kt b/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/util/AnvilTitleUtil.kt index dc8ac092..cf9686c4 100644 --- a/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/util/AnvilTitleUtil.kt +++ b/nms/nms-paper/src/main/kotlin/xyz/alexcrea/cuanvil/util/AnvilTitleUtil.kt @@ -2,18 +2,18 @@ package xyz.alexcrea.cuanvil.util import io.papermc.paper.threadedregions.scheduler.ScheduledTask import org.bukkit.entity.HumanEntity -import org.bukkit.inventory.view.AnvilView +import org.bukkit.inventory.InventoryView import org.bukkit.plugin.Plugin import xyz.alexcrea.cuanvil.dialog.AnvilRenameDialog import java.util.HashMap import java.util.UUID -@Suppress("UnstableApiUsage") object AnvilTitleUtil { private val runTaskMap = HashMap() - private fun actualRename(view: AnvilView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog) { + @Suppress("DEPRECATION") + private fun actualRename(view: InventoryView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog) { runTaskMap.remove(player.uniqueId) if (view.title == name) return @@ -25,7 +25,7 @@ object AnvilTitleUtil { // We don't want to rename instantly it is causing issue with rename text // especially as it can "override" current ui when it is rename ui time but rename ui also need some delay - fun rename(view: AnvilView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog, plugin: Plugin) { + fun rename(view: InventoryView, name: String, player: HumanEntity, anvilDialog: AnvilRenameDialog, plugin: Plugin) { runTaskMap.remove(player.uniqueId)?.cancel() val task = player.scheduler.runDelayed( diff --git a/nms/v1_21R1/.gitignore b/nms/v1_17R1/.gitignore similarity index 100% rename from nms/v1_21R1/.gitignore rename to nms/v1_17R1/.gitignore diff --git a/nms/v1_21R3/build.gradle.kts b/nms/v1_17R1/build.gradle.kts similarity index 75% rename from nms/v1_21R3/build.gradle.kts rename to nms/v1_17R1/build.gradle.kts index d06816cc..45599335 100644 --- a/nms/v1_21R3/build.gradle.kts +++ b/nms/v1_17R1/build.gradle.kts @@ -11,7 +11,7 @@ dependencies { implementation(project(":nms:nms-common")) // Used for nms - paperweight.paperDevBundle("1.21.4-R0.1-SNAPSHOT") + paperweight.paperDevBundle("1.17.1-R0.1-SNAPSHOT") } repositories { @@ -21,15 +21,15 @@ repositories { // Set target version tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" + sourceCompatibility = "16" + targetCompatibility = "16" options.encoding = "UTF-8" } kotlin { compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_16) } } diff --git a/nms/v1_21R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R3_PacketManager.kt b/nms/v1_17R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_17R1_PacketManager.kt similarity index 91% rename from nms/v1_21R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R3_PacketManager.kt rename to nms/v1_17R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_17R1_PacketManager.kt index 0f581d96..c820eabf 100644 --- a/nms/v1_21R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R3_PacketManager.kt +++ b/nms/v1_17R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_17R1_PacketManager.kt @@ -2,12 +2,12 @@ package xyz.alexcrea.cuanvil.dependency.packet.versions import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket import net.minecraft.world.entity.player.Abilities -import org.bukkit.craftbukkit.entity.CraftPlayer +import org.bukkit.craftbukkit.v1_17_R1.entity.CraftPlayer import org.bukkit.entity.Player import xyz.alexcrea.cuanvil.dependency.packet.PacketManager import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase -class V1_21R3_PacketManager : PacketManagerBase(), PacketManager { +class V1_17R1_PacketManager : PacketManagerBase(), PacketManager { override val canSetInstantBuild: Boolean get() = true diff --git a/nms/v1_21R2/.gitignore b/nms/v1_18R1/.gitignore similarity index 100% rename from nms/v1_21R2/.gitignore rename to nms/v1_18R1/.gitignore diff --git a/nms/v1_21R1/build.gradle.kts b/nms/v1_18R1/build.gradle.kts similarity index 75% rename from nms/v1_21R1/build.gradle.kts rename to nms/v1_18R1/build.gradle.kts index bf2152cc..9c334f3c 100644 --- a/nms/v1_21R1/build.gradle.kts +++ b/nms/v1_18R1/build.gradle.kts @@ -11,7 +11,7 @@ dependencies { implementation(project(":nms:nms-common")) // Used for nms - paperweight.paperDevBundle("1.21.1-R0.1-SNAPSHOT") + paperweight.paperDevBundle("1.18.1-R0.1-SNAPSHOT") } repositories { @@ -21,15 +21,15 @@ repositories { // Set target version tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" + sourceCompatibility = "17" + targetCompatibility = "17" options.encoding = "UTF-8" } kotlin { compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_17) } } diff --git a/nms/v1_21R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R1_PacketManager.kt b/nms/v1_18R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_18R1_PacketManager.kt similarity index 91% rename from nms/v1_21R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R1_PacketManager.kt rename to nms/v1_18R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_18R1_PacketManager.kt index 4ea99508..71df5c72 100644 --- a/nms/v1_21R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R1_PacketManager.kt +++ b/nms/v1_18R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_18R1_PacketManager.kt @@ -2,12 +2,12 @@ package xyz.alexcrea.cuanvil.dependency.packet.versions import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket import net.minecraft.world.entity.player.Abilities -import org.bukkit.craftbukkit.entity.CraftPlayer +import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer import org.bukkit.entity.Player import xyz.alexcrea.cuanvil.dependency.packet.PacketManager import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase -class V1_21R1_PacketManager : PacketManagerBase(), PacketManager { +class V1_18R1_PacketManager : PacketManagerBase(), PacketManager { override val canSetInstantBuild: Boolean get() = true diff --git a/nms/v1_21R3/.gitignore b/nms/v1_18R2/.gitignore similarity index 100% rename from nms/v1_21R3/.gitignore rename to nms/v1_18R2/.gitignore diff --git a/nms/v1_21R2/build.gradle.kts b/nms/v1_18R2/build.gradle.kts similarity index 75% rename from nms/v1_21R2/build.gradle.kts rename to nms/v1_18R2/build.gradle.kts index e65f6fd8..3d31ad63 100644 --- a/nms/v1_21R2/build.gradle.kts +++ b/nms/v1_18R2/build.gradle.kts @@ -11,7 +11,7 @@ dependencies { implementation(project(":nms:nms-common")) // Used for nms - paperweight.paperDevBundle("1.21.3-R0.1-SNAPSHOT") + paperweight.paperDevBundle("1.18.2-R0.1-SNAPSHOT") } repositories { @@ -21,15 +21,15 @@ repositories { // Set target version tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" + sourceCompatibility = "17" + targetCompatibility = "17" options.encoding = "UTF-8" } kotlin { compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_17) } } diff --git a/nms/v1_21R4/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R4_PacketManager.kt b/nms/v1_18R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_18R2_PacketManager.kt similarity index 91% rename from nms/v1_21R4/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R4_PacketManager.kt rename to nms/v1_18R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_18R2_PacketManager.kt index b1236256..ee442f5e 100644 --- a/nms/v1_21R4/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R4_PacketManager.kt +++ b/nms/v1_18R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_18R2_PacketManager.kt @@ -2,12 +2,12 @@ package xyz.alexcrea.cuanvil.dependency.packet.versions import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket import net.minecraft.world.entity.player.Abilities -import org.bukkit.craftbukkit.entity.CraftPlayer +import org.bukkit.craftbukkit.v1_18_R2.entity.CraftPlayer import org.bukkit.entity.Player import xyz.alexcrea.cuanvil.dependency.packet.PacketManager import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase -class V1_21R4_PacketManager : PacketManagerBase(), PacketManager { +class V1_18R2_PacketManager : PacketManagerBase(), PacketManager { override val canSetInstantBuild: Boolean get() = true diff --git a/nms/v1_21R4/.gitignore b/nms/v1_19R1/.gitignore similarity index 100% rename from nms/v1_21R4/.gitignore rename to nms/v1_19R1/.gitignore diff --git a/nms/v1_21R4/build.gradle.kts b/nms/v1_19R1/build.gradle.kts similarity index 75% rename from nms/v1_21R4/build.gradle.kts rename to nms/v1_19R1/build.gradle.kts index 8bd22b9f..fdd9d07a 100644 --- a/nms/v1_21R4/build.gradle.kts +++ b/nms/v1_19R1/build.gradle.kts @@ -11,24 +11,25 @@ dependencies { implementation(project(":nms:nms-common")) // Used for nms - paperweight.paperDevBundle("1.21.5-R0.1-SNAPSHOT") + paperweight.paperDevBundle("1.19.2-R0.1-SNAPSHOT") } repositories { maven("https://repo.papermc.io/repository/maven-public/") + } // Set target version tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" + sourceCompatibility = "17" + targetCompatibility = "17" options.encoding = "UTF-8" } kotlin { compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_17) } } diff --git a/nms/v1_19R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R1_PacketManager.kt b/nms/v1_19R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R1_PacketManager.kt new file mode 100644 index 00000000..7a057fcc --- /dev/null +++ b/nms/v1_19R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R1_PacketManager.kt @@ -0,0 +1,33 @@ +package xyz.alexcrea.cuanvil.dependency.packet.versions + +import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket +import net.minecraft.world.entity.player.Abilities +import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer +import org.bukkit.entity.Player +import xyz.alexcrea.cuanvil.dependency.packet.PacketManager +import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase + +class V1_19R1_PacketManager : PacketManagerBase(), PacketManager { + override val canSetInstantBuild: Boolean + get() = true + + override fun setInstantBuild(player: Player, instantBuild: Boolean) { + val nmsPlayer = (player as CraftPlayer).handle + val playerAbilities = nmsPlayer.abilities + val sendedAbilities: Abilities + if (playerAbilities.instabuild == instantBuild) { + sendedAbilities = playerAbilities + } else { + sendedAbilities = Abilities() + sendedAbilities.invulnerable = playerAbilities.invulnerable + sendedAbilities.flying = playerAbilities.flying + sendedAbilities.mayfly = playerAbilities.mayfly + sendedAbilities.instabuild = instantBuild + sendedAbilities.mayBuild = playerAbilities.mayBuild + sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed + sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed + } + val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) + nmsPlayer.connection.send(packet) + } +} diff --git a/nms/v1_21R5/.gitignore b/nms/v1_19R2/.gitignore similarity index 100% rename from nms/v1_21R5/.gitignore rename to nms/v1_19R2/.gitignore diff --git a/nms/v1_19R2/build.gradle.kts b/nms/v1_19R2/build.gradle.kts new file mode 100644 index 00000000..bab486de --- /dev/null +++ b/nms/v1_19R2/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = rootProject.group +version = rootProject.version + +plugins { + id("io.papermc.paperweight.userdev") +} + +dependencies { + implementation(project(":nms:nms-common")) + + // Used for nms + paperweight.paperDevBundle("1.19.3-R0.1-SNAPSHOT") +} + +repositories { + maven("https://repo.papermc.io/repository/maven-public/") + +} + +// Set target version +tasks.withType().configureEach { + sourceCompatibility = "17" + targetCompatibility = "17" + + options.encoding = "UTF-8" +} + +kotlin { + compilerOptions { + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_17) + } +} diff --git a/nms/v1_19R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R2_PacketManager.kt b/nms/v1_19R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R2_PacketManager.kt new file mode 100644 index 00000000..0d04cd1f --- /dev/null +++ b/nms/v1_19R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R2_PacketManager.kt @@ -0,0 +1,33 @@ +package xyz.alexcrea.cuanvil.dependency.packet.versions + +import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket +import net.minecraft.world.entity.player.Abilities +import org.bukkit.craftbukkit.v1_19_R2.entity.CraftPlayer +import org.bukkit.entity.Player +import xyz.alexcrea.cuanvil.dependency.packet.PacketManager +import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase + +class V1_19R2_PacketManager : PacketManagerBase(), PacketManager { + override val canSetInstantBuild: Boolean + get() = true + + override fun setInstantBuild(player: Player, instantBuild: Boolean) { + val nmsPlayer = (player as CraftPlayer).handle + val playerAbilities = nmsPlayer.abilities + val sendedAbilities: Abilities + if (playerAbilities.instabuild == instantBuild) { + sendedAbilities = playerAbilities + } else { + sendedAbilities = Abilities() + sendedAbilities.invulnerable = playerAbilities.invulnerable + sendedAbilities.flying = playerAbilities.flying + sendedAbilities.mayfly = playerAbilities.mayfly + sendedAbilities.instabuild = instantBuild + sendedAbilities.mayBuild = playerAbilities.mayBuild + sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed + sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed + } + val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) + nmsPlayer.connection.send(packet) + } +} diff --git a/nms/v1_21R6/.gitignore b/nms/v1_19R3/.gitignore similarity index 100% rename from nms/v1_21R6/.gitignore rename to nms/v1_19R3/.gitignore diff --git a/nms/v1_19R3/build.gradle.kts b/nms/v1_19R3/build.gradle.kts new file mode 100644 index 00000000..41d70647 --- /dev/null +++ b/nms/v1_19R3/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = rootProject.group +version = rootProject.version + +plugins { + id("io.papermc.paperweight.userdev") +} + +dependencies { + implementation(project(":nms:nms-common")) + + // Used for nms + paperweight.paperDevBundle("1.19.4-R0.1-SNAPSHOT") +} + +repositories { + maven("https://repo.papermc.io/repository/maven-public/") + +} + +// Set target version +tasks.withType().configureEach { + sourceCompatibility = "17" + targetCompatibility = "17" + + options.encoding = "UTF-8" +} + +kotlin { + compilerOptions { + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_17) + } +} diff --git a/nms/v1_19R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R3_PacketManager.kt b/nms/v1_19R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R3_PacketManager.kt new file mode 100644 index 00000000..7c727912 --- /dev/null +++ b/nms/v1_19R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_19R3_PacketManager.kt @@ -0,0 +1,33 @@ +package xyz.alexcrea.cuanvil.dependency.packet.versions + +import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket +import net.minecraft.world.entity.player.Abilities +import org.bukkit.craftbukkit.v1_19_R3.entity.CraftPlayer +import org.bukkit.entity.Player +import xyz.alexcrea.cuanvil.dependency.packet.PacketManager +import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase + +class V1_19R3_PacketManager : PacketManagerBase(), PacketManager { + override val canSetInstantBuild: Boolean + get() = true + + override fun setInstantBuild(player: Player, instantBuild: Boolean) { + val nmsPlayer = (player as CraftPlayer).handle + val playerAbilities = nmsPlayer.abilities + val sendedAbilities: Abilities + if (playerAbilities.instabuild == instantBuild) { + sendedAbilities = playerAbilities + } else { + sendedAbilities = Abilities() + sendedAbilities.invulnerable = playerAbilities.invulnerable + sendedAbilities.flying = playerAbilities.flying + sendedAbilities.mayfly = playerAbilities.mayfly + sendedAbilities.instabuild = instantBuild + sendedAbilities.mayBuild = playerAbilities.mayBuild + sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed + sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed + } + val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) + nmsPlayer.connection.send(packet) + } +} diff --git a/nms/v1_21R7/.gitignore b/nms/v1_20R1/.gitignore similarity index 100% rename from nms/v1_21R7/.gitignore rename to nms/v1_20R1/.gitignore diff --git a/nms/v1_20R1/build.gradle.kts b/nms/v1_20R1/build.gradle.kts new file mode 100644 index 00000000..3bec3f81 --- /dev/null +++ b/nms/v1_20R1/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = rootProject.group +version = rootProject.version + +plugins { + id("io.papermc.paperweight.userdev") +} + +dependencies { + implementation(project(":nms:nms-common")) + + // Used for nms + paperweight.paperDevBundle("1.20.1-R0.1-SNAPSHOT") +} + +repositories { + maven("https://repo.papermc.io/repository/maven-public/") + +} + +// Set target version +tasks.withType().configureEach { + sourceCompatibility = "18" + targetCompatibility = "18" + + options.encoding = "UTF-8" +} + +kotlin { + compilerOptions { + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_18) + } +} diff --git a/nms/v1_20R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R1_PacketManager.kt b/nms/v1_20R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R1_PacketManager.kt new file mode 100644 index 00000000..1fbac836 --- /dev/null +++ b/nms/v1_20R1/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R1_PacketManager.kt @@ -0,0 +1,33 @@ +package xyz.alexcrea.cuanvil.dependency.packet.versions + +import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket +import net.minecraft.world.entity.player.Abilities +import org.bukkit.craftbukkit.v1_20_R1.entity.CraftPlayer +import org.bukkit.entity.Player +import xyz.alexcrea.cuanvil.dependency.packet.PacketManager +import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase + +class V1_20R1_PacketManager : PacketManagerBase(), PacketManager { + override val canSetInstantBuild: Boolean + get() = true + + override fun setInstantBuild(player: Player, instantBuild: Boolean) { + val nmsPlayer = (player as CraftPlayer).handle + val playerAbilities = nmsPlayer.abilities + val sendedAbilities: Abilities + if (playerAbilities.instabuild == instantBuild) { + sendedAbilities = playerAbilities + } else { + sendedAbilities = Abilities() + sendedAbilities.invulnerable = playerAbilities.invulnerable + sendedAbilities.flying = playerAbilities.flying + sendedAbilities.mayfly = playerAbilities.mayfly + sendedAbilities.instabuild = instantBuild + sendedAbilities.mayBuild = playerAbilities.mayBuild + sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed + sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed + } + val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) + nmsPlayer.connection.send(packet) + } +} diff --git a/nms/v1_20R2/.gitignore b/nms/v1_20R2/.gitignore new file mode 100644 index 00000000..47374f17 --- /dev/null +++ b/nms/v1_20R2/.gitignore @@ -0,0 +1 @@ +.lastDeploymentsId \ No newline at end of file diff --git a/nms/v1_20R2/build.gradle.kts b/nms/v1_20R2/build.gradle.kts new file mode 100644 index 00000000..0b28d317 --- /dev/null +++ b/nms/v1_20R2/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = rootProject.group +version = rootProject.version + +plugins { + id("io.papermc.paperweight.userdev") +} + +dependencies { + implementation(project(":nms:nms-common")) + + // Used for nms + paperweight.paperDevBundle("1.20.2-R0.1-SNAPSHOT") +} + +repositories { + maven("https://repo.papermc.io/repository/maven-public/") + +} + +// Set target version +tasks.withType().configureEach { + sourceCompatibility = "18" + targetCompatibility = "18" + + options.encoding = "UTF-8" +} + +kotlin { + compilerOptions { + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_18) + } +} diff --git a/nms/v1_20R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R2_PacketManager.kt b/nms/v1_20R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R2_PacketManager.kt new file mode 100644 index 00000000..a2db371b --- /dev/null +++ b/nms/v1_20R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R2_PacketManager.kt @@ -0,0 +1,33 @@ +package xyz.alexcrea.cuanvil.dependency.packet.versions + +import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket +import net.minecraft.world.entity.player.Abilities +import org.bukkit.craftbukkit.v1_20_R2.entity.CraftPlayer +import org.bukkit.entity.Player +import xyz.alexcrea.cuanvil.dependency.packet.PacketManager +import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase + +class V1_20R2_PacketManager : PacketManagerBase(), PacketManager { + override val canSetInstantBuild: Boolean + get() = true + + override fun setInstantBuild(player: Player, instantBuild: Boolean) { + val nmsPlayer = (player as CraftPlayer).handle + val playerAbilities = nmsPlayer.abilities + val sendedAbilities: Abilities + if (playerAbilities.instabuild == instantBuild) { + sendedAbilities = playerAbilities + } else { + sendedAbilities = Abilities() + sendedAbilities.invulnerable = playerAbilities.invulnerable + sendedAbilities.flying = playerAbilities.flying + sendedAbilities.mayfly = playerAbilities.mayfly + sendedAbilities.instabuild = instantBuild + sendedAbilities.mayBuild = playerAbilities.mayBuild + sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed + sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed + } + val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) + nmsPlayer.connection.send(packet) + } +} diff --git a/nms/v1_20R3/.gitignore b/nms/v1_20R3/.gitignore new file mode 100644 index 00000000..47374f17 --- /dev/null +++ b/nms/v1_20R3/.gitignore @@ -0,0 +1 @@ +.lastDeploymentsId \ No newline at end of file diff --git a/nms/v1_20R3/build.gradle.kts b/nms/v1_20R3/build.gradle.kts new file mode 100644 index 00000000..2a6d822d --- /dev/null +++ b/nms/v1_20R3/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = rootProject.group +version = rootProject.version + +plugins { + id("io.papermc.paperweight.userdev") +} + +dependencies { + implementation(project(":nms:nms-common")) + + // Used for nms + paperweight.paperDevBundle("1.20.4-R0.1-SNAPSHOT") +} + +repositories { + maven("https://repo.papermc.io/repository/maven-public/") + +} + +// Set target version +tasks.withType().configureEach { + sourceCompatibility = "18" + targetCompatibility = "18" + + options.encoding = "UTF-8" +} + +kotlin { + compilerOptions { + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_18) + } +} diff --git a/nms/v1_20R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R3_PacketManager.kt b/nms/v1_20R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R3_PacketManager.kt new file mode 100644 index 00000000..51c2ecb6 --- /dev/null +++ b/nms/v1_20R3/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R3_PacketManager.kt @@ -0,0 +1,33 @@ +package xyz.alexcrea.cuanvil.dependency.packet.versions + +import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket +import net.minecraft.world.entity.player.Abilities +import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer +import org.bukkit.entity.Player +import xyz.alexcrea.cuanvil.dependency.packet.PacketManager +import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase + +class V1_20R3_PacketManager : PacketManagerBase(), PacketManager { + override val canSetInstantBuild: Boolean + get() = true + + override fun setInstantBuild(player: Player, instantBuild: Boolean) { + val nmsPlayer = (player as CraftPlayer).handle + val playerAbilities = nmsPlayer.abilities + val sendedAbilities: Abilities + if (playerAbilities.instabuild == instantBuild) { + sendedAbilities = playerAbilities + } else { + sendedAbilities = Abilities() + sendedAbilities.invulnerable = playerAbilities.invulnerable + sendedAbilities.flying = playerAbilities.flying + sendedAbilities.mayfly = playerAbilities.mayfly + sendedAbilities.instabuild = instantBuild + sendedAbilities.mayBuild = playerAbilities.mayBuild + sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed + sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed + } + val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) + nmsPlayer.connection.send(packet) + } +} diff --git a/nms/v1_20R4/.gitignore b/nms/v1_20R4/.gitignore new file mode 100644 index 00000000..47374f17 --- /dev/null +++ b/nms/v1_20R4/.gitignore @@ -0,0 +1 @@ +.lastDeploymentsId \ No newline at end of file diff --git a/nms/v1_20R4/build.gradle.kts b/nms/v1_20R4/build.gradle.kts new file mode 100644 index 00000000..821c3cd3 --- /dev/null +++ b/nms/v1_20R4/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = rootProject.group +version = rootProject.version + +plugins { + id("io.papermc.paperweight.userdev") +} + +dependencies { + implementation(project(":nms:nms-common")) + + // Used for nms + paperweight.paperDevBundle("1.20.6-R0.1-SNAPSHOT") +} + +repositories { + maven("https://repo.papermc.io/repository/maven-public/") + +} + +// Set target version +tasks.withType().configureEach { + sourceCompatibility = "18" + targetCompatibility = "18" + + options.encoding = "UTF-8" +} + +kotlin { + compilerOptions { + apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4) + jvmTarget.set(JvmTarget.JVM_18) + } +} diff --git a/nms/v1_21R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R2_PacketManager.kt b/nms/v1_20R4/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R4_PacketManager.kt similarity index 95% rename from nms/v1_21R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R2_PacketManager.kt rename to nms/v1_20R4/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R4_PacketManager.kt index 9d88c20b..ac1e504d 100644 --- a/nms/v1_21R2/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R2_PacketManager.kt +++ b/nms/v1_20R4/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_20R4_PacketManager.kt @@ -7,7 +7,7 @@ import org.bukkit.entity.Player import xyz.alexcrea.cuanvil.dependency.packet.PacketManager import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase -class V1_21R2_PacketManager : PacketManagerBase(), PacketManager { +class V1_20R4_PacketManager : PacketManagerBase(), PacketManager { override val canSetInstantBuild: Boolean get() = true diff --git a/nms/v1_20R4/src/main/kotlin/xyz/alexcrea/cuanvil/util/MaxDamageCheckerUtil.kt b/nms/v1_20R4/src/main/kotlin/xyz/alexcrea/cuanvil/util/MaxDamageCheckerUtil.kt new file mode 100644 index 00000000..a05d9425 --- /dev/null +++ b/nms/v1_20R4/src/main/kotlin/xyz/alexcrea/cuanvil/util/MaxDamageCheckerUtil.kt @@ -0,0 +1,19 @@ +package xyz.alexcrea.cuanvil.util + +import org.bukkit.Material +import org.bukkit.inventory.meta.Damageable + +// I LOVE support of old versions and needing to do modules like that +// That truly is my favorite activity +// TODO clean this one of legacy removal branch +object MaxDamageCheckerUtil { + + /** + * @return max damage or int max if not set + */ + fun getMaxDamage(type: Material, meta: Damageable): Int { + if(!meta.hasMaxDamage()) return type.maxDurability.toInt() + return meta.maxDamage + } + +} \ No newline at end of file diff --git a/nms/v1_21R5/build.gradle.kts b/nms/v1_21R5/build.gradle.kts deleted file mode 100644 index e7f7c47c..00000000 --- a/nms/v1_21R5/build.gradle.kts +++ /dev/null @@ -1,34 +0,0 @@ -import org.jetbrains.kotlin.gradle.dsl.JvmTarget - -group = rootProject.group -version = rootProject.version - -plugins { - id("io.papermc.paperweight.userdev") -} - -dependencies { - implementation(project(":nms:nms-common")) - - // Used for nms - paperweight.paperDevBundle("1.21.6-R0.1-SNAPSHOT") -} - -repositories { - maven("https://repo.papermc.io/repository/maven-public/") -} - -// Set target version -tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" - - options.encoding = "UTF-8" -} - -kotlin { - compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) - } -} diff --git a/nms/v1_21R5/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R5_PacketManager.kt b/nms/v1_21R5/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R5_PacketManager.kt deleted file mode 100644 index 561a6af4..00000000 --- a/nms/v1_21R5/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R5_PacketManager.kt +++ /dev/null @@ -1,33 +0,0 @@ -package xyz.alexcrea.cuanvil.dependency.packet.versions - -import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket -import net.minecraft.world.entity.player.Abilities -import org.bukkit.craftbukkit.entity.CraftPlayer -import org.bukkit.entity.Player -import xyz.alexcrea.cuanvil.dependency.packet.PacketManager -import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase - -class V1_21R5_PacketManager : PacketManagerBase(), PacketManager { - override val canSetInstantBuild: Boolean - get() = true - - override fun setInstantBuild(player: Player, instantBuild: Boolean) { - val nmsPlayer = (player as CraftPlayer).handle - val playerAbilities = nmsPlayer.abilities - val sendedAbilities: Abilities - if (playerAbilities.instabuild == instantBuild) { - sendedAbilities = playerAbilities - } else { - sendedAbilities = Abilities() - sendedAbilities.invulnerable = playerAbilities.invulnerable - sendedAbilities.flying = playerAbilities.flying - sendedAbilities.mayfly = playerAbilities.mayfly - sendedAbilities.instabuild = instantBuild - sendedAbilities.mayBuild = playerAbilities.mayBuild - sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed - sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed - } - val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) - nmsPlayer.connection.send(packet) - } -} diff --git a/nms/v1_21R6/build.gradle.kts b/nms/v1_21R6/build.gradle.kts deleted file mode 100644 index 3189b5cb..00000000 --- a/nms/v1_21R6/build.gradle.kts +++ /dev/null @@ -1,34 +0,0 @@ -import org.jetbrains.kotlin.gradle.dsl.JvmTarget - -group = rootProject.group -version = rootProject.version - -plugins { - id("io.papermc.paperweight.userdev") -} - -dependencies { - implementation(project(":nms:nms-common")) - - // Used for nms - paperweight.paperDevBundle("1.21.10-R0.1-SNAPSHOT") -} - -repositories { - maven("https://repo.papermc.io/repository/maven-public/") -} - -// Set target version -tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" - - options.encoding = "UTF-8" -} - -kotlin { - compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) - } -} diff --git a/nms/v1_21R6/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/PaperPacketManager.kt b/nms/v1_21R6/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/PaperPacketManager.kt deleted file mode 100644 index ee006666..00000000 --- a/nms/v1_21R6/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/PaperPacketManager.kt +++ /dev/null @@ -1,33 +0,0 @@ -package xyz.alexcrea.cuanvil.dependency.packet.versions - -import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket -import net.minecraft.world.entity.player.Abilities -import org.bukkit.craftbukkit.entity.CraftPlayer -import org.bukkit.entity.Player -import xyz.alexcrea.cuanvil.dependency.packet.PacketManager -import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase - -class V1_21R6_PacketManager : PacketManagerBase(), PacketManager { - override val canSetInstantBuild: Boolean - get() = true - - override fun setInstantBuild(player: Player, instantBuild: Boolean) { - val nmsPlayer = (player as CraftPlayer).handle - val playerAbilities = nmsPlayer.abilities - val sendedAbilities: Abilities - if (playerAbilities.instabuild == instantBuild) { - sendedAbilities = playerAbilities - } else { - sendedAbilities = Abilities() - sendedAbilities.invulnerable = playerAbilities.invulnerable - sendedAbilities.flying = playerAbilities.flying - sendedAbilities.mayfly = playerAbilities.mayfly - sendedAbilities.instabuild = instantBuild - sendedAbilities.mayBuild = playerAbilities.mayBuild - sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed - sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed - } - val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) - nmsPlayer.connection.send(packet) - } -} \ No newline at end of file diff --git a/nms/v1_21R7/build.gradle.kts b/nms/v1_21R7/build.gradle.kts deleted file mode 100644 index 91c3111a..00000000 --- a/nms/v1_21R7/build.gradle.kts +++ /dev/null @@ -1,34 +0,0 @@ -import org.jetbrains.kotlin.gradle.dsl.JvmTarget - -group = rootProject.group -version = rootProject.version - -plugins { - id("io.papermc.paperweight.userdev") -} - -dependencies { - implementation(project(":nms:nms-common")) - - // Used for nms - paperweight.paperDevBundle("1.21.11-R0.1-SNAPSHOT") -} - -repositories { - maven("https://repo.papermc.io/repository/maven-public/") -} - -// Set target version -tasks.withType().configureEach { - sourceCompatibility = "21" - targetCompatibility = "21" - - options.encoding = "UTF-8" -} - -kotlin { - compilerOptions { - apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_2) - jvmTarget.set(JvmTarget.JVM_21) - } -} diff --git a/nms/v1_21R7/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R7_PacketManager.kt b/nms/v1_21R7/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R7_PacketManager.kt deleted file mode 100644 index 59ae9ceb..00000000 --- a/nms/v1_21R7/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/versions/V1_21R7_PacketManager.kt +++ /dev/null @@ -1,33 +0,0 @@ -package xyz.alexcrea.cuanvil.dependency.packet.versions - -import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket -import net.minecraft.world.entity.player.Abilities -import org.bukkit.craftbukkit.entity.CraftPlayer -import org.bukkit.entity.Player -import xyz.alexcrea.cuanvil.dependency.packet.PacketManager -import xyz.alexcrea.cuanvil.dependency.packet.PacketManagerBase - -class V1_21R7_PacketManager : PacketManagerBase(), PacketManager { - override val canSetInstantBuild: Boolean - get() = true - - override fun setInstantBuild(player: Player, instantBuild: Boolean) { - val nmsPlayer = (player as CraftPlayer).handle - val playerAbilities = nmsPlayer.abilities - val sendedAbilities: Abilities - if (playerAbilities.instabuild == instantBuild) { - sendedAbilities = playerAbilities - } else { - sendedAbilities = Abilities() - sendedAbilities.invulnerable = playerAbilities.invulnerable - sendedAbilities.flying = playerAbilities.flying - sendedAbilities.mayfly = playerAbilities.mayfly - sendedAbilities.instabuild = instantBuild - sendedAbilities.mayBuild = playerAbilities.mayBuild - sendedAbilities.flyingSpeed = playerAbilities.flyingSpeed - sendedAbilities.walkingSpeed = playerAbilities.walkingSpeed - } - val packet = ClientboundPlayerAbilitiesPacket(sendedAbilities) - nmsPlayer.connection.send(packet) - } -} \ No newline at end of file diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java b/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java index c4a52daf..4292fa01 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java +++ b/src/main/java/xyz/alexcrea/cuanvil/api/AnvilRecipeBuilder.java @@ -90,6 +90,29 @@ public class AnvilRecipeBuilder { return this; } + /** + * Get the xp level cost per craft. (default 0) + * + * @return The xp level cost per craft + * @deprecated use {@link #getLevelCostPerCraft() getLevelCostPerCraft} instead + */ + @Deprecated(since = "1.13.0") + public int getXpCostPerCraft() { + return getLevelCostPerCraft(); + } + + /** + * Sets the xp level cost per craft. + * + * @param xpCostPerCraft The xp level cost per craft + * @return This recipe builder instance. + * @deprecated use {@link #setLevelCostPerCraft(int) setLevelCostPerCraft} instead + */ + @Deprecated(since = "1.13.0") + public AnvilRecipeBuilder setXpCostPerCraft(int xpCostPerCraft) { + return setLevelCostPerCraft(xpCostPerCraft); + } + /** * Get the xp level cost per craft. (default 0) * diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java b/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java index df0ccfbf..14607664 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java +++ b/src/main/java/xyz/alexcrea/cuanvil/api/ConflictBuilder.java @@ -387,7 +387,7 @@ public class ConflictBuilder { */ protected void appendEnchantments(@NotNull EnchantConflictGroup conflict) { for (String enchantmentName : getEnchantmentNames()) { - if (appendEnchantments(conflict, EnchantmentApi.getByName(enchantmentName)) == 0) { + if (appendEnchantments(conflict, EnchantmentApi.getListByName(enchantmentName)) == 0) { CustomAnvil.instance.getLogger().warning("Could not find enchantment " + enchantmentName + " for conflict " + getName()); ConflictAPI.logConflictOrigin(this); } diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java b/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java index 0bc7aa4d..3e8bb8af 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java +++ b/src/main/java/xyz/alexcrea/cuanvil/api/EnchantmentApi.java @@ -132,14 +132,27 @@ public class EnchantmentApi { return CAEnchantment.getByKey(key); } + /** + * Get by name an enchantment. + * + * @param name The name used to fetch + * @return The custom anvil enchantment of this name. null if not found. + * @deprecated use {@link #getListByName(String)} + */ + @Deprecated(since = "1.6.3") + @Nullable + public static CAEnchantment getByName(@NotNull String name) { + return CAEnchantment.getByName(name); + } + /** * Get list of enchantment using the provided name. * * @param name The name used to fetch * @return List of custom anvil enchantments of this name. May be empty if not found. */ - public static List getByName(@NotNull String name) { - return CAEnchantment.getByName(name); + public static List getListByName(@NotNull String name) { + return CAEnchantment.getListByName(name); } /** diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAClickResultBypassEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAClickResultBypassEvent.java index a27c65e4..fe5e1993 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAClickResultBypassEvent.java +++ b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAClickResultBypassEvent.java @@ -17,7 +17,7 @@ import org.jetbrains.annotations.NotNull; * Most of the time you would likely need {@link CAPreAnvilBypassEvent} or {@link CAEarlyPreAnvilBypassEvent} * for this event to be useful. *

- * There is also {@link CATreatAnvilResultEvent} that may be better for some use case. + * There is also {@link CATreatAnvilResult2Event} that may be better for some use case. */ public class CAClickResultBypassEvent extends Event implements Cancellable { diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAEarlyPreAnvilBypassEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAEarlyPreAnvilBypassEvent.java index 2fbd275d..e92b4cdb 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAEarlyPreAnvilBypassEvent.java +++ b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAEarlyPreAnvilBypassEvent.java @@ -15,7 +15,7 @@ import org.jetbrains.annotations.NotNull; *

* You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful. *

- * It is also recommended that you read about {@link CAPreAnvilBypassEvent} and {@link CATreatAnvilResultEvent} + * It is also recommended that you read about {@link CAPreAnvilBypassEvent} and {@link CATreatAnvilResult2Event} * as your use case may be more prone to use theses. */ public class CAEarlyPreAnvilBypassEvent extends Event implements Cancellable { diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAPreAnvilBypassEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAPreAnvilBypassEvent.java index 18334e36..9103a4b2 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAPreAnvilBypassEvent.java +++ b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CAPreAnvilBypassEvent.java @@ -18,7 +18,7 @@ import org.jetbrains.annotations.NotNull; *

* You should also use {@link CAClickResultBypassEvent} if you want to use this event for something useful. *

- * It is also recommended that you read about {@link CAEarlyPreAnvilBypassEvent} and {@link CATreatAnvilResultEvent} + * It is also recommended that you read about {@link CAEarlyPreAnvilBypassEvent} and {@link CATreatAnvilResult2Event} * as your use case may be more prone to use theses. */ public class CAPreAnvilBypassEvent extends Event implements Cancellable { diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResult2Event.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResult2Event.java new file mode 100644 index 00000000..30c53806 --- /dev/null +++ b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResult2Event.java @@ -0,0 +1,196 @@ +package xyz.alexcrea.cuanvil.api.event.listener; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import xyz.alexcrea.cuanvil.anvil.AnvilCost; +import xyz.alexcrea.cuanvil.anvil.AnvilUseType; + +/** + * Called after custom anvil processed the click on the result on the anvil inventory. + * This event should be used to modify the result of an anvil use. + *

+ * You may also want to check {@link CAClickResultBypassEvent}, + * {@link CAPreAnvilBypassEvent} + * and {@link CAEarlyPreAnvilBypassEvent} for your use case + *

+ * A null result will cancel this event + */ +@SuppressWarnings("unused") +public class CATreatAnvilResult2Event extends Event { + + private static final HandlerList HANDLERS = new HandlerList(); + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public @NotNull HandlerList getHandlers() { + return HANDLERS; + } + + @NotNull + private final InventoryView view; + + private final AnvilUseType useType; + + @Nullable + private final ItemStack left; + @Nullable + private final ItemStack right; + + @Nullable + private ItemStack result; + + private final AnvilCost cost; + + @ApiStatus.Internal + public CATreatAnvilResult2Event( + @NotNull InventoryView view, + Inventory inv, + AnvilUseType useType, + @Nullable ItemStack result, + AnvilCost cost) { + this.view = view; + this.useType = useType; + + this.left = inv.getItem(0); // TODO use view here + this.right = inv.getItem(1); + this.result = result; + this.cost = cost; + } + + /** + * Get the bukkit inventory view. + *

+ * Temporarily marked as internal as it will get changed to anvil view on legacy removal + * so signature will change + * + * @return The inventory view of this event. + */ + @ApiStatus.Internal + public @NotNull InventoryView getView() { + return view; + } + + + /** + * Get the type of use source of the result. + * + * @return The craft use type. + */ + public AnvilUseType getUseType() { + return useType; + } + + /** + * Get the left item of the anvil use + * + * @return the left item + */ + public @Nullable ItemStack getLeftItem() { + return left; + } + + /** + * Get the right item of the anvil use + * + * @return the right item + */ + public @Nullable ItemStack getRightItem() { + return right; + } + + /** + * Get the current result + *

+ * note that it will not be null unless another listener previously set it to null. + * + * @return The current result. + */ + public @Nullable ItemStack getResult() { + return result; + } + + /** + * Set the current result + *

+ * note that a null result will cancel this anvil use. + * + * @param result The new result + */ + public void setResult(@Nullable ItemStack result) { + this.result = result; + } + + /** + * Get the level cost displayed on the anvil. + *

Important note:

+ * the final price are re calculated on click for the following use case: + *
    + *
  • Custom craft
  • + *
  • Unit repair
  • + *
  • Lore edit
  • + *
+ * This value will be used as final price for: + *
  • Item merge
  • + *
  • Item rename
  • + * + * + * @return The current cost. + * @deprecated use #{@link #getCost()} instead + */ + @Deprecated(forRemoval = true, since = "1.17.0") + public int getLevelCost() { + return cost.asXpCost(); + } + + /** + * Set the level cost displayed on the anvil. + *

    Important note:

    + * the final price are re calculated on click for the following use case: + *
      + *
    • Custom craft
    • + *
    • Unit repair
    • + *
    • Lore edit
    • + *
    + * This value will be used as final price for: + *
  • Item merge
  • + *
  • Item rename
  • + * + * + * @param levelCost The new cost. + * @deprecated use #{@link #getCost()} and set value on this instead + */ + @Deprecated(forRemoval = true, since = "1.17.0") + public void setLevelCost(int levelCost) { + cost.setGeneric(levelCost - cost.getGeneric() - cost.asXpCost()); + } + + /** + * Allow access to the current cost of the event + * Note that modifying this object will change the event resulting cost + * + *

    Important note:

    + * the final price are re calculated on click for the following use case: + *
      + *
    • Custom craft
    • + *
    • Unit repair
    • + *
    • Lore edit
    • + *
    + * This value will be used as final price for: + *
  • Item merge
  • + *
  • Item rename
  • + * + * @return the current anvil cost + */ + public AnvilCost getCost() { + return cost; + } +} diff --git a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResultEvent.java b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResultEvent.java index 703a2829..80965b57 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResultEvent.java +++ b/src/main/java/xyz/alexcrea/cuanvil/api/event/listener/CATreatAnvilResultEvent.java @@ -2,8 +2,8 @@ package xyz.alexcrea.cuanvil.api.event.listener; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.PrepareAnvilEvent; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.view.AnvilView; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import xyz.alexcrea.cuanvil.anvil.AnvilCost; @@ -17,9 +17,13 @@ import xyz.alexcrea.cuanvil.anvil.AnvilUseType; * {@link CAPreAnvilBypassEvent} * and {@link CAEarlyPreAnvilBypassEvent} for your use case *

    - * A null result will cancel this event + * A null result will cancel this pre anvil event + * + * @deprecated Prepare anvil Event cannot be provided as it can be called on result and therefore not have prepared anvil event + * use {@link CATreatAnvilResult2Event} instead */ -@SuppressWarnings({"unused", "UnstableApiUsage"}) +@SuppressWarnings("unused") +@Deprecated(forRemoval = true, since = "1.17.0") public class CATreatAnvilResultEvent extends Event { private static final HandlerList HANDLERS = new HandlerList(); @@ -34,44 +38,31 @@ public class CATreatAnvilResultEvent extends Event { } @NotNull - private final AnvilView view; + private final PrepareAnvilEvent event; private final AnvilUseType useType; - @Nullable - private final ItemStack left; - @Nullable - private final ItemStack right; - @Nullable private ItemStack result; private final AnvilCost cost; - public CATreatAnvilResultEvent( - @NotNull AnvilView view, - AnvilUseType useType, - @Nullable ItemStack result, - AnvilCost cost) { - this.view = view; + public CATreatAnvilResultEvent(@NotNull PrepareAnvilEvent event, AnvilUseType useType, @Nullable ItemStack result, AnvilCost cost) { + this.event = event; this.useType = useType; - - this.left = view.getItem(0); - this.right = view.getItem(1); this.result = result; this.cost = cost; } /** - * Get the bukkit inventory view. + * Get the bukkit inventory click event causing to this event. * - * @return The inventory view of this event. + * @return The click event causing to this event. */ - public @NotNull AnvilView getView() { - return view; + public @NotNull PrepareAnvilEvent getEvent() { + return event; } - /** * Get the type of use source of the result. * @@ -81,24 +72,6 @@ public class CATreatAnvilResultEvent extends Event { return useType; } - /** - * Get the left item of the anvil use - * - * @return the left item - */ - public @Nullable ItemStack getLeftItem() { - return left; - } - - /** - * Get the right item of the anvil use - * - * @return the right item - */ - public @Nullable ItemStack getRightItem() { - return right; - } - /** * Get the current result *

    @@ -121,6 +94,50 @@ public class CATreatAnvilResultEvent extends Event { this.result = result; } + /** + * Get the level cost displayed on the anvil. + *

    Important note:

    + * the final price are re calculated on click for the following use case: + *
      + *
    • Custom craft
    • + *
    • Unit repair
    • + *
    • Lore edit
    • + *
    + * This value will be used as final price for: + *
  • Item merge
  • + *
  • Item rename
  • + * + * + * @return The current cost. + * @deprecated use #{@link #getCost()} instead + */ + @Deprecated(forRemoval = true, since = "1.17.0") + public int getLevelCost() { + return cost.asXpCost(); + } + + /** + * Set the level cost displayed on the anvil. + *

    Important note:

    + * the final price are re calculated on click for the following use case: + *
      + *
    • Custom craft
    • + *
    • Unit repair
    • + *
    • Lore edit
    • + *
    + * This value will be used as final price for: + *
  • Item merge
  • + *
  • Item rename
  • + * + * + * @param levelCost The new cost. + * @deprecated use #{@link #getCost()} and set value on this instead + */ + @Deprecated(forRemoval = true, since = "1.17.0") + public void setLevelCost(int levelCost) { + cost.setGeneric(levelCost - cost.getGeneric() - cost.asXpCost()); + } + /** * Allow access to the current cost of the event * Note that modifying this object will change the event resulting cost @@ -141,4 +158,5 @@ public class CATreatAnvilResultEvent extends Event { public AnvilCost getCost() { return cost; } + } diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java index e17b36d0..95f3001b 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java +++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantment.java @@ -235,13 +235,24 @@ public interface CAEnchantment { } /** - * Gets list of enchantment using the provided name. - * + * Gets the enchantment by the provided name. * @param name Name to fetch. - * @return List of registered enchantment. + * @return Registered enchantment. null if absent. + * + * @deprecated use {@link #getListByName(String)} */ - static List getByName(@NotNull String name){ + @Deprecated(since = "1.6.3") + static @Nullable CAEnchantment getByName(@NotNull String name){ return CAEnchantmentRegistry.getInstance().getByName(name); } + /** + * Gets list of enchantment using the provided name. + * @param name Name to fetch. + * @return List of registered enchantment. + */ + static List getListByName(@NotNull String name){ + return CAEnchantmentRegistry.getInstance().getListByName(name); + } + } diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java index 13674f33..b1f9a7b8 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java +++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/CAEnchantmentRegistry.java @@ -154,6 +154,22 @@ public class CAEnchantmentRegistry { return byKeyMap.get(key); } + /** + * Gets the enchantment by the provided name. + * + * @param name Name to fetch. + * @return Registered enchantment. null if absent. + * @deprecated use {@link #getListByName(String)} + */ + @Deprecated(since = "1.6.3") + @Nullable + public CAEnchantment getByName(@NotNull String name) { + List enchantments = getListByName(name); + if (enchantments.isEmpty()) return null; + + return enchantments.get(0); + } + /** * Gets list of enchantment using the provided name. * @@ -161,7 +177,7 @@ public class CAEnchantmentRegistry { * @return List of registered enchantment. */ @NotNull - public List getByName(@NotNull String name) { + public List getListByName(@NotNull String name) { return byNameMap.getOrDefault(name, Collections.emptyList()); } diff --git a/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java b/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java index 7ad3269e..3718f39b 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java +++ b/src/main/java/xyz/alexcrea/cuanvil/enchant/EnchantmentRarity.java @@ -1,6 +1,6 @@ package xyz.alexcrea.cuanvil.enchant; -// because spigot (1.21) do not look like to provide access to enchantment rarity I need to do it myself... +// because spigot (1.18) do not look like to provide access to enchantment rarity I need to do it myself... public class EnchantmentRarity { public static final EnchantmentRarity NO_RARITY = new EnchantmentRarity(0, 0); diff --git a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java index 4473eb29..397ae6f5 100644 --- a/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java +++ b/src/main/java/xyz/alexcrea/cuanvil/gui/config/settings/EnchantSelectSettingGui.java @@ -141,10 +141,10 @@ public class EnchantSelectSettingGui extends SettingGuiListConfigGui 0) @@ -306,7 +311,7 @@ object AnvilMergeLogic { } val result = - DependencyManager.tryTreatAnvilResult(view, player, resultItem, AnvilUseType.UNIT_REPAIR, cost) + DependencyManager.tryTreatAnvilResult(view, inventory, player, resultItem, AnvilUseType.UNIT_REPAIR, cost) return UnitRepairResult(result, cost, repairAmount) } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CASubCommand.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/CASubCommand.kt index ede87e9a..60dcdbee 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CASubCommand.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/CASubCommand.kt @@ -1,29 +1,50 @@ package xyz.alexcrea.cuanvil.command +import org.bukkit.ChatColor import org.bukkit.command.Command +import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry -interface CASubCommand { +abstract class CASubCommand: CommandExecutor { - fun executeCommand( + private var alreadySaid = false; + override fun onCommand( sender: CommandSender, cmd: Command, cmdstr: String, args: Array - ): Boolean + ): Boolean { + if(!alreadySaid){ + sender.sendMessage(ChatColor.RED.toString() + + "Please not that this command will be replaced as a subcommand of `/customanvil` or `/ca`") + alreadySaid = true + } - fun allowed(sender: CommandSender): Boolean + return executeCommand(sender, cmd, cmdstr, args) + } - fun tabCompleter( + abstract fun executeCommand( + sender: CommandSender, + cmd: Command, + cmdstr: String, + args: Array): Boolean + + open fun allowed(sender: CommandSender): Boolean { + return true + } + + open fun tabCompleter( sender: CommandSender, args: Array, - list: MutableList - ) + list: MutableList) { + } - fun description(): String + open fun description(): String { + return "no description" + } - fun allEnchantmentsByName(): Collection { + protected fun allEnchantmentsByName(): Collection { val names = mutableSetOf() for (enchantment in CAEnchantmentRegistry.getInstance().values()) { names.add(enchantment.name) diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CustomAnvilCommand.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/CustomAnvilCommand.kt index 1cae583f..9b9402c9 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/CustomAnvilCommand.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/CustomAnvilCommand.kt @@ -46,17 +46,17 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter { val subcmdStr: String val newargs: Array - if (args.isEmpty()) { + if(args.isEmpty()) { subcmdStr = "config" subcmd = editConfigCommand newargs = args - } else { + }else { subcmdStr = args[0].lowercase() subcmd = commands[subcmdStr] newargs = args.copyOfRange(1, args.size) } - if (subcmd == null || !subcmd.allowed(sender)) { + if(subcmd == null || !subcmd.allowed(sender)) { sender.sendMessage("Invalid subcommand. run `$cmdstr help` to see available commands") return true } @@ -77,18 +77,18 @@ class CustomAnvilCommand(plugin: CustomAnvil) : CommandExecutor, TabCompleter { args: Array ): MutableList { val result = ArrayList() - if (args.size < 2) { - for ((key, cmd) in commands) { - if (!cmd.allowed(sender)) continue - if("gui".contentEquals(key)) continue + if(args.size < 2) { + for ((key, cmd) in commands) { + if(!cmd.allowed(sender)) continue + if("gui".contentEquals(key)) continue result.add(key) } } else { val subcmd = commands[args[0].lowercase()] - if (subcmd != null) { + if(subcmd != null) { val newArgs = args.copyOfRange(1, args.size) - if (!subcmd.allowed(sender)) return result + if(!subcmd.allowed(sender)) return result subcmd.tabCompleter(sender, newArgs, result) } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/DebugToggleExecutor.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/DebugToggleExecutor.kt index 302ff782..c668e6e0 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/DebugToggleExecutor.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/DebugToggleExecutor.kt @@ -12,7 +12,7 @@ import org.bukkit.command.CommandSender import org.bukkit.entity.Player import xyz.alexcrea.cuanvil.command.DiagnosticExecutor.Companion.NO_DIAG_PERM -class DebugToggleExecutor : CASubCommand { +class DebugToggleExecutor : CASubCommand() { override fun description(): String { return "Used to toggle debug logs and retrieve it" diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/DiagnosticExecutor.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/DiagnosticExecutor.kt index c2293afc..75459728 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/DiagnosticExecutor.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/DiagnosticExecutor.kt @@ -1,5 +1,6 @@ package xyz.alexcrea.cuanvil.command +import com.github.stefvanschie.inventoryframework.inventoryview.interface_.InventoryViewUtil import io.delilaheve.CustomAnvil import net.md_5.bungee.api.chat.ClickEvent import net.md_5.bungee.api.chat.HoverEvent @@ -15,10 +16,11 @@ import org.bukkit.entity.HumanEntity import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryType import org.bukkit.event.inventory.PrepareAnvilEvent +import org.bukkit.inventory.AnvilInventory +import org.bukkit.inventory.InventoryView import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.Damageable import org.bukkit.inventory.meta.EnchantmentStorageMeta -import org.bukkit.inventory.view.AnvilView import org.bukkit.plugin.Plugin import org.bukkit.plugin.RegisteredListener import xyz.alexcrea.cuanvil.dependency.DependencyManager @@ -30,9 +32,10 @@ import xyz.alexcrea.cuanvil.util.MetricsUtil import java.util.* import java.util.stream.Collectors -class DiagnosticExecutor : CASubCommand { - companion object { +class DiagnosticExecutor: CASubCommand() { + + companion object{ const val NO_DIAG_PERM = "You do not have permission to diagnostic this server" fun fetchNMSType(): String { @@ -40,7 +43,7 @@ class DiagnosticExecutor : CASubCommand { val packetManagerClass = packetManager.javaClass val className = packetManagerClass.name - val result = if (className.contains("PaperPacket")) { + val result = if(className.contains("PaperPacket")) { "Paper" } else { when (packetManagerClass) { @@ -51,7 +54,7 @@ class DiagnosticExecutor : CASubCommand { } - return "$result ${if (packetManager.canSetInstantBuild) '✅' else '❌'}" + return "$result ${if(packetManager.canSetInstantBuild) '✅' else '❌'}" } } @@ -72,7 +75,7 @@ class DiagnosticExecutor : CASubCommand { } for (param in DiagParams.entries) { - if (argSet.contains(param.value)) + if(argSet.contains(param.value)) result.add(param) } @@ -82,13 +85,12 @@ class DiagnosticExecutor : CASubCommand { override fun tabCompleter( sender: CommandSender, args: Array, - list: MutableList - ) { - if (!allowed(sender)) return + list: MutableList) { + if(!allowed(sender)) return val map = fetchParameters(args) for (param in DiagParams.entries) { - if (!map.contains(param)) + if(!map.contains(param)) list.add(param.value) } @@ -110,7 +112,7 @@ class DiagnosticExecutor : CASubCommand { var hasError = false try { diagnostic(sender, stb, params) - } catch (e: Throwable) { + } catch(e: Throwable){ stb.append("\n\nError happened trying to get diagnostic data:\n") .append(e.message).append("\n") .append(e.stackTrace.joinToString("\n")) @@ -121,9 +123,8 @@ class DiagnosticExecutor : CASubCommand { stb.append("\n```") if (sender is HumanEntity) { - if (hasError) - sender.spigot() - .sendMessage(TextComponent(ChatColor.RED.toString() + "There was an error running the diagnostic")) + if(hasError) + sender.spigot().sendMessage(TextComponent(ChatColor.RED.toString() + "There was an error running the diagnostic")) val message = TextComponent(ChatColor.GREEN.toString() + "Click to copy diagnostic data") message.clickEvent = ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, stb.toString()) @@ -141,41 +142,41 @@ class DiagnosticExecutor : CASubCommand { return sender.hasPermission(CustomAnvil.diagnosticPermission) } - fun diagnostic(sender: CommandSender, stb: StringBuilder, params: Set) { + fun diagnostic(sender: CommandSender, stb: StringBuilder, params: Set){ stb.append("Server Info\n") val version = CustomAnvil.instance.description.version stb.append("\nPlugin Version: ").append(version) - if (version.contains("dev")) stb.append(" (alpha)") + if(version.contains("dev")) stb.append(" (alpha)") stb.append("\nLatest Update: ").append(CustomAnvil.latestVer) stb.append("\nServer Version: ").append(Bukkit.getVersion()).append(" (").append(Bukkit.getName()).append(')') - stb.append("\nPlugin Enabled: ").append(if (CustomAnvil.instance.isEnabled) "Yes" else "No") + stb.append("\nPlugin Enabled: ").append(if(CustomAnvil.instance.isEnabled) "Yes" else "No") stb.append("\nNMS type: ").append(fetchNMSType()) - if (!params.contains(DiagParams.OS_PRIVACY)) { + if(!params.contains(DiagParams.OS_PRIVACY)) { stb.append("\nJava Version: ").append(System.getProperty("java.version")) stb.append("\nOS: ").append(System.getProperty("os.name")).append(" ") .append(System.getProperty("os.version")) .append(System.getProperty("os.arch")) } - stb.append("\nHad detect error: ").append(if (MetricsUtil.lastError != null) "Yes" else "No") + stb.append("\nHad detect error: ").append(if(MetricsUtil.lastError != null) "Yes" else "No") - if (!params.contains(DiagParams.PLUGIN_PRIVACY)) { + if(!params.contains(DiagParams.PLUGIN_PRIVACY)) { pluginListDiag(sender, stb) } prepareAnvilListeners(stb) - if (!params.contains(DiagParams.NO_MERGE_TEST)) { - if (sender is Player) testMerge(sender, stb) + if(!params.contains(DiagParams.NO_MERGE_TEST)){ + if(sender is Player) testMerge(sender, stb) } stb.append("\n\nEnchantments data:") partialEnchantmentData(stb) - if (params.contains(DiagParams.FULL_ENCHANTMENT_DATA)) { + if(params.contains(DiagParams.FULL_ENCHANTMENT_DATA)){ fullEnchantmentData(stb) } - if (params.contains(DiagParams.INCLUDE_LAST_ERROR)) { + if(params.contains(DiagParams.INCLUDE_LAST_ERROR)){ includeLastError(stb) } } @@ -192,11 +193,11 @@ class DiagnosticExecutor : CASubCommand { damagedSword.itemMeta = meta meta = enchantedSword.itemMeta - meta!!.addEnchant(Enchantment.SHARPNESS, 1, true) + meta!!.addEnchant(Enchantment.DAMAGE_ALL, 1, true) enchantedSword.itemMeta = meta meta = enchantedBook.itemMeta - (meta as EnchantmentStorageMeta).addStoredEnchant(Enchantment.SHARPNESS, 1, true) + (meta as EnchantmentStorageMeta).addStoredEnchant(Enchantment.DAMAGE_ALL, 1, true) enchantedBook.itemMeta = meta stb.append("\n\nItem to Item repair:") @@ -261,11 +262,11 @@ class DiagnosticExecutor : CASubCommand { } fun simulateAnvil(player: Player, stb: StringBuilder, left: ItemStack?, right: ItemStack?, result: ItemStack?) { - var invView: AnvilView + var invView: InventoryView var event: PrepareAnvilEvent try { val fakeInv = Bukkit.createInventory(player, InventoryType.ANVIL) - invView = player.openInventory(fakeInv)!! as AnvilView + invView = player.openInventory(fakeInv)!! event = DependencyManager.createFakeEvent(invView, result) } catch (_: Throwable) { // Help @@ -273,40 +274,42 @@ class DiagnosticExecutor : CASubCommand { val anvilTypeField = menuTypeClazz.getField("ANVIL") val anvilType = anvilTypeField.get(null) val createMethod = anvilType.javaClass.getMethod("create", HumanEntity::class.java) - invView = createMethod.invoke(anvilType, player) as AnvilView + invView = createMethod.invoke(anvilType, player) as InventoryView player.openInventory(invView) - val constructor = PrepareAnvilEvent::class.java.getConstructor(AnvilView::class.java, ItemStack::class.java) + val anvilViewClass = Class.forName("org.bukkit.inventory.view.AnvilView") + val constructor = PrepareAnvilEvent::class.java.getConstructor(anvilViewClass, ItemStack::class.java) event = constructor.newInstance(invView, result) } - invView.setItem(0, left) - invView.setItem(1, right) + val fakeInv = InventoryViewUtil.getInstance().getTopInventory(invView) as AnvilInventory + fakeInv.setItem(0, left) + fakeInv.setItem(1, right) - val xp = invView.repairCost - val maxXp = invView.maximumRepairCost - val mergeResult = invView.getItem(2) - stb.append("\n${if (result == mergeResult) "E" else "Une"}xpected Result") + val xp = fakeInv.repairCost + val maxXp = fakeInv.maximumRepairCost + val mergeResult = fakeInv.getItem(2) + stb.append("\n${if(result == mergeResult) "E" else "Une"}xpected Result") PrepareAnvilListener().anvilCombineCheck(event) // Now we check if item and xp same stb.append("\nXP/Max XP: ") - .append(if (invView.repairCost == xp) "Correct" else "Incorrect") + .append(if(fakeInv.repairCost == xp) "Correct" else "Incorrect") .append("/") - .append(if (invView.maximumRepairCost == maxXp) "Correct" else "Incorrect") - .append(" (${invView.repairCost} $xp|${invView.maximumRepairCost} $maxXp)") + .append(if(fakeInv.maximumRepairCost == maxXp) "Correct" else "Incorrect") + .append(" (${fakeInv.repairCost} $xp|${fakeInv.maximumRepairCost} $maxXp)") .append("\nMerge result: ") - .append(if (invView.getItem(2) == mergeResult) "Correct" else "Incorrect") + .append(if(fakeInv.getItem(2) == mergeResult) "Correct" else "Incorrect") PrepareAnvilListener.IS_EMPTY_TEST = true Bukkit.getPluginManager().callEvent(event) stb.append("\nNull result test: ") - .append(if (event.result == null) "Correct" else "Incorrect") + .append(if(event.result == null) "Correct" else "Incorrect") - invView.setItem(0, null) - invView.setItem(1, null) - invView.setItem(2, null) + fakeInv.setItem(0, null) + fakeInv.setItem(1, null) + fakeInv.setItem(2, null) player.closeInventory() } @@ -324,13 +327,11 @@ class DiagnosticExecutor : CASubCommand { map[enchant.key.namespace] = map.getOrDefault(enchant.key.namespace, 0) + 1 } - stb.append( - "\nNamespaces: ${ - map.entries.stream() - .map { (key, value) -> "$key ($value)" } - .reduce { a, b -> "$a, $b" }.get() - }" - ) + stb.append("\nNamespaces: ${ + map.entries.stream() + .map { (key, value) -> "$key ($value)" } + .reduce { a, b -> "$a, $b" }.get() + }") } @@ -340,6 +341,7 @@ class DiagnosticExecutor : CASubCommand { stb.append("\n\nLast stack trace: ${e.stackTraceToString()}") - } + } + } \ No newline at end of file diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/EditConfigExecutor.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/EditConfigExecutor.kt index 79151cd3..c6bc191b 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/EditConfigExecutor.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/EditConfigExecutor.kt @@ -14,7 +14,7 @@ import xyz.alexcrea.cuanvil.gui.util.GuiGlobalActions import xyz.alexcrea.cuanvil.util.MaterialUtil.customType import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir -class EditConfigExecutor : CASubCommand { +class EditConfigExecutor : CASubCommand() { override fun allowed(sender: CommandSender): Boolean { return sender.hasPermission(CustomAnvil.editConfigPermission) @@ -72,7 +72,7 @@ class EditConfigExecutor : CASubCommand { return } } else { - enchantToFilter = HashSet(EnchantmentApi.getByName(args[1].lowercase())) + enchantToFilter = HashSet(EnchantmentApi.getListByName(args[1].lowercase())) if (enchantToFilter.isEmpty()) { sender.sendMessage("No enchantment found with the name \"${args[1]}\"") diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/EnchantExecutor.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/EnchantExecutor.kt index 654df1a8..1bdf56a1 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/EnchantExecutor.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/EnchantExecutor.kt @@ -12,7 +12,7 @@ import xyz.alexcrea.cuanvil.api.EnchantmentApi import xyz.alexcrea.cuanvil.enchant.CAEnchantment import xyz.alexcrea.cuanvil.util.MaterialUtil.isAir -class EnchantExecutor : CASubCommand { +class EnchantExecutor : CASubCommand() { override fun allowed(sender: CommandSender): Boolean { @@ -116,7 +116,7 @@ class EnchantExecutor : CASubCommand { } private fun firstEnchantment(name: String): CAEnchantment? { - val enchants = EnchantmentApi.getByName(name.lowercase()) + val enchants = EnchantmentApi.getListByName(name.lowercase()) if (!enchants.isEmpty()) return enchants.iterator().next() diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/HelpExecutor.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/HelpExecutor.kt index c6c4d08c..697f1ee2 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/HelpExecutor.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/HelpExecutor.kt @@ -4,20 +4,18 @@ import com.google.common.collect.ImmutableMap import org.bukkit.command.Command import org.bukkit.command.CommandSender -class HelpExecutor : CASubCommand { +class HelpExecutor: CASubCommand() { lateinit var commands: ImmutableMap - override fun executeCommand( - sender: CommandSender, - cmd: Command, - cmdstr: String, - args: Array - ): Boolean { + override fun executeCommand(sender: CommandSender, + cmd: Command, + cmdstr: String, + args: Array): Boolean { val stb = StringBuilder("List of available commands:") for ((key, cmd) in commands) { - if (!cmd.allowed(sender)) continue + if(!cmd.allowed(sender)) continue stb.append("\n- $key: ").append(cmd.description()) } @@ -27,17 +25,6 @@ class HelpExecutor : CASubCommand { return true } - override fun allowed(sender: CommandSender): Boolean { - return true - } - - override fun tabCompleter( - sender: CommandSender, - args: Array, - list: MutableList - ) { - } - override fun description(): String { return "Help command" } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/command/ReloadExecutor.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/command/ReloadExecutor.kt index d3df341a..cb0d24a9 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/command/ReloadExecutor.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/command/ReloadExecutor.kt @@ -10,14 +10,12 @@ import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.gui.config.global.* import xyz.alexcrea.cuanvil.update.UpdateHandler -class ReloadExecutor : CASubCommand { +class ReloadExecutor : CASubCommand() { - override fun executeCommand( - sender: CommandSender, - cmd: Command, - cmdstr: String, - args: Array - ): Boolean { + override fun executeCommand(sender: CommandSender, + cmd: Command, + cmdstr: String, + args: Array): Boolean { if (!allowed(sender)) { sender.sendMessage("§cYou do not have permission to reload the config") return false @@ -40,13 +38,6 @@ class ReloadExecutor : CASubCommand { return sender.hasPermission(CustomAnvil.commandReloadPermission) } - override fun tabCompleter( - sender: CommandSender, - args: Array, - list: MutableList - ) { - } - override fun description(): String { return "Reload the configuration of this plugin" } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/DependencyManager.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/DependencyManager.kt index 66dd5db4..e736a8fa 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/DependencyManager.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/DependencyManager.kt @@ -1,5 +1,6 @@ package xyz.alexcrea.cuanvil.dependency +import com.maddoxh.superEnchants.SuperEnchants import io.delilaheve.CustomAnvil import net.kyori.adventure.text.Component import org.bukkit.Bukkit @@ -9,14 +10,16 @@ import org.bukkit.entity.HumanEntity import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.PrepareAnvilEvent +import org.bukkit.inventory.AnvilInventory +import org.bukkit.inventory.Inventory +import org.bukkit.inventory.InventoryView import org.bukkit.inventory.ItemStack -import org.bukkit.inventory.view.AnvilView import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilUseType import xyz.alexcrea.cuanvil.api.event.listener.CAClickResultBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAEarlyPreAnvilBypassEvent import xyz.alexcrea.cuanvil.api.event.listener.CAPreAnvilBypassEvent -import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent +import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResult2Event import xyz.alexcrea.cuanvil.config.ConfigHolder import xyz.alexcrea.cuanvil.dependency.datapack.DataPackDependency import xyz.alexcrea.cuanvil.dependency.gui.GenericExternGuiTester @@ -30,16 +33,17 @@ import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil.componentLore import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_OUTPUT_SLOT import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError -import java.lang.reflect.Constructor +import java.lang.IllegalStateException import java.util.logging.Level -@Suppress("UnstableApiUsage") object DependencyManager { lateinit var scheduler: TaskScheduler lateinit var packetManager: PacketManager var externGuiTester: GenericExternGuiTester = GenericExternGuiTester() + val inTesting = externGuiTester.isInTest() + var enchantmentSquaredCompatibility: EnchantmentSquaredDependency? = null var ecoEnchantCompatibility: EcoEnchantDependency? = null var hasEcoItem: Boolean = false @@ -121,7 +125,7 @@ object DependencyManager { genericDependencies.add(GenericPluginDependency(pluginManager.getPlugin("ItemsAdder")!!)) if (pluginManager.isPluginEnabled("SuperEnchants")) { - val compatibility = SuperEnchantDependency(pluginManager.getPlugin("SuperEnchants")!!) + val compatibility = SuperEnchantDependency(pluginManager.getPlugin("SuperEnchants")!! as SuperEnchants) if (compatibility.registerEnchantments()) genericDependencies.add(compatibility) } @@ -172,11 +176,11 @@ object DependencyManager { ) } - private fun logExceptionAndClear(view: AnvilView, e: Exception) { + private fun logExceptionAndClear(target: CommandSender, inventory: Inventory, e: Exception) { // Just in case to avoid illegal items - view.setItem(ANVIL_OUTPUT_SLOT, null) + inventory.setItem(ANVIL_OUTPUT_SLOT, null) - logException(view.player, e) + logException(target, e) } // Return true if should bypass (either by a dependency or error) @@ -185,7 +189,7 @@ object DependencyManager { try { return earlyUnsafeTryEventPreAnvilBypass(event, player) } catch (e: Exception) { - logExceptionAndClear(event.view, e) + logExceptionAndClear(event.view.player, event.inventory, e) return true } } @@ -211,7 +215,7 @@ object DependencyManager { try { return unsafeTryEventPreAnvilBypass(event, player) } catch (e: Exception) { - logExceptionAndClear(event.view, e) + logExceptionAndClear(event.view.player, event.inventory, e) return true } } @@ -241,39 +245,40 @@ object DependencyManager { // Return null if there was an issue fun tryTreatAnvilResult( - view: AnvilView, + view: InventoryView, + inventory: Inventory, // TODO REMOVE, use view instead on legacy removal player: HumanEntity, result: ItemStack, useType: AnvilUseType, cost: AnvilCost ): ItemStack? { - val treatEvent = CATreatAnvilResultEvent(view, useType, result, cost) + val treatEvent = CATreatAnvilResult2Event(view, inventory, useType, result, cost) try { unsafeTryTreatAnvilResult(treatEvent) return treatEvent.result } catch (e: Exception) { - logExceptionAndClear(view, e) + logExceptionAndClear(player, inventory, e) return null } } - private fun unsafeTryTreatAnvilResult(event: CATreatAnvilResultEvent) { + private fun unsafeTryTreatAnvilResult(event: CATreatAnvilResult2Event) { Bukkit.getPluginManager().callEvent(event) excellentEnchantsCompatibility?.treatAnvilResult(event) } // Return true if should bypass (either by a dependency or error) - fun tryClickAnvilResultBypass(event: InventoryClickEvent, view: AnvilView): Boolean { + fun tryClickAnvilResultBypass(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { try { - return unsafeTryClickAnvilResultBypass(event, view) + return unsafeTryClickAnvilResultBypass(event, inventory) } catch (e: Exception) { - logExceptionAndClear(view, e) + logExceptionAndClear(event.view.player, event.inventory, e) return true } } - private fun unsafeTryClickAnvilResultBypass(event: InventoryClickEvent, view: AnvilView): Boolean { + private fun unsafeTryClickAnvilResultBypass(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { // Run the event val bypassEvent = CAClickResultBypassEvent(event) Bukkit.getPluginManager().callEvent(bypassEvent) @@ -281,10 +286,10 @@ object DependencyManager { var bypass = bypassEvent.isCancelled // Test if disenchantment used event click - if (!bypass && (disenchantmentCompatibility?.testAnvilResult(event, view) == true)) bypass = true + if (!bypass && (disenchantmentCompatibility?.testAnvilResult(event, inventory) == true)) bypass = true // Test if haven bag used event click - if (!bypass && (havenBagsCompatibility?.testAnvilResult(event, view) == true)) bypass = true + if (!bypass && (havenBagsCompatibility?.testAnvilResult(event, inventory) == true)) bypass = true // Test if disenchantment used event click if (!bypass && (excellentEnchantsCompatibility?.testAnvilResult(event) == true)) bypass = true @@ -294,10 +299,10 @@ object DependencyManager { } // Test if the inventory is a gui(version specific) - if (!bypass && externGuiTester.testIfGui(view)) bypass = true + if (!bypass && externGuiTester.testIfGui(event.view)) bypass = true // Test if in an ax player warp rating gui - if (!bypass && (axPlayerWarpsCompatibility?.testIfGui(view.player) == true)) bypass = true + if (!bypass && (axPlayerWarpsCompatibility?.testIfGui(event.view.player) == true)) bypass = true return bypass } @@ -337,10 +342,14 @@ object DependencyManager { private val prepareAnvilConstructor = - PrepareAnvilEvent::class.java.constructors.first() as Constructor + PrepareAnvilEvent::class.java.constructors.first() - fun createFakeEvent(view: AnvilView, result: ItemStack?): PrepareAnvilEvent { - return prepareAnvilConstructor.newInstance(view, result) + fun createFakeEvent(view: InventoryView, result: ItemStack?): PrepareAnvilEvent { + val result = prepareAnvilConstructor.newInstance(view, result) + if(result !is PrepareAnvilEvent) + throw IllegalStateException("Could not create a PrepareAnvilEvent ?") + + return result } } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/MinecraftVersionUtil.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/MinecraftVersionUtil.kt index 7813cb4e..5d333e29 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/MinecraftVersionUtil.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/MinecraftVersionUtil.kt @@ -10,6 +10,32 @@ object MinecraftVersionUtil { if (version.major != 1) return null return when (version.minor) { + 17 -> when (version.patch) { + 0, 1 -> "1_17R1" + else -> null + } + + 18 -> when (version.patch) { + 0, 1 -> "1_18R1" + 2 -> "1_18R2" + else -> null + } + + 19 -> when (version.patch) { + 0, 1, 2 -> "1_19R1" + 3 -> "1_19R2" + 4 -> "1_19R3" + else -> null + } + + 20 -> when (version.patch) { + 0, 1 -> "1_20R1" + 2 -> "1_20R2" + 3, 4 -> "1_20R3" + 5, 6 -> "1_20R4" + else -> null + } + 21 -> when (version.patch) { 0, 1 -> "1_21R1" 2, 3 -> "1_21R2" @@ -20,16 +46,9 @@ object MinecraftVersionUtil { 11 -> "1_21R7" else -> null } - //TODO need to continue updating that for anvil gui test dependency.... else -> null } } - val isTooNewForSpigot: Boolean - get() { - - return UpdateUtils.currentMinecraftVersion().major != 1 - } - } \ No newline at end of file diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/gui/GenericExternGuiTester.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/gui/GenericExternGuiTester.kt index cd62c816..4046f4ab 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/gui/GenericExternGuiTester.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/gui/GenericExternGuiTester.kt @@ -1,11 +1,10 @@ package xyz.alexcrea.cuanvil.dependency.gui -import org.bukkit.inventory.view.AnvilView +import org.bukkit.inventory.InventoryView import xyz.alexcrea.cuanvil.dependency.MinecraftVersionUtil import xyz.alexcrea.cuanvil.dependency.util.PlatformUtil import java.lang.reflect.Method -@Suppress("UnstableApiUsage") class GenericExternGuiTester { companion object { @@ -22,7 +21,7 @@ class GenericExternGuiTester { var testedClass: String? = null lateinit var getHandleMethod: Method - private fun getContainerClass(view: AnvilView): Class? { + private fun getContainerClass(view: InventoryView): Class? { if(!testedClass.contentEquals(view.javaClass.name)) return null @@ -65,11 +64,11 @@ class GenericExternGuiTester { } // Try if were in another plugin anvil inventory - fun testIfGui(view: AnvilView): Boolean { + fun testIfGui(inventory: InventoryView): Boolean { // In case we are in a test environment if(isInTest()) return false - val clazz = getContainerClass(view) ?: return false + val clazz = getContainerClass(inventory) ?: return false val clazzName = clazz.name if(!PlatformUtil.isPaper){ diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/PacketManagerSelector.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/PacketManagerSelector.kt index e21a66ed..69ca28cc 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/PacketManagerSelector.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/packet/PacketManagerSelector.kt @@ -3,7 +3,7 @@ package xyz.alexcrea.cuanvil.dependency.packet import org.bukkit.Bukkit import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.dependency.MinecraftVersionUtil -import xyz.alexcrea.cuanvil.dependency.packet.versions.PaperPacketManager +import xyz.alexcrea.cuanvil.dependency.packet.versions.* import xyz.alexcrea.cuanvil.update.UpdateUtils object PacketManagerSelector { @@ -12,7 +12,7 @@ object PacketManagerSelector { fun selectPacketManager(forceProtocolib: Boolean): PacketManager { // Try to find version - if(DependencyManager.externGuiTester.isInTest()) + if(DependencyManager.inTesting) return NoPacketManager() return if (forceProtocolib) diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/DisenchantmentDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/DisenchantmentDependency.kt index ba0b330b..690b3846 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/DisenchantmentDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/DisenchantmentDependency.kt @@ -12,8 +12,8 @@ import org.bukkit.entity.Player import org.bukkit.event.Listener import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.PrepareAnvilEvent +import org.bukkit.inventory.AnvilInventory import org.bukkit.inventory.ItemStack -import org.bukkit.inventory.view.AnvilView import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener import xyz.alexcrea.cuanvil.util.MetricsUtil.trackError @@ -21,7 +21,6 @@ import xyz.alexcrea.cuanvil.util.anvil.AnvilXpUtil import java.util.logging.Level import kotlin.reflect.KClass -@Suppress("UnstableApiUsage") class DisenchantmentDependency { init { @@ -60,14 +59,14 @@ class DisenchantmentDependency { DisenchantEvent.onEvent(event) if (event.result != null) { CustomAnvil.log("Detected pre anvil item extract bypass.") - AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost)) + AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) return true } ShatterEvent.onEvent(event) if (event.result != null) { CustomAnvil.log("Detected pre anvil split enchant bypass.") - AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost)) + AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) return true } @@ -75,18 +74,18 @@ class DisenchantmentDependency { return false } - fun testAnvilResult(event: InventoryClickEvent, view: AnvilView): Boolean { - val previousResultSlot = view.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone() + fun testAnvilResult(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { + val previousResultSlot = inventory.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone() // Test event if change the result DisenchantClickEvent.onEvent(event) - if (!testAnvilChange(view, previousResultSlot) || event.isCancelled) { + if (!testAnvilInventoryChange(inventory, previousResultSlot) || event.isCancelled) { CustomAnvil.log("Detected anvil click item extract bypass.") return true } ShatterClickEvent.onEvent(event) - if (!testAnvilChange(view, previousResultSlot) || event.isCancelled) { + if (!testAnvilInventoryChange(inventory, previousResultSlot) || event.isCancelled) { CustomAnvil.log("Detected anvil click split enchant bypass.") return true } @@ -94,8 +93,8 @@ class DisenchantmentDependency { return false } - private fun testAnvilChange(view: AnvilView, previous: ItemStack?): Boolean { - val currentResult = view.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT) + private fun testAnvilInventoryChange(inventory: AnvilInventory, previous: ItemStack?): Boolean { + val currentResult = inventory.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT) return currentResult == previous } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantedBookDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantedBookDependency.kt index da3a57e2..54de4e12 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantedBookDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantedBookDependency.kt @@ -2,17 +2,15 @@ package xyz.alexcrea.cuanvil.dependency.plugins import org.bukkit.event.Event import org.bukkit.event.inventory.InventoryClickEvent -import org.bukkit.inventory.view.AnvilView import org.bukkit.plugin.Plugin import xyz.alexcrea.cuanvil.dependency.DependencyManager import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_INPUT_LEFT import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener.Companion.ANVIL_OUTPUT_SLOT -@Suppress("UnstableApiUsage") class EnchantedBookDependency(plugin: Plugin) : GenericPluginDependency(plugin) { override fun testAnvilResult(event: InventoryClickEvent): Boolean { - val view = event.view as? AnvilView ?: return false + val view = event.view val inv = event.inventory //TODO use view here (v2) diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantmentSquaredDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantmentSquaredDependency.kt index 72c8fbab..d769986b 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantmentSquaredDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/EnchantmentSquaredDependency.kt @@ -30,29 +30,28 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) "disable_anvil, " + "incompatible_vanilla_enchantments, " + "incompatible_custom_enchantments and max_level " + - "configuration values." - ) + "configuration values.") } - fun disableAnvilListener() { + fun disableAnvilListener(){ PrepareAnvilEvent.getHandlerList().unregister(this.enchantmentSquaredPlugin) // Find the anvil click event var toRemove: AnvilListener? = null for (registered in InventoryClickEvent.getHandlerList().registeredListeners) { val listener = registered.listener - if (listener is AnvilListener) { + if(listener is AnvilListener) { toRemove = listener break } } - if (toRemove != null) + if(toRemove != null) InventoryClickEvent.getHandlerList().unregister(toRemove) } - fun registerEnchantments() { + fun registerEnchantments(){ CustomAnvil.instance.logger.info("Preparing Enchantment Squared compatibility...") // Register enchantments @@ -70,21 +69,20 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) fun getEnchantmentsSquared(item: ItemStack, enchantments: MutableMap) { val customEnchants = CustomEnchantManager.getInstance().getItemsEnchantsFromPDC(item) - customEnchants.forEach { (enchantment, level) -> - enchantments[getWrappedEnchant(enchantment)] = level + customEnchants.forEach{ + (enchantment, level ) -> enchantments[getWrappedEnchant(enchantment)] = level } } - fun getKeyFromEnchant(enchant: CustomEnchant): NamespacedKey { + fun getKeyFromEnchant(enchant: CustomEnchant): NamespacedKey{ return NamespacedKey.fromString(enchant.type.lowercase(Locale.getDefault()), this.enchantmentSquaredPlugin)!! } - private fun getWrappedEnchant(enchant: CustomEnchant): CAEnchantment { return CAEnchantment.getByKey(getKeyFromEnchant(enchant))!! } - fun registerPluginConfiguration() { + fun registerPluginConfiguration(){ CustomAnvil.instance.logger.info("Preparing Enchantment Squared config...") // Prepare enchantments @@ -101,7 +99,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) CustomAnvil.instance.logger.info("Enchantment Squared should now work as expected !") } - private fun writeMissingGroups() { + private fun writeMissingGroups(){ // Write group that do not exist on custom anvil. val shield = IncludeGroup("shield") shield.addToPolicy(Material.SHIELD.key) @@ -116,7 +114,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) MaterialGroupApi.addMaterialGroup(trinkets) } - private fun writeMaterialRestriction(esEnchantments: List) { + private fun writeMaterialRestriction(esEnchantments: List){ for (enchantment in esEnchantments) { val conflict = ConflictBuilder("restriction_${enchantment.key.key}", CustomAnvil.instance) conflict.addEnchantment(enchantment) @@ -127,7 +125,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) // Get allowed groups for (esGroup in enchantment.enchant.compatibleItems) { val caGroup = esGroupToCAGroup(esGroup) - if (caGroup == null) { + if(caGroup == null){ CustomAnvil.instance.logger.info("Could not find equivalent custom anvil group for $esGroup") continue } @@ -138,7 +136,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) } } - private fun writeEnchantmentConflicts(esEnchantments: List) { + private fun writeEnchantmentConflicts(esEnchantments: List){ val otherEnchants = ArrayList() otherEnchants.addAll(CAEnchantmentRegistry.getInstance().values()) @@ -147,14 +145,14 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) // find conflicting enchantment. for (otherEnchant in otherEnchants) { - if (enchantment.enchant.conflictsWithEnchantment(otherEnchant.name)) { + if(enchantment.enchant.conflictsWithEnchantment(otherEnchant.name)){ writeConflict(enchantment, otherEnchant) } } } } - private fun writeConflict(enchantment1: CAEnchantment, enchantment2: CAEnchantment) { + private fun writeConflict(enchantment1: CAEnchantment, enchantment2: CAEnchantment){ val conflict = ConflictBuilder("${enchantment1.name}_with_${enchantment2.name}_conflict", CustomAnvil.instance) conflict.addEnchantment(enchantment1).addEnchantment(enchantment2) @@ -167,7 +165,7 @@ class EnchantmentSquaredDependency(private val enchantmentSquaredPlugin: Plugin) * Transform an Enchantment Squared group to a Custom Anvil group */ private fun esGroupToCAGroup(esGroup: String): String? { - return when (esGroup) { + return when(esGroup){ "SWORDS" -> "swords" "BOWS" -> "bow" "CROSSBOWS" -> "crossbow" diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ExcellentEnchantsDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ExcellentEnchantsDependency.kt index a41bdea0..8ac479f1 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ExcellentEnchantsDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ExcellentEnchantsDependency.kt @@ -8,8 +8,8 @@ import org.bukkit.event.inventory.PrepareAnvilEvent import org.bukkit.inventory.ItemStack import org.bukkit.plugin.RegisteredListener import xyz.alexcrea.cuanvil.api.EnchantmentApi +import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResult2Event import xyz.alexcrea.cuanvil.dependency.DependencyManager -import xyz.alexcrea.cuanvil.api.event.listener.CATreatAnvilResultEvent import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEPreV5Enchantment import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEV5Enchantment import xyz.alexcrea.cuanvil.enchant.wrapped.CAEEV5_4Enchantment @@ -17,10 +17,10 @@ import xyz.alexcrea.cuanvil.enchant.wrapped.CALegacyEEEnchantment import java.lang.reflect.Method import su.nightexpress.excellentenchants.api.EnchantRegistry as V5EnchantRegistry import su.nightexpress.excellentenchants.enchantment.impl.universal.CurseOfFragilityEnchant as LegacyCurseOfFragilityEnchant +import su.nightexpress.excellentenchants.manager.listener.AnvilListener as V5AnvilListener import su.nightexpress.excellentenchants.enchantment.listener.AnvilListener as PreV5AnvilListener import su.nightexpress.excellentenchants.enchantment.listener.EnchantAnvilListener as LegacyAnvilListener import su.nightexpress.excellentenchants.enchantment.registry.EnchantRegistry as LegacyEnchantRegistry -import su.nightexpress.excellentenchants.manager.listener.AnvilListener as V5AnvilListener import su.nightexpress.excellentenchants.registry.EnchantRegistry as PreV5EnchantRegistry // I don't like that I need to support older version. if I could just drop older support it would be sooo nice @@ -53,7 +53,7 @@ class ExcellentEnchantsDependency { if (listenerVersion == null) { CustomAnvil.instance.logger.severe("Found issue with listener of Excellent Enchants. compatiblity is broken. please contact CustomAnvil devs") - } else { + } else{ CustomAnvil.log("Support version: " + listenerVersion.name) } @@ -171,7 +171,6 @@ class ExcellentEnchantsDependency { ListenerVersion.V5, ListenerVersion.V5_4, -> this.usedAnvilListener = v5AnvilListener!! - ListenerVersion.PRE_V5 -> this.usedAnvilListener = preV5AnvilListener!! ListenerVersion.LEGACY -> this.usedAnvilListener = legacyAnvilListener!! null -> {} @@ -220,7 +219,7 @@ class ExcellentEnchantsDependency { return handleRechargeMethod.invoke(this.usedAnvilListener, event, first, second) as Boolean } - fun treatAnvilResult(event: CATreatAnvilResultEvent) { + fun treatAnvilResult(event: CATreatAnvilResult2Event) { val result = event.result ?: return val first: ItemStack = treatInput(event.leftItem) @@ -239,7 +238,6 @@ class ExcellentEnchantsDependency { ListenerVersion.V5_3, ListenerVersion.V5_4, -> v5AnvilListener!!.onClickAnvil(event) - ListenerVersion.PRE_V5 -> preV5AnvilListener!!.onClickAnvil(event) ListenerVersion.LEGACY -> legacyAnvilListener!!.onClickAnvil(event) null -> {} diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/GenericPluginDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/GenericPluginDependency.kt index 8bfd98ea..62dae9ba 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/GenericPluginDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/GenericPluginDependency.kt @@ -24,7 +24,7 @@ open class GenericPluginDependency(protected open val plugin: Plugin, private va } } - open fun fillPreAnvil(preAnvil: ArrayList) { + open fun fillPreAnvil(preAnvil: ArrayList){ // get PreAnvil and PostAnvil listeners for (registeredListener in PrepareAnvilEvent.getHandlerList().registeredListeners) { @@ -35,13 +35,12 @@ open class GenericPluginDependency(protected open val plugin: Plugin, private va protected open fun fillPostAnvil( postAnvil: ArrayList, - preAnvil: ArrayList - ) { + preAnvil: ArrayList) { } open fun testPrepareAnvil(event: PrepareAnvilEvent): Boolean { - if (!testPrepare) return false + if(!testPrepare) return false val previousResult = event.result event.result = null @@ -62,7 +61,7 @@ open class GenericPluginDependency(protected open val plugin: Plugin, private va } open fun testAnvilResult(event: InventoryClickEvent): Boolean { - if (!testPrepare) return false + if(!testPrepare) return false for (registeredListener in postAnvil) { // We do not want error from another plugin to be our fault diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/HavenBagsDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/HavenBagsDependency.kt index 23a8544d..6f304973 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/HavenBagsDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/HavenBagsDependency.kt @@ -4,7 +4,7 @@ import io.delilaheve.CustomAnvil import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.PrepareAnvilEvent -import org.bukkit.inventory.view.AnvilView +import org.bukkit.inventory.AnvilInventory import org.bukkit.plugin.RegisteredListener import valorless.havenbags.HavenBags import valorless.havenbags.features.BagSkin @@ -13,7 +13,6 @@ import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.listener.PrepareAnvilListener import xyz.alexcrea.cuanvil.util.anvil.AnvilXpUtil -@Suppress("UnstableApiUsage") class HavenBagsDependency { init { @@ -55,14 +54,14 @@ class HavenBagsDependency { bagSkin.onPrepareAnvil(event) if (event.result != null) { CustomAnvil.log("Detected pre anvil heaven bag anvil skin.") - AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost)) + AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) return true } bagUpgrade.onPrepareAnvil(event) if (event.result != null) { CustomAnvil.log("Detected pre anvil heaven bag anvil upgrade.") - AnvilXpUtil.setAnvilInvCost(event.view, player, AnvilCost(event.view.repairCost)) + AnvilXpUtil.setAnvilInvCost(event.inventory, event.view, player, AnvilCost(event.inventory.repairCost)) return true } @@ -70,8 +69,8 @@ class HavenBagsDependency { return false } - fun testAnvilResult(event: InventoryClickEvent, view: AnvilView): Boolean { - val result = view.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone() + fun testAnvilResult(event: InventoryClickEvent, inventory: AnvilInventory): Boolean { + val result = inventory.getItem(PrepareAnvilListener.ANVIL_OUTPUT_SLOT)?.clone() if (HavenBags.IsBag(result)) { CustomAnvil.log("Detected anvil click haven bag bypass.") diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ItemsAdderDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ItemsAdderDependency.kt index 9f366b20..548080fb 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ItemsAdderDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ItemsAdderDependency.kt @@ -6,6 +6,7 @@ import org.bukkit.NamespacedKey import org.bukkit.inventory.ItemStack import org.bukkit.plugin.Plugin +@Suppress("DEPRECATION") class ItemsAdderDependency(plugin: Plugin) : GenericPluginDependency(plugin) { var isLoaded: Boolean = false get() { @@ -17,19 +18,19 @@ class ItemsAdderDependency(plugin: Plugin) : GenericPluginDependency(plugin) { } fun tryClone(item: ItemStack): ItemStack? { - if (!isLoaded) return null + if(!isLoaded) return null val customItem = CustomStack.byItemStack(item) ?: return null return CustomStack.getInstance(customItem.namespacedID)?.itemStack } fun fromKey(key: NamespacedKey): ItemStack? { - if (!isLoaded) return null + if(!isLoaded) return null return CustomStack.getInstance(key.toString())?.itemStack } - fun getKey(item: ItemStack): NamespacedKey? { - if (!isLoaded) return null + fun getKey(item: ItemStack) : NamespacedKey? { + if(!isLoaded) return null val customItem = CustomStack.byItemStack(item) ?: return null return NamespacedKey.fromString(customItem.namespacedID) diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/LegacyEcoEnchantDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/LegacyEcoEnchantDependency.kt index 60f00b85..7f4196cf 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/LegacyEcoEnchantDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/LegacyEcoEnchantDependency.kt @@ -10,13 +10,20 @@ class LegacyEcoEnchantDependency { private var ecoEnchantOldEnchantments: MutableSet? = null + private fun unregisterEnchantment(enchant: Any) { + EnchantmentApi.unregisterEnchantment((enchant as Enchantment).key) + } + + private fun registerEnchantment(ecoEnchant: EcoEnchant, enchant: Any) { + EnchantmentApi.registerEnchantment(CALegacyEcoEnchant(ecoEnchant, enchant as Enchantment)) + } + fun registerEnchantments() { val enchantments = EcoEnchants.values() for (ecoEnchant in enchantments) { - ecoEnchant as Enchantment - - EnchantmentApi.unregisterEnchantment(ecoEnchant) // As eco enchants is loaded before custom anvil and register enchantment to registry, we need to unregister old "vanilla" enchant. - EnchantmentApi.registerEnchantment(CALegacyEcoEnchant(ecoEnchant, ecoEnchant)) + // As eco enchants is loaded before custom anvil and register enchantment to registry, we need to unregister old "vanilla" enchant. + unregisterEnchantment(ecoEnchant) + registerEnchantment(ecoEnchant, ecoEnchant) } ecoEnchantOldEnchantments = HashSet(enchantments) @@ -31,13 +38,13 @@ class LegacyEcoEnchantDependency { // Add new enchantments for (ecoEnchant in newEnchantments) if (!this.ecoEnchantOldEnchantments!!.contains(ecoEnchant)) - EnchantmentApi.registerEnchantment(CALegacyEcoEnchant(ecoEnchant, ecoEnchant as Enchantment)) + registerEnchantment(ecoEnchant, ecoEnchant) // Remove old enchantments that not now currently used this.ecoEnchantOldEnchantments!!.removeAll(newEnchantments) for (oldEnchantment in this.ecoEnchantOldEnchantments!!) { - EnchantmentApi.unregisterEnchantment(oldEnchantment as Enchantment) + unregisterEnchantment(oldEnchantment) } this.ecoEnchantOldEnchantments = HashSet(newEnchantments) diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/SuperEnchantDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/SuperEnchantDependency.kt index 6b9d6fd7..11622f92 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/SuperEnchantDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/SuperEnchantDependency.kt @@ -8,28 +8,22 @@ import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.event.inventory.InventoryClickEvent -import org.bukkit.plugin.Plugin import org.bukkit.plugin.RegisteredListener import xyz.alexcrea.cuanvil.api.EnchantmentApi import xyz.alexcrea.cuanvil.enchant.bulk.SuperEnchantBulkOperation import xyz.alexcrea.cuanvil.enchant.wrapped.CASuperEnchantEnchantment import java.util.logging.Level -class SuperEnchantDependency : GenericPluginDependency { +class SuperEnchantDependency(override val plugin: SuperEnchants): GenericPluginDependency(plugin, false) { - override val plugin: SuperEnchants lateinit var enchManager: EnchantManager val enchantments = ArrayList() - constructor(plugin: Plugin) : super(plugin) { - this.plugin = plugin as SuperEnchants - } - - fun registerEnchantments(): Boolean { + fun registerEnchantments(): Boolean{ CustomAnvil.instance.logger.info("Preparing Super Enchant compatibility...") val field = SuperEnchants::class.java.getDeclaredField("enchantManager") - if (field == null) { + if(field == null) { CustomAnvil.instance.logger.log(Level.SEVERE, "Failed to initialize Super Enchant compatibility") return false } @@ -67,7 +61,7 @@ class SuperEnchantDependency : GenericPluginDependency { reload?.setExecutor(ReloadInterceptor(reload.executor)) } - inner class ReloadInterceptor(val other: CommandExecutor) : CommandExecutor { + inner class ReloadInterceptor(val other: CommandExecutor): CommandExecutor { override fun onCommand( sender: CommandSender, diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ToolStatsDependency.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ToolStatsDependency.kt index f1193d17..8456ec87 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ToolStatsDependency.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/dependency/plugins/ToolStatsDependency.kt @@ -18,9 +18,13 @@ class ToolStatsDependency(plugin: Plugin) : GenericPluginDependency(plugin) { getTokenMethod.trySetAccessible() } - private fun ItemChecker.getTokenSafe(item: ItemStack?): Array { - if (item == null) return arrayOf() - return getTokenMethod.invoke(this, item) as Array + private fun ItemChecker.getTokenSafe(item: ItemStack?): Array<*> { + if (item == null) return arrayOf() + val result = getTokenMethod.invoke(this, item) + if(result !is Array<*>) + throw IllegalStateException("Could not get token from ToolStats") + + return result } override fun testAnvilResult(event: InventoryClickEvent): Boolean { diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictGroup.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictGroup.kt index 2957e324..59841ac6 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictGroup.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictGroup.kt @@ -18,19 +18,18 @@ class EnchantConflictGroup( fun addEnchantment(enchant: CAEnchantment) { enchantments.add(enchant) } - fun addEnchantments(enchants: List) { enchantments.addAll(enchants) } private fun canBypassByBeforeLevel(enchants: Map): Boolean { // Either there no "conflict after" - if (conflictsAfterLevel.isEmpty()) return false + if(conflictsAfterLevel.isEmpty()) return false // Or we check if any conflict after enchantment is true for (entry in conflictsAfterLevel) { val current = enchants.getOrDefault(entry.key, 0) - if (current > entry.value) + if(current > entry.value) return false } @@ -39,12 +38,12 @@ class EnchantConflictGroup( private fun canBypassByAfterLevel(enchants: Map): Boolean { // Either there no "conflict after" - if (conflictsBeforeLevel.isEmpty()) return false + if(conflictsBeforeLevel.isEmpty()) return false // Or we check if any conflict after enchantment is true for (entry in conflictsBeforeLevel) { val current = enchants.getOrDefault(entry.key, 0) - if (current < entry.value) + if(current < entry.value) return false } @@ -65,7 +64,7 @@ class EnchantConflictGroup( return true // If empty we skip. else we - if (canBypassConflictByLevel(enchants)) + if(canBypassConflictByLevel(enchants)) return true // Count the amount of enchantment that are in the list @@ -103,7 +102,7 @@ class EnchantConflictGroup( fun putConflictAfterLevel(enchantment: CAEnchantment, level: Int): Boolean { return null != ( - if (level < 0) conflictsAfterLevel.remove(enchantment) + if(level < 0) conflictsAfterLevel.remove(enchantment) else conflictsAfterLevel.put(enchantment, level)) } @@ -118,7 +117,7 @@ class EnchantConflictGroup( fun putConflictsBeforeLevel(enchantment: CAEnchantment, level: Int): Boolean { return null != ( - if (level < 0) conflictsBeforeLevel.remove(enchantment) + if(level < 0) conflictsBeforeLevel.remove(enchantment) else conflictsBeforeLevel.put(enchantment, level)) } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictManager.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictManager.kt index 1aa956e2..ee9c718b 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictManager.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/group/EnchantConflictManager.kt @@ -10,6 +10,7 @@ import xyz.alexcrea.cuanvil.enchant.CAEnchantment import xyz.alexcrea.cuanvil.enchant.CAEnchantmentRegistry import xyz.alexcrea.cuanvil.util.MaterialUtil.customType import java.util.* +import kotlin.collections.set class EnchantConflictManager { @@ -153,7 +154,7 @@ class EnchantConflictManager { } - return CAEnchantment.getByName(enchantName) + return CAEnchantment.getListByName(enchantName) } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/group/ExcludeGroup.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/group/ExcludeGroup.kt index 4b1a31bb..d752db5b 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/group/ExcludeGroup.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/group/ExcludeGroup.kt @@ -1,6 +1,7 @@ package xyz.alexcrea.cuanvil.group import org.bukkit.NamespacedKey +import java.util.* class ExcludeGroup(name: String) : AbstractMaterialGroup(name) { diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/group/IncludeGroup.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/group/IncludeGroup.kt index f4076350..fc9614b7 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/group/IncludeGroup.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/group/IncludeGroup.kt @@ -1,6 +1,8 @@ package xyz.alexcrea.cuanvil.group +import org.bukkit.Material import org.bukkit.NamespacedKey +import java.util.* class IncludeGroup(name: String) : AbstractMaterialGroup(name) { override fun createDefaultSet(): MutableSet { diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/group/ItemGroupManager.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/group/ItemGroupManager.kt index 7a9c388b..348d0fff 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/group/ItemGroupManager.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/group/ItemGroupManager.kt @@ -41,7 +41,7 @@ class ItemGroupManager { fun createGroup( config: ConfigurationSection, name: String - ): AbstractMaterialGroup { + ): AbstractMaterialGroup{ return createGroup(config, groupMap.keys, name) } @@ -109,10 +109,11 @@ class ItemGroupManager { } // Get other group or create it if not yet created val otherGroup = - if (!groupMap.containsKey(groupName)) { - if (!config.isConfigurationSection(groupName)) continue - createGroup(config, keys, groupName) - } else groupMap[groupName]!! + if (!groupMap.containsKey(groupName)) { + if(!config.isConfigurationSection(groupName)) continue + createGroup(config, keys, groupName) + } + else groupMap[groupName]!! // Avoid self reference or it will create an infinite loop if (otherGroup.isReferencing(group)) { diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/group/NegativeMaterialSet.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/group/NegativeMaterialSet.kt index ef442e57..d87004d4 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/group/NegativeMaterialSet.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/group/NegativeMaterialSet.kt @@ -4,7 +4,7 @@ import org.bukkit.NamespacedKey import xyz.alexcrea.cuanvil.util.MaterialUtil import xyz.alexcrea.cuanvil.util.NegativeSet -class NegativeMaterialSet : NegativeSet() { +class NegativeMaterialSet: NegativeSet() { override fun iterator(): MutableIterator { val materials = MaterialUtil.getMaterials() diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilCloseListener.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilCloseListener.kt index b73effe1..d707b562 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilCloseListener.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilCloseListener.kt @@ -5,18 +5,17 @@ import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.inventory.InventoryCloseEvent -import org.bukkit.inventory.view.AnvilView +import org.bukkit.inventory.AnvilInventory import xyz.alexcrea.cuanvil.dependency.packet.PacketManager import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil -@Suppress("UnstableApiUsage") class AnvilCloseListener(private val packetManager: PacketManager) : Listener { @EventHandler - fun onAnvilClose(event: InventoryCloseEvent) { + fun onAnvilClose(event: InventoryCloseEvent){ val player = event.player - if (event.view !is AnvilView) return - if (player is Player && GameMode.CREATIVE != player.gameMode) { + if(event.inventory !is AnvilInventory) return + if(player is Player && GameMode.CREATIVE != player.gameMode){ packetManager.setInstantBuild(player, false) } diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilResultListener.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilResultListener.kt index 386a920b..11dc1936 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilResultListener.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/AnvilResultListener.kt @@ -14,9 +14,9 @@ import org.bukkit.event.Listener import org.bukkit.event.inventory.ClickType import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.inventory.AnvilInventory +import org.bukkit.inventory.InventoryView import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.BookMeta -import org.bukkit.inventory.view.AnvilView import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.AnvilResult @@ -41,7 +41,6 @@ import java.util.* import java.util.concurrent.atomic.AtomicReference import kotlin.math.min -@Suppress("UnstableApiUsage") class AnvilResultListener : Listener { companion object { @@ -56,49 +55,50 @@ class AnvilResultListener : Listener { @EventHandler(ignoreCancelled = true) fun anvilExtractionCheck(event: InventoryClickEvent) { val player = event.whoClicked as? Player ?: return - val view = event.view as? AnvilView ?: return + val inventory = event.inventory as? AnvilInventory ?: return + val view = event.view if (event.rawSlot != ANVIL_OUTPUT_SLOT) { return } // Test if the event should bypass custom anvil. - if (DependencyManager.tryClickAnvilResultBypass(event, view)) return + if (DependencyManager.tryClickAnvilResultBypass(event, inventory)) return if (!player.hasPermission(CustomAnvil.affectedByPluginPermission)) return - val output = view.getItem(ANVIL_OUTPUT_SLOT) ?: return - val leftItem = view.getItem(ANVIL_INPUT_LEFT) ?: return - val rightItem = view.getItem(ANVIL_INPUT_RIGHT) + val output = inventory.getItem(ANVIL_OUTPUT_SLOT) ?: return + val leftItem = inventory.getItem(ANVIL_INPUT_LEFT) ?: return + val rightItem = inventory.getItem(ANVIL_INPUT_RIGHT) // Deny by default. allow if working event.result = Event.Result.DENY - if (GameMode.CREATIVE != player.gameMode && view.repairCost >= view.maximumRepairCost) { + if (GameMode.CREATIVE != player.gameMode && inventory.repairCost >= inventory.maximumRepairCost) { return } // Test custom recipe - val customRecipeResult = AnvilMergeLogic.testCustomRecipe(view, player, leftItem, rightItem) + val customRecipeResult = AnvilMergeLogic.testCustomRecipe(view, inventory, player, leftItem, rightItem) if (!customRecipeResult.isEmpty()) { onCustomCraft( - event, player, view, + event, player, inventory, leftItem, rightItem, customRecipeResult ) return } // Do not continue if there was no change - if ((output == view.getItem(ANVIL_INPUT_LEFT))) { + if ((output == inventory.getItem(ANVIL_INPUT_LEFT))) { return } // Rename if (rightItem.isAir) { - val result = AnvilMergeLogic.doRenaming(view, player, leftItem) + val result = AnvilMergeLogic.doRenaming(view, inventory, player, leftItem) if (result.isEmpty()) return extractAnvilResult( - event, player, view, + event, player, inventory, null, 0, null, 0, result @@ -109,10 +109,10 @@ class AnvilResultListener : Listener { // Merge val canMerge = leftItem.canMergeWith(rightItem!!) if (canMerge) { - val result = AnvilMergeLogic.doMerge(view, player, leftItem, rightItem) + val result = AnvilMergeLogic.doMerge(view, inventory, player, leftItem, rightItem) val worked = extractAnvilResult( - event, player, view, + event, player, inventory, null, 0, null, 0, result @@ -120,19 +120,19 @@ class AnvilResultListener : Listener { if(!worked) { CustomAnvil.verboseLog("Merge extract failed. reset the displayed price") // Reset the price - AnvilXpUtil.setAnvilResult(view, player, result) + AnvilXpUtil.setAnvilResult(inventory, view, player, result) } return } // Unit repair val unitRepairResult = AnvilMergeLogic.testUnitRepair( - view, player, + view, inventory, player, leftItem, rightItem ) if (!unitRepairResult.isEmpty()) { onUnitRepairExtract( - rightItem, event, player, view, + rightItem, event, player, inventory, unitRepairResult ) return @@ -142,9 +142,9 @@ class AnvilResultListener : Listener { val loreResult = AnvilMergeLogic.testLoreEdit(player, leftItem, rightItem) if (!loreResult.isEmpty()) { if (loreResult.type.isBook) - handleBookLoreEdit(event, view, player, leftItem, rightItem, loreResult) + handleBookLoreEdit(event, inventory, player, leftItem, rightItem, loreResult) else - handlePaperLoreEdit(event, view, player, leftItem, rightItem, loreResult) + handlePaperLoreEdit(event, inventory, player, leftItem, rightItem, loreResult) return } } @@ -152,7 +152,7 @@ class AnvilResultListener : Listener { private fun onCustomCraft( event: InventoryClickEvent, player: Player, - view: AnvilView, + inventory: AnvilInventory, leftItem: ItemStack, rightItem: ItemStack?, result: CustomCraftResult, @@ -189,13 +189,17 @@ class AnvilResultListener : Listener { // Handle not creative middle click... if (event.click != ClickType.MIDDLE && !handleCustomCraftClick( - view, + event, + inventory, player, leftItem, rightItem, result ) ) return + else if(player.gameMode != GameMode.CREATIVE) { + return + } // Finally, we add the item to the player if (slotDestination.type == SlotType.CURSOR) { @@ -206,7 +210,8 @@ class AnvilResultListener : Listener { } private fun handleCustomCraftClick( - view: AnvilView, player: Player, + event: InventoryClickEvent, + inventory: AnvilInventory, player: Player, leftItem: ItemStack, rightItem: ItemStack?, result: CustomCraftResult ): Boolean { @@ -218,11 +223,11 @@ class AnvilResultListener : Listener { if (recipe.rightItem.isAir) return false// in case it changed rightItem!!.amount -= amount * recipe.rightItem!!.amount - view.setItem(ANVIL_INPUT_RIGHT, rightItem) + inventory.setItem(ANVIL_INPUT_RIGHT, rightItem) } leftItem.amount -= amount * recipe.leftItem!!.amount - view.setItem(ANVIL_INPUT_LEFT, leftItem) + inventory.setItem(ANVIL_INPUT_LEFT, leftItem) removeCustomCraftCost(player, result) @@ -231,20 +236,22 @@ class AnvilResultListener : Listener { CustomAnvil.verboseLog("new amount is $newAmount") if (newAmount <= 0 || recipe.exactCount) { - view.setItem(ANVIL_OUTPUT_SLOT, null) + inventory.setItem(ANVIL_OUTPUT_SLOT, null) } else { val resultItem: ItemStack = recipe.resultItem!!.clone() resultItem.amount *= newAmount val newXp = newAmount * newAmount - view.repairCost = newXp - view.setItem(ANVIL_OUTPUT_SLOT, resultItem) + inventory.repairCost = newXp + event.view.setProperty(InventoryView.Property.REPAIR_COST, newXp) + + inventory.setItem(ANVIL_OUTPUT_SLOT, resultItem) player.updateInventory() } - handleAnvilMechanic(player, view) + handleAnvilMechanic(player, inventory) return true } @@ -307,7 +314,7 @@ class AnvilResultListener : Listener { private fun extractAnvilResult( event: InventoryClickEvent, player: Player, - view: AnvilView, + inventory: AnvilInventory, leftItem: ItemStack?, leftRemoveCount: Int, rightItem: ItemStack?, @@ -324,7 +331,7 @@ class AnvilResultListener : Listener { event.isCancelled = true val cost = result.cost - processCost(view, player, cost) + processCost(inventory, player, cost) if (!cost.valid && player.gameMode != GameMode.CREATIVE) { CustomAnvil.verboseLog("Player cannot afford the cost") return false @@ -340,13 +347,15 @@ class AnvilResultListener : Listener { // We remove what should be removed if (leftItem != null) leftItem.amount -= leftRemoveCount - view.setItem(ANVIL_INPUT_LEFT, leftItem) + inventory.setItem(ANVIL_INPUT_LEFT, leftItem) if (rightItem != null) rightItem.amount -= rightRemoveCount - view.setItem(ANVIL_INPUT_RIGHT, rightItem) + inventory.setItem(ANVIL_INPUT_RIGHT, rightItem) - view.setItem(ANVIL_OUTPUT_SLOT, null) + inventory.setItem(ANVIL_OUTPUT_SLOT, null) + } else if(player.gameMode != GameMode.CREATIVE) { + return false } // Finally, we add the item to the player @@ -357,12 +366,12 @@ class AnvilResultListener : Listener { } if (event.click != ClickType.MIDDLE) - handleAnvilMechanic(player, view) + handleAnvilMechanic(player, inventory) return true } - private fun processCost(view: AnvilView, player: Player, cost: AnvilCost) { + private fun processCost(inventory: AnvilInventory, player: Player, cost: AnvilCost) { var sum = cost.repair if ( @@ -380,28 +389,27 @@ class AnvilResultListener : Listener { if (!EconomyManager.economy!!.has(player, cost.asMonetaryCost())) cost.valid = false } else { - if ((view.maximumRepairCost <= sum) + if ((inventory.maximumRepairCost <= sum) || (player.level < sum) ) cost.valid = false } } // Process both sound & degradation - private fun handleAnvilMechanic(player: HumanEntity, view: AnvilView) { - return handleAnvilMechanic(player, view, player.gameMode != GameMode.CREATIVE) + private fun handleAnvilMechanic(player: HumanEntity, inventory: AnvilInventory) { + return handleAnvilMechanic(player, inventory, player.gameMode != GameMode.CREATIVE) } // Process both sound & degradation - private fun handleAnvilMechanic(player: HumanEntity, view: AnvilView, canDegrade: Boolean) { + private fun handleAnvilMechanic(player: HumanEntity, inventory: AnvilInventory, canDegrade: Boolean) { // ok so we do not provide a getLocation on view ? - val inv = view.topInventory as? AnvilInventory - val location = inv?.location + val location = inventory.location - val wasDestroyed = canDegrade && tryDegradeAnvil(view, location) - tryPlaySound(location, player, wasDestroyed) + val wasDestroyed = canDegrade && tryDegradeAnvil(player, location) + tryPlaySound(location, wasDestroyed) } - private fun tryDegradeAnvil(view: AnvilView, location: Location?): Boolean { + private fun tryDegradeAnvil(player: HumanEntity, location: Location?): Boolean { val world = location?.world ?: return false if (Math.random() > AnvilFinishOptions.degradation_chance) return false @@ -417,7 +425,7 @@ class AnvilResultListener : Listener { block.type = next if (next == Material.AIR) { - view.close() + player.closeInventory() return true } @@ -426,7 +434,6 @@ class AnvilResultListener : Listener { private fun tryPlaySound( location: Location?, - player: HumanEntity, wasDestroyed: Boolean, ) { val world = location?.world @@ -434,35 +441,25 @@ class AnvilResultListener : Listener { if (!AnvilFinishOptions.sound_enabled) return val sound = AnvilFinishOptions.getAnvilSound(wasDestroyed) - if(world == null) { - player.world.playSound( - player, - sound.sound, - sound.category, - sound.volume, - sound.pitch, - ) - } else { - world.playSound( - location, - sound.sound, - sound.category, - sound.volume, - sound.pitch, - ) - } + world?.playSound( + location, + sound.sound, + sound.category, + sound.volume, + sound.pitch, + ) } private fun onUnitRepairExtract( rightItem: ItemStack, event: InventoryClickEvent, player: Player, - view: AnvilView, + inventory: AnvilInventory, result: UnitRepairResult, ) { // We give the item manually extractAnvilResult( - event, player, view, + event, player, inventory, null, 0, rightItem, result.repairAmount, result @@ -471,21 +468,21 @@ class AnvilResultListener : Listener { private fun handleBookLoreEdit( event: InventoryClickEvent, - view: AnvilView, + inventory: AnvilInventory, player: Player, leftItem: ItemStack, rightItem: ItemStack, result: LoreEditResult ) { if (result.type.isAppend) - handleBookLoreAppend(event, view, player, rightItem, result) + handleBookLoreAppend(event, inventory, player, rightItem, result) else - handleBookLoreRemove(event, view, player, leftItem, rightItem, result) + handleBookLoreRemove(event, inventory, player, leftItem, rightItem, result) } private fun handleBookLoreAppend( event: InventoryClickEvent, - view: AnvilView, + inventory: AnvilInventory, player: Player, rightItem: ItemStack, result: LoreEditResult @@ -503,7 +500,7 @@ class AnvilResultListener : Listener { } extractAnvilResult( - event, player, view, + event, player, inventory, null, 0, clearedBook, 0, result @@ -512,7 +509,7 @@ class AnvilResultListener : Listener { private fun handleBookLoreRemove( event: InventoryClickEvent, - view: AnvilView, + inventory: AnvilInventory, player: Player, leftItem: ItemStack, rightItem: ItemStack, @@ -548,7 +545,7 @@ class AnvilResultListener : Listener { } extractAnvilResult( - event, player, view, + event, player, inventory, null, 0, rightCopy, 0, result @@ -557,21 +554,21 @@ class AnvilResultListener : Listener { private fun handlePaperLoreEdit( event: InventoryClickEvent, - view: AnvilView, + inventory: AnvilInventory, player: Player, leftItem: ItemStack, rightItem: ItemStack, result: LoreEditResult ) { if (result.type.isAppend) - handlePaperLoreAppend(event, view, player, rightItem, result) + handlePaperLoreAppend(event, inventory, player, rightItem, result) else - handlePaperLoreRemove(event, view, player, leftItem, rightItem, result) + handlePaperLoreRemove(event, inventory, player, leftItem, rightItem, result) } private fun handlePaperLoreAppend( event: InventoryClickEvent, - view: AnvilView, + inventory: AnvilInventory, player: Player, rightItem: ItemStack, result: LoreEditResult @@ -596,14 +593,14 @@ class AnvilResultListener : Listener { if (rightItem.amount > 1) { extractAnvilResult( - event, player, view, + event, player, inventory, paperCopy, 0, rightItem, 1, result ) } else { extractAnvilResult( - event, player, view, + event, player, inventory, null, 0, paperCopy, 0, result @@ -613,7 +610,7 @@ class AnvilResultListener : Listener { private fun handlePaperLoreRemove( event: InventoryClickEvent, - view: AnvilView, + inventory: AnvilInventory, player: Player, leftItem: ItemStack, rightItem: ItemStack, @@ -648,14 +645,14 @@ class AnvilResultListener : Listener { if (rightItem.amount > 1) { extractAnvilResult( - event, player, view, + event, player, inventory, rightClone, 0, rightItem, 1, result ) } else { extractAnvilResult( - event, player, view, + event, player, inventory, null, 0, rightClone, 0, result diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/ChatEventListener.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/ChatEventListener.kt index f2a68cb0..f166fa39 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/ChatEventListener.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/ChatEventListener.kt @@ -41,10 +41,9 @@ class ChatEventListener : Listener { // sync callback with default server thread DependencyManager.scheduler.scheduleOnEntity( CustomAnvil.instance, player, - { - eventCallback.accept(event.message) - }, 0L - ) + Runnable { + eventCallback.accept(event.message) + }, 0L) } } \ No newline at end of file diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/PrepareAnvilListener.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/PrepareAnvilListener.kt index eda35fc6..c0fe939b 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/listener/PrepareAnvilListener.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/listener/PrepareAnvilListener.kt @@ -1,5 +1,6 @@ package xyz.alexcrea.cuanvil.listener +import com.github.stefvanschie.inventoryframework.util.InventoryViewUtil import io.delilaheve.CustomAnvil import io.delilaheve.util.ConfigOptions import io.delilaheve.util.ItemUtil.canMergeWith @@ -9,11 +10,12 @@ import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.inventory.PrepareAnvilEvent +import org.bukkit.inventory.AnvilInventory +import org.bukkit.inventory.InventoryView import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.EnchantmentStorageMeta import org.bukkit.inventory.meta.ItemMeta import xyz.alexcrea.cuanvil.anvil.AnvilCost -import org.bukkit.inventory.view.AnvilView import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.AnvilResult import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.doMerge import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.doRenaming @@ -28,7 +30,6 @@ import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil /** * Listener for anvil events */ -@Suppress("UnstableApiUsage") class PrepareAnvilListener : Listener { companion object { @@ -47,23 +48,24 @@ class PrepareAnvilListener : Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) fun anvilCombineCheck(event: PrepareAnvilEvent) { val view = event.view - val player = view.player + val inventory = event.inventory - if (player !is Player) return + val player = InventoryViewUtil.getInstance().getPlayer(view) + if(player !is Player) return tryRenameDialog(player, event) // Test if custom anvil is bypassed before immutability test if (DependencyManager.earlyTryEventPreAnvilBypass(event, player)) { // even if we got bypassed we still want to set price - AnvilXpUtil.setAnvilInvCost(view, player, AnvilCost(view.repairCost)) + AnvilXpUtil.setAnvilInvCost(inventory, view, player, AnvilCost(event.inventory.repairCost)) return } - val first = view.getItem(ANVIL_INPUT_LEFT) - val second = view.getItem(ANVIL_INPUT_RIGHT) + val first = inventory.getItem(ANVIL_INPUT_LEFT) + val second = inventory.getItem(ANVIL_INPUT_RIGHT) - if (IS_EMPTY_TEST) { + if(IS_EMPTY_TEST) { IS_EMPTY_TEST = false applyResult(event, player, AnvilResult.EMPTY) return @@ -84,26 +86,27 @@ class PrepareAnvilListener : Listener { // Test if the event should bypass custom anvil. if (DependencyManager.tryEventPreAnvilBypass(event, player)) { // even if we got bypassed we still want to set price - AnvilXpUtil.setAnvilInvCost(view, player, AnvilCost(view.repairCost)) + AnvilXpUtil.setAnvilInvCost(inventory, view, player, AnvilCost(event.inventory.repairCost)) return } if (!player.hasPermission(CustomAnvil.affectedByPluginPermission)) return - val result = getResult(view, player, first, second) + val result = getResult(view, inventory, player, first, second) applyResult(event, player, result) } fun getResult( - view: AnvilView, + view: InventoryView, //TODO use anvil view + inventory: AnvilInventory, player: Player, - first: ItemStack?, second: ItemStack? - ): AnvilResult { - if (first == null) + first: ItemStack?, second: ItemStack?) : AnvilResult + { + if(first == null) return AnvilResult.EMPTY // Test custom recipe - var result: AnvilResult = testCustomRecipe(view, player, first, second) + var result: AnvilResult = testCustomRecipe(view, inventory, player, first, second) if (!result.isEmpty()) return result @@ -111,14 +114,14 @@ class PrepareAnvilListener : Listener { val shouldTryRename = second.isAir CustomAnvil.verboseLog("checking air in main logic: $shouldTryRename") if (shouldTryRename) - return doRenaming(view, player, first) + return doRenaming(view, inventory, player, first) // Test for merge if (first.canMergeWith(second!!)) - return doMerge(view, player, first, second) + return doMerge(view, inventory, player, first, second) // Test for unit repair - result = testUnitRepair(view, player, first, second) + result = testUnitRepair(view, inventory, player, first, second) if (!result.isEmpty()) return result @@ -134,7 +137,7 @@ class PrepareAnvilListener : Listener { player: HumanEntity, event: PrepareAnvilEvent ) { - if (!ConfigOptions.canUseDialogRename(player)) return + if(!ConfigOptions.canUseDialogRename(player)) return AnvilRenameDialogUtil.anvilRenameDialog.tryShowDialog(player, event) } @@ -168,7 +171,7 @@ class PrepareAnvilListener : Listener { private fun applyResult(event: PrepareAnvilEvent, player: Player, result: AnvilResult) { event.result = result.item - AnvilXpUtil.setAnvilResult(event.view, player, result) + AnvilXpUtil.setAnvilResult(event.inventory, event.view, player, result) } } \ No newline at end of file diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/util/MetricsUtil.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/util/MetricsUtil.kt index 1763db56..9459ad9e 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/util/MetricsUtil.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/util/MetricsUtil.kt @@ -18,7 +18,7 @@ object MetricsUtil { private var FAST_STATS_METRICS: BukkitContext? = null fun loadMetrics(plugin: CustomAnvil) { - if(DependencyManager.externGuiTester.isInTest()) return + if(DependencyManager.inTesting) return val config = ConfigHolder.DEFAULT_CONFIG.config val metricString = config.getString(ConfigOptions.METRIC_TYPE, MetricType.AUTO.value)!! diff --git a/src/main/kotlin/xyz/alexcrea/cuanvil/util/anvil/AnvilXpUtil.kt b/src/main/kotlin/xyz/alexcrea/cuanvil/util/anvil/AnvilXpUtil.kt index 433680b0..379694f2 100644 --- a/src/main/kotlin/xyz/alexcrea/cuanvil/util/anvil/AnvilXpUtil.kt +++ b/src/main/kotlin/xyz/alexcrea/cuanvil/util/anvil/AnvilXpUtil.kt @@ -8,9 +8,10 @@ import org.bukkit.GameMode import org.bukkit.NamespacedKey import org.bukkit.entity.HumanEntity import org.bukkit.entity.Player +import org.bukkit.inventory.AnvilInventory +import org.bukkit.inventory.InventoryView import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.Repairable -import org.bukkit.inventory.view.AnvilView import org.bukkit.persistence.PersistentDataType import xyz.alexcrea.cuanvil.anvil.AnvilCost import xyz.alexcrea.cuanvil.anvil.AnvilMergeLogic.AnvilResult @@ -24,7 +25,6 @@ import xyz.alexcrea.cuanvil.util.AnvilTitleUtil import xyz.alexcrea.cuanvil.util.dialog.AnvilRenameDialogUtil import kotlin.math.sqrt -@Suppress("UnstableApiUsage") object AnvilXpUtil { const val EXCLUSIVE_PENALTY_PREFIX = "repair_cost" @@ -33,7 +33,8 @@ object AnvilXpUtil { * Display the required cost (either as xp or as money) or reset anvil price depending on result */ fun setAnvilResult( - view: AnvilView, + inventory: AnvilInventory, + view: InventoryView, player: Player, result: AnvilResult ) { @@ -42,23 +43,24 @@ object AnvilXpUtil { return } - setAnvilInvCost(view, player, result.cost, result.ignoreXpRules) + setAnvilInvCost(inventory, view, player, result.cost, result.ignoreXpRules) } /** * Display the required cost (either as xp or as money) */ fun setAnvilInvCost( - view: AnvilView, + inventory: AnvilInventory, + view: InventoryView, player: Player, cost: AnvilCost, ignoreRules: Boolean = false ) { if (ConfigOptions.shouldUseMoney(player)) { cost.isMonetary = true - setAnvilPrice(view, player, cost) + setAnvilPrice(inventory, view, player, cost) } else - setAnvilInvXp(view, player, cost.filteredXpCost(ignoreRules), ignoreRules) + setAnvilInvXp(inventory, view, player, cost.filteredXpCost(ignoreRules), ignoreRules) } fun maximumXpCost(ignoreRules: Boolean = false): Int { @@ -73,7 +75,8 @@ object AnvilXpUtil { * Display xp needed for the work on the anvil inventory */ private fun setAnvilInvXp( - view: AnvilView, + inventory: AnvilInventory, + view: InventoryView, player: HumanEntity, anvilCost: Int, ignoreRules: Boolean = false @@ -81,8 +84,9 @@ object AnvilXpUtil { val maximumRepairCost = maximumXpCost(ignoreRules) // Try first just in case another plugin, or the test need this - view.maximumRepairCost = maximumRepairCost - view.repairCost = anvilCost + inventory.maximumRepairCost = maximumRepairCost + inventory.repairCost = anvilCost + // TODO for 2.x.x use anvil view & set directly there /* Because Minecraft likes to have the final say in the repair cost displayed * we need to wait for the event to end before overriding it, this ensures that @@ -91,15 +95,16 @@ object AnvilXpUtil { CustomAnvil.instance, player ) { // retry after a tick - view.maximumRepairCost = maximumRepairCost - view.repairCost = anvilCost + inventory.maximumRepairCost = maximumRepairCost + inventory.repairCost = anvilCost + // TODO for 2.x.x use anvil view & set directly there if (player !is Player) return@scheduleOnEntity if (player.gameMode != GameMode.CREATIVE) { val bypassToExpensive = (ConfigOptions.doReplaceTooExpensive) && (anvilCost >= 40) && - anvilCost < view.maximumRepairCost + anvilCost < inventory.maximumRepairCost DependencyManager.packetManager.setInstantBuild(player, bypassToExpensive) } @@ -112,7 +117,8 @@ object AnvilXpUtil { * Display monetary cost needed for the work on the anvil inventory */ private fun setAnvilPrice( - view: AnvilView, + inventory: AnvilInventory, + view: InventoryView, player: Player, cost: AnvilCost, ) { @@ -130,20 +136,22 @@ object AnvilXpUtil { CustomAnvil.instance ) - clearAnvilXpCost(view, player) + clearAnvilXpCost(inventory, view, player) } private fun clearAnvilXpCost( - view: AnvilView, + inventory: AnvilInventory, + view: InventoryView, player: HumanEntity, ) { - view.repairCost = 0 + // TODO for 2.x.x use anvil view & set directly there + inventory.repairCost = 0 // retry after a tick DependencyManager.scheduler.scheduleOnEntity( CustomAnvil.instance, player ) { - view.repairCost = 0 + inventory.repairCost = 0 if (player !is Player) return@scheduleOnEntity player.updateInventory() @@ -196,7 +204,7 @@ object AnvilXpUtil { return resultSum } - fun onNoResult(player: HumanEntity, view: AnvilView) { + fun onNoResult(player: HumanEntity, view: InventoryView) { if (ConfigOptions.shouldUseMoney(player)) AnvilTitleUtil.rename( view, "Repair & Name", @@ -269,7 +277,7 @@ object AnvilXpUtil { // We know "enchantment.key in resultEnchs" true val resultLevel = resultEnchs[enchantment.key]!! - val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, isFromBook, isToBook) + val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, isToBook, isFromBook) val value = resultLevel * enchantmentMultiplier CustomAnvil.log("Value for sacrifice item ${enchantment.key.enchantmentName} level ${enchantment.value} is $value ($resultLevel * $enchantmentMultiplier)") rightValue += value @@ -283,7 +291,7 @@ object AnvilXpUtil { val resultLevel = resultEnchs.getOrDefault(enchantment.key, 0) - val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, isFromBook, isToBook) + val enchantmentMultiplier = ConfigOptions.enchantmentValue(enchantment.key, isToBook, isFromBook) val value = resultLevel * enchantmentMultiplier CustomAnvil.log("Value for left item ${enchantment.key.enchantmentName} level ${enchantment.value} is $value ($resultLevel * $enchantmentMultiplier)") leftValue += value diff --git a/src/main/resources/item_groups.yml b/src/main/resources/item_groups.yml index cccfc1f8..dff1b41c 100644 --- a/src/main/resources/item_groups.yml +++ b/src/main/resources/item_groups.yml @@ -121,6 +121,7 @@ wearable: - player_head - creeper_head - dragon_head + # do not exist in 1.18 but exist in future update - piglin_head groups: - armors diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 927d72b0..a8d98c8c 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -4,7 +4,7 @@ prefix: "Custom Anvil" version: ${version} folia-supported: true description: Allow to customise anvil mechanics -api-version: 1.21 +api-version: 1.16 load: POSTWORLD authors: [ DelilahEve, alexcrea ] libraries: [${libraries}] @@ -14,6 +14,18 @@ commands: description: Generic command for custom anvil aliases: - ca + anvilconfigreload: + description: Reload every config of this plugin + permission: ca.command.reload + aliases: + #- acreload # anvil config reload + #- careload # custom anvil reload + - carl # custom anvil reload + customanvilconfig: + description: open a menu for administrator to edit plugin's config in game + permission: ca.config.edit + aliases: + - configanvil permissions: ca.affected: diff --git a/src/test/java/xyz/alexcrea/cuanvil/util/AnvilFuseTestUtil.java b/src/test/java/xyz/alexcrea/cuanvil/util/AnvilFuseTestUtil.java index 75af4db3..fefec130 100644 --- a/src/test/java/xyz/alexcrea/cuanvil/util/AnvilFuseTestUtil.java +++ b/src/test/java/xyz/alexcrea/cuanvil/util/AnvilFuseTestUtil.java @@ -71,7 +71,7 @@ public class AnvilFuseTestUtil { List enchantments = new ArrayList<>(); for (String enchantmentName : enchantmentNames) { - List enchantmentList = CAEnchantment.getByName(enchantmentName); + List enchantmentList = CAEnchantment.getListByName(enchantmentName); Assertions.assertNotEquals(0, enchantmentList.size(), "Could not find enchantment \"" + enchantmentName + "\"");