From c618edfc902406c32db0d569811d53c3bae07551 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:21:27 +0100 Subject: [PATCH 1/3] refactor: Extract item building helpers from items registries Co-Authored-By: Claude Fable 5.2 --- .../kotlin/impl/mmoitems/MmoItemsRegistry.kt | 14 +++-------- .../kotlin/impl/mmoitems/MmoItemsWrapper.kt | 25 ++++++++++++++++--- .../kotlin/impl/vanilla/ItemMetaPayload.kt | 19 ++++++++++++++ .../impl/vanilla/MinecraftItemsRegistry.kt | 19 -------------- 4 files changed, 43 insertions(+), 34 deletions(-) diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt index 9071ef9b..7253701c 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt @@ -18,29 +18,21 @@ public class MmoItemsRegistry private constructor(private val mmoItems: MmoItems get() = templates.map { it.id.lowercase() } private val templates: Collection - get() = mmoItems.templatesManager.collectTemplates() + get() = mmoItems.templates override fun isItemExists(itemId: String): Boolean = itemId in knownIds override fun getItemId(item: ItemStack): String? { - val nbtItem = mmoItems.getNbtItem(item) - return nbtItem.getString("MMOITEMS_ITEM_ID")?.lowercase() + return mmoItems.getId(item)?.lowercase() } override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? { val template = templates.find { it.id.equals(itemId, ignoreCase = true) } ?: return null - return template.buildItemStack() + return mmoItems.buildItem(template, player = null) ?.also { it.amount = amount.coerceIn(1, it.maxStackSize) } } - private fun MMOItemTemplate.buildItemStack(): ItemStack? { - return newBuilder(0, null) - .build() - .newBuilder() - .build() - } - public companion object { public const val ID: String = "mmoitems" } diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt index ed364431..f96bced9 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsWrapper.kt @@ -3,15 +3,32 @@ package ru.endlesscode.mimic.impl.mmoitems -import io.lumine.mythic.lib.api.item.NBTItem import net.Indyuce.mmoitems.MMOItems -import net.Indyuce.mmoitems.manager.TemplateManager +import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate +import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack internal class MmoItemsWrapper { val isEnabled: Boolean get() = MMOItems.plugin.isEnabled - val templatesManager: TemplateManager get() = MMOItems.plugin.templates + val templates: Collection get() = MMOItems.plugin.templates.collectTemplates() - fun getNbtItem(item: ItemStack): NBTItem = NBTItem.get(item) + /** Returns name of the item type like `SWORD`. */ + fun getTypeName(template: MMOItemTemplate): String = template.type.id + + /** Returns name of the item type like `SWORD`, or `null` if the [item] isn't an MMOItems item. */ + fun getTypeName(item: ItemStack): String? = MMOItems.getTypeName(item) + + /** Returns ID of the [item] within its type, or `null` if the [item] isn't an MMOItems item. */ + fun getId(item: ItemStack): String? = MMOItems.getID(item)?.takeIf { it.isNotEmpty() } + + /** + * Builds an item from the [template]. + * If the [player] is given, the item is built for them as MMOItems does, for example, scaled to their level. + * Otherwise, the item has no tier and no level. + */ + fun buildItem(template: MMOItemTemplate, player: Player?): ItemStack? { + val builder = if (player != null) template.newBuilder(player) else template.newBuilder(0, null) + return builder.build().newBuilder().build() + } } diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt index 69861b28..b30e3472 100644 --- a/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/ItemMetaPayload.kt @@ -13,6 +13,8 @@ import kotlinx.serialization.hocon.decodeFromConfig import net.kyori.adventure.text.Component import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag +import org.bukkit.inventory.meta.Damageable +import org.bukkit.inventory.meta.ItemMeta import ru.endlesscode.mimic.internal.* /** @@ -85,3 +87,20 @@ public data class ItemMetaPayload( } } } + +internal fun ItemMeta.applyPayload(payload: ItemMetaPayload): ItemMeta { + // Apply text options + displayName(payload.name) + lore(payload.lore) + + // Apply damage and custom model data + isUnbreakable = payload.isUnbreakable + (this as? Damageable)?.damage = payload.damage + if (payload.customModelData != null) setCustomModelData(payload.customModelData) + + // Apply enchants and item flags + payload.enchantments.forEach { (enchant, level) -> addEnchant(enchant, level, true) } + addItemFlags(*payload.flags.toTypedArray()) + + return this +} diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt index 7ec3ee65..53155cba 100644 --- a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt @@ -6,8 +6,6 @@ package ru.endlesscode.mimic.impl.vanilla import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.inventory.ItemStack -import org.bukkit.inventory.meta.Damageable -import org.bukkit.inventory.meta.ItemMeta import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.items.BukkitItemsRegistry @@ -67,23 +65,6 @@ public class MinecraftItemsRegistry : BukkitItemsRegistry { ?.takeIf { it.isItem } } - private fun ItemMeta.applyPayload(payload: ItemMetaPayload): ItemMeta { - // Apply text options - displayName(payload.name) - lore(payload.lore) - - // Apply damage and custom model data - isUnbreakable = payload.isUnbreakable - (this as? Damageable)?.damage = payload.damage - if (payload.customModelData != null) setCustomModelData(payload.customModelData) - - // Apply enchants and item flags - payload.enchantments.forEach { (enchant, level) -> addEnchant(enchant, level, true) } - addItemFlags(*payload.flags.toTypedArray()) - - return this - } - public companion object { public const val ID: String = "minecraft" } From 87e826233ca6863b0b601724171ce4d800cc5b6b Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:21:35 +0100 Subject: [PATCH 2/3] feat: Add Items API, deprecate ItemsRegistry ItemProvider for implementers and Items for consumers, aggregated by Mimic. An item belongs to the provider with the highest priority recognizing it. Every registered ItemsRegistry is bridged to an item provider, Mimic.itemsRegistry is a view over the new aggregator. Closes #95, closes #85, closes #86, closes #87 Co-Authored-By: Claude Fable 5.2 --- mimic-api/src/main/kotlin/MimicApiLevel.kt | 1 + .../src/main/kotlin/items/ItemsRegistry.kt | 1 + mimic-bukkit-api/api/mimic-bukkit-api.api | 19 + mimic-bukkit-api/src/main/kotlin/Mimic.kt | 62 +++- .../main/kotlin/items/BukkitItemsRegistry.kt | 3 + .../src/main/kotlin/items/ItemProvider.kt | 83 +++++ .../src/main/kotlin/items/Items.kt | 95 +++++ mimic-bukkit/build.gradle.kts | 1 + mimic-bukkit/src/main/kotlin/MimicImpl.kt | 46 ++- mimic-bukkit/src/main/kotlin/MimicMetrics.kt | 2 +- mimic-bukkit/src/main/kotlin/MimicPlugin.kt | 18 +- .../src/main/kotlin/command/ConfigCommand.kt | 25 +- .../src/main/kotlin/command/ConfigMessage.kt | 11 +- .../main/kotlin/command/ItemsSubcommand.kt | 98 +++--- .../src/main/kotlin/command/MainCommand.kt | 4 +- .../src/main/kotlin/command/brigadier.kt | 34 +- .../src/main/kotlin/config/MimicConfig.kt | 31 +- .../craftengine/CraftEngineItemProvider.kt | 44 +++ .../craftengine/CraftEngineItemsRegistry.kt | 3 + .../impl/craftengine/CraftEngineWrapper.kt | 13 +- .../customitems/CustomItemsItemProvider.kt | 35 ++ .../impl/customitems/CustomItemsRegistry.kt | 3 + .../impl/mimic/ItemsRegistryProvider.kt | 12 - .../src/main/kotlin/impl/mimic/MimicItems.kt | 77 +++++ .../kotlin/impl/mimic/MimicItemsRegistry.kt | 126 ++++--- .../impl/mimic/SafeBukkitItemsRegistry.kt | 22 -- .../impl/mmoitems/MmoItemsItemProvider.kt | 46 +++ .../kotlin/impl/mmoitems/MmoItemsRegistry.kt | 3 + .../impl/vanilla/MinecraftItemProvider.kt | 58 ++++ .../impl/vanilla/MinecraftItemsRegistry.kt | 3 + .../kotlin/items/ItemsRegistryItemProvider.kt | 45 +++ .../main/kotlin/items/WrappedItemProvider.kt | 23 ++ .../main/kotlin/items/WrappedItemsRegistry.kt | 4 + mimic-bukkit/src/test/kotlin/MimicImplTest.kt | 65 +++- .../src/test/kotlin/command/IdHintsTest.kt | 2 - .../src/test/kotlin/config/MimicConfigTest.kt | 15 + .../impl/mimic/MimicItemsRegistryTest.kt | 233 +++++++++++-- .../test/kotlin/impl/mimic/MimicItemsTest.kt | 326 ++++++++++++++++++ .../impl/mmoitems/MmoItemsItemProviderTest.kt | 78 +++++ .../impl/vanilla/MinecraftItemProviderTest.kt | 122 +++++++ .../vanilla/MinecraftItemsRegistryTest.kt | 2 + 41 files changed, 1641 insertions(+), 253 deletions(-) create mode 100644 mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt create mode 100644 mimic-bukkit-api/src/main/kotlin/items/Items.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt delete mode 100644 mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt delete mode 100644 mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt create mode 100644 mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt create mode 100644 mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt create mode 100644 mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt create mode 100644 mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt diff --git a/mimic-api/src/main/kotlin/MimicApiLevel.kt b/mimic-api/src/main/kotlin/MimicApiLevel.kt index fd7d81f0..bbf92d63 100644 --- a/mimic-api/src/main/kotlin/MimicApiLevel.kt +++ b/mimic-api/src/main/kotlin/MimicApiLevel.kt @@ -53,6 +53,7 @@ public object MimicApiLevel { /** * # Version 0.11 * - Blocks API, experimental BlockRegistry API is removed + * - Items API, ItemsRegistry API is deprecated */ public const val VERSION_0_11: Int = 7 diff --git a/mimic-api/src/main/kotlin/items/ItemsRegistry.kt b/mimic-api/src/main/kotlin/items/ItemsRegistry.kt index a9e80bf1..c6b9c953 100644 --- a/mimic-api/src/main/kotlin/items/ItemsRegistry.kt +++ b/mimic-api/src/main/kotlin/items/ItemsRegistry.kt @@ -19,6 +19,7 @@ import ru.endlesscode.mimic.MimicService * Mapping them to the plugin's own IDs is up to the implementation: `itemsadder:ruby_sword` -> `itemsadder/ruby_sword`. * Invalid IDs are ignored. */ +@Deprecated("Use Items API from mimic-bukkit-api instead, it identifies items by their owner and creates them for a player.") public interface ItemsRegistry : MimicService { /** Returns all known item IDs. */ diff --git a/mimic-bukkit-api/api/mimic-bukkit-api.api b/mimic-bukkit-api/api/mimic-bukkit-api.api index f6de0b67..6f4916dd 100644 --- a/mimic-bukkit-api/api/mimic-bukkit-api.api +++ b/mimic-bukkit-api/api/mimic-bukkit-api.api @@ -9,6 +9,7 @@ public abstract interface class ru/endlesscode/mimic/Mimic { public abstract fun getClassSystemProvider ()Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider; public abstract fun getClasses ()Lru/endlesscode/mimic/classes/Classes; public static fun getInstance ()Lru/endlesscode/mimic/Mimic; + public abstract fun getItems ()Lru/endlesscode/mimic/items/Items; public abstract fun getItemsRegistry ()Lru/endlesscode/mimic/items/BukkitItemsRegistry; public fun getLevelSystem (Lorg/bukkit/entity/Player;)Lru/endlesscode/mimic/level/BukkitLevelSystem; public abstract fun getLevelSystemProvider ()Lru/endlesscode/mimic/level/BukkitLevelSystem$Provider; @@ -22,6 +23,8 @@ public abstract interface class ru/endlesscode/mimic/Mimic { public abstract fun registerClassProvider (Lru/endlesscode/mimic/classes/ClassProvider;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/classes/ClassProvider; public fun registerClassSystem (Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider; public abstract fun registerClassSystem (Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/classes/BukkitClassSystem$Provider; + public fun registerItemProvider (Lru/endlesscode/mimic/items/ItemProvider;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/items/ItemProvider; + public abstract fun registerItemProvider (Lru/endlesscode/mimic/items/ItemProvider;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/items/ItemProvider; public fun registerItemsRegistry (Lru/endlesscode/mimic/items/BukkitItemsRegistry;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/items/BukkitItemsRegistry; public abstract fun registerItemsRegistry (Lru/endlesscode/mimic/items/BukkitItemsRegistry;ILorg/bukkit/plugin/Plugin;Lorg/bukkit/plugin/ServicePriority;)Lru/endlesscode/mimic/items/BukkitItemsRegistry; public fun registerLevelProvider (Lru/endlesscode/mimic/level/LevelProvider;ILorg/bukkit/plugin/Plugin;)Lru/endlesscode/mimic/level/LevelProvider; @@ -151,6 +154,22 @@ public abstract interface class ru/endlesscode/mimic/inventory/BukkitPlayerInven public abstract interface class ru/endlesscode/mimic/items/BukkitItemsRegistry : ru/endlesscode/mimic/items/ItemsRegistry { } +public abstract interface class ru/endlesscode/mimic/items/ItemProvider : ru/endlesscode/mimic/MimicService { + public abstract fun createItem (Ljava/lang/String;ILorg/bukkit/entity/Player;Ljava/lang/String;)Lorg/bukkit/inventory/ItemStack; + public abstract fun getAllItems ()Ljava/util/Collection; + public abstract fun getItemId (Lorg/bukkit/inventory/ItemStack;)Ljava/lang/String; +} + +public abstract interface class ru/endlesscode/mimic/items/Items { + public fun createItem (Lnet/kyori/adventure/key/Key;)Lorg/bukkit/inventory/ItemStack; + public fun createItem (Lnet/kyori/adventure/key/Key;I)Lorg/bukkit/inventory/ItemStack; + public abstract fun createItem (Lnet/kyori/adventure/key/Key;ILorg/bukkit/entity/Player;Ljava/lang/String;)Lorg/bukkit/inventory/ItemStack; + public abstract fun getAllItems ()Ljava/util/List; + public abstract fun getItemId (Lorg/bukkit/inventory/ItemStack;)Lnet/kyori/adventure/key/Key; + public abstract fun hasItem (Lnet/kyori/adventure/key/Key;)Z + public abstract fun isItem (Lorg/bukkit/inventory/ItemStack;Lnet/kyori/adventure/key/Key;)Z +} + public abstract class ru/endlesscode/mimic/level/BukkitLevelSystem : ru/endlesscode/mimic/level/LevelSystem { public fun (Lorg/bukkit/entity/Player;)V public final fun getPlayer ()Lorg/bukkit/entity/Player; diff --git a/mimic-bukkit-api/src/main/kotlin/Mimic.kt b/mimic-bukkit-api/src/main/kotlin/Mimic.kt index abacdf71..32fe0c33 100644 --- a/mimic-bukkit-api/src/main/kotlin/Mimic.kt +++ b/mimic-bukkit-api/src/main/kotlin/Mimic.kt @@ -1,7 +1,7 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic @@ -18,6 +18,8 @@ import ru.endlesscode.mimic.classes.ClassProvider import ru.endlesscode.mimic.classes.Classes import ru.endlesscode.mimic.inventory.BukkitPlayerInventory import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.Items import ru.endlesscode.mimic.level.BukkitLevelSystem import ru.endlesscode.mimic.level.LevelProvider import ru.endlesscode.mimic.level.Levels @@ -168,6 +170,7 @@ public interface Mimic { * @param plugin The plugin implementing this item registry. * @return registered registry or `null` if it was not registered. */ + @Deprecated("Use registerItemProvider instead.") public fun registerItemsRegistry( registry: BukkitItemsRegistry, apiLevel: Int, @@ -187,6 +190,7 @@ public interface Mimic { * preferred service in config. * @return registered registry or `null` if it was not registered. */ + @Deprecated("Use registerItemProvider instead.") public fun registerItemsRegistry( registry: BukkitItemsRegistry, apiLevel: Int, @@ -194,13 +198,67 @@ public interface Mimic { priority: ServicePriority, ): BukkitItemsRegistry? - /** Returns [BukkitItemsRegistry] implementation. */ + /** + * Returns [BukkitItemsRegistry] combining items of all item providers. + * Unlike [items], it searches an ID without a namespace over all providers. + */ + @Deprecated("Use items instead.") public val itemsRegistry: BukkitItemsRegistry /** Returns map containing all known [BukkitItemsRegistry], where key is an item registry ID. */ + @Deprecated("Use items.getAllItems() instead.") public fun getAllItemsRegistries(): Map // endregion + // region Items + /** + * Registers the given [provider] of items with normal priority. + * + * @param provider The [ItemProvider] implementation. + * @param apiLevel Minimal required API level for this item provider implementation: + * - if the required API level is higher than installed Mimic, provider will not be registered, + * - if the required API level is lower - will be enabled compatibility mode. + * Specify `MimicApiLevel.CURRENT` to use API level of Mimic dependency used at compile time. + * @param plugin The plugin implementing this item provider. + * @return registered provider or `null` if it was not registered. + * @since 0.11.0 + */ + public fun registerItemProvider( + provider: ItemProvider, + apiLevel: Int, + plugin: Plugin, + ): ItemProvider? = registerItemProvider(provider, apiLevel, plugin, ServicePriority.Normal) + + /** + * Registers the given [provider] of items. + * + * @param provider The [ItemProvider] implementation. + * @param apiLevel Minimal required API level for this item provider implementation: + * - if the required API level is higher than installed Mimic, provider will not be registered, + * - if the required API level is lower - will be enabled compatibility mode. + * Specify `MimicApiLevel.CURRENT` to use API level of Mimic dependency used at compile time. + * @param plugin The plugin implementing this item provider. + * @param priority Default priority. An item recognized by several providers belongs to the provider + * with the highest priority. + * @return registered provider or `null` if it was not registered. + * @since 0.11.0 + */ + public fun registerItemProvider( + provider: ItemProvider, + apiLevel: Int, + plugin: Plugin, + priority: ServicePriority, + ): ItemProvider? + + /** + * Vanilla and custom items from all plugins: create them by ID, identify stacks, list and validate IDs. + * See [Items] for details and examples. + * To make your plugin's items available here, use [registerItemProvider]. + * @since 0.11.0 + */ + public val items: Items + // endregion + // region Level System /** * Registers the given [provider] for [BukkitLevelSystem] with normal priority. diff --git a/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt b/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt index de16f99d..d2c62409 100644 --- a/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt +++ b/mimic-bukkit-api/src/main/kotlin/items/BukkitItemsRegistry.kt @@ -1,9 +1,12 @@ // Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.items import org.bukkit.inventory.ItemStack /** [ItemsRegistry] for Bukkit. */ +@Deprecated("Use Items API instead: implement ItemProvider to provide items, use Items to get them.") public interface BukkitItemsRegistry : ItemsRegistry diff --git a/mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt b/mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt new file mode 100644 index 00000000..d5ae0dbb --- /dev/null +++ b/mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt @@ -0,0 +1,83 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.items + +import net.kyori.adventure.key.KeyPattern +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.MimicService + +/** + * Implement it to make your plugin's items available via [Items]. + * Register it in `onLoad` via [Mimic.registerItemProvider][ru.endlesscode.mimic.Mimic.registerItemProvider]. + * To create or identify items, use [Items] instead. + * + * ### IDs + * + * Mimic adds your provider [id] as the namespace, so receive and return IDs without it: + * `ruby_sword` becomes `myplugin:ruby_sword`. Don't change [id] later, it breaks consumers' configs. + * + * If your plugin has its own namespaced IDs, convert them to paths: + * - Drop your plugin's own namespace: `myplugin:ruby_sword` -> `ruby_sword`. + * - Keep other namespaces as the first path part: `default:palm_log` -> `default/palm_log`. + * + * Other rules: + * - Allowed characters: `a-z`, `0-9`, `.`, `_`, `-` and `/`. Items with other characters are ignored. + * - To convert other IDs, lowercase them and replace other characters with `_`. + * Keep a map back to the original IDs. + * - If two IDs become the same (`Ruby_Sword` and `ruby_sword`), log a warning and keep one of them. + * + * ### Ownership + * + * An item belongs to the provider with the highest priority that returns an ID for it. + * So return an ID only for your items, and `null` for the rest, including the vanilla items your items are built on. + * Vanilla items belong to Mimic's own `minecraft` provider, which is always asked last. + * + * ### Rules + * + * - Never throw. Return `null` instead. + * - Item IDs may be unknown until your plugin loads its data. Return `null` for them until then. + * - [allItems] and [getItemId] may be called from any thread, [createItem] is called on the main thread. + * - Document the format of the payload your provider takes, or that it takes none. + * + * Mimic does the rest: selects the provider by the item ID namespace, finds the owner of an item, + * compares items by ID, limits the amount of the created stack, and catches errors thrown by the provider. + * + * @since 0.11.0 + */ +public interface ItemProvider : MimicService { + + /** + * IDs of all items this provider knows. + * The list may change while the plugin loads or reloads its data, so it is read on every request. + * Return a [Set] if you can, Mimic uses it to check that an item exists. + */ + public val allItems: Collection + + /** + * Returns ID of the [item], or `null` if it isn't an item of this provider. + * Amount, stats, durability and lore of the stack don't affect the ID. + */ + public fun getItemId(item: ItemStack): String? + + /** + * Creates a new stack of the item with [itemId]. + * The caller owns the returned stack, so never return a shared one. + * + * @param amount Amount of items, at least `1`. If it is greater than the maximum stack size, + * Mimic lowers the amount of the returned stack. + * @param player The player the item is created for, or `null` if there is no such player. + * Use it if the item depends on the player, like items scaled to the player's level. + * @param payload Additional configuration of the item in the format of this provider, or `null`. + * If the provider takes no payload, ignore it. If the payload can't be parsed, return `null`: + * Mimic logs a warning with the item ID and the payload. + * @return the stack, or `null` if the ID is unknown or the payload is invalid. + */ + public fun createItem( + @KeyPattern.Value itemId: String, + amount: Int, + player: Player?, + payload: String?, + ): ItemStack? +} diff --git a/mimic-bukkit-api/src/main/kotlin/items/Items.kt b/mimic-bukkit-api/src/main/kotlin/items/Items.kt new file mode 100644 index 00000000..f2bf9244 --- /dev/null +++ b/mimic-bukkit-api/src/main/kotlin/items/Items.kt @@ -0,0 +1,95 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.items + +import net.kyori.adventure.key.Key +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack + +/** + * Vanilla items and custom items from all plugins supported by Mimic. + * Get it via [Mimic.items][ru.endlesscode.mimic.Mimic.items]. + * To make your own plugin's items available here, implement [ItemProvider] instead. + * + * ### Quick start + * + * ```java + * Key excalibur = Key.key("mmoitems:sword/excalibur"); + * + * // Check the ID read from a config + * if (!items.hasItem(excalibur)) { ... } + * + * // Create an item for the player + * ItemStack sword = items.createItem(excalibur, 1, player, null); + * + * // Identify an item + * if (items.isItem(player.getInventory().getItemInMainHand(), excalibur)) { ... } + * ``` + * + * ### IDs + * + * Items are identified by [Key], which consists of a namespace and a path: + * - The namespace is the ID of the plugin providing the item: `minecraft`, `mmoitems`, `craftengine`. + * - The path is the item within that plugin: `diamond`, `sword/excalibur`, `default/palm_log`. + * + * The namespace is required, there is no search over all plugins. + * Note that `Key.key("excalibur")` turns into `minecraft:excalibur`, + * so validate item IDs read from configs with [hasItem] or against [getAllItems]. + * + * ### Ownership + * + * An item belongs to the plugin with the highest priority that recognizes it, and vanilla items belong to `minecraft`. + * So a custom item is never recognized as the vanilla item it is built on: + * a ruby built on a diamond is not `minecraft:diamond`. + * To check the vanilla item regardless of plugins, use [ItemStack.getType]. + * + * ### Rules + * + * - [createItem] must be called on the main thread, other methods may be called from any thread. + * - Item IDs may be unknown until their plugins finish loading, and may change when a plugin reloads. + * Don't validate configs in `onLoad`, and don't keep created stacks across reloads. + * - `null` or `false` means "not possible": the item doesn't exist, no plugin recognizes it, or the payload is invalid. + * + * @since 0.11.0 + */ +public interface Items { + + /** + * Returns IDs of all items of all providers. Use it for config validation and tab completion. + * IDs are sorted by provider priority, then in the order the provider returns them. + */ + public fun getAllItems(): List + + /** Returns `true` if the item with [itemId] exists. */ + public fun hasItem(itemId: Key): Boolean + + /** Returns ID of the [item] in the provider owning it, or `null` if no provider recognizes the item. */ + public fun getItemId(item: ItemStack): Key? + + /** + * Returns `true` if the [item] has [itemId]. Same as `getItemId(item) == itemId`: + * amount, stats, durability and lore of the stack are ignored. + */ + public fun isItem(item: ItemStack, itemId: Key): Boolean + + /** Creates a new stack with a single item with [itemId]. */ + public fun createItem(itemId: Key): ItemStack? = createItem(itemId, amount = 1) + + /** Creates a new stack of the item with [itemId] and the given [amount]. */ + public fun createItem(itemId: Key, amount: Int): ItemStack? = + createItem(itemId, amount, player = null, payload = null) + + /** + * Creates a new stack of the item with [itemId]. The caller owns the returned stack. + * + * @param amount Amount of items. It is kept within `1` and the maximum stack size of the item. + * @param player The player the item is created for, or `null` if there is no such player. + * Some items depend on the player, like items scaled to the player's level. + * @param payload Additional configuration of the item in the format of its provider, or `null`. + * For example, `minecraft` takes item components like `[damage=10]`. + * Providers taking no payload ignore it. If the payload is invalid, the item is not created and a warning is logged. + * @return the stack, or `null` if the ID is unknown or the payload is invalid. + */ + public fun createItem(itemId: Key, amount: Int, player: Player?, payload: String?): ItemStack? +} diff --git a/mimic-bukkit/build.gradle.kts b/mimic-bukkit/build.gradle.kts index 65a3aab3..dd7a5388 100644 --- a/mimic-bukkit/build.gradle.kts +++ b/mimic-bukkit/build.gradle.kts @@ -105,6 +105,7 @@ dependencies { testImplementation(libs.rpgplugins.valhallammo) { isTransitive = false } testImplementation(libs.rpgplugins.heroes) { isTransitive = false } testImplementation(libs.rpgplugins.mmocore) { isTransitive = false } + testImplementation(libs.rpgplugins.mmoitems) { isTransitive = false } testImplementation(libs.rpgplugins.mythiclib) { isTransitive = false } testImplementation(libs.rpgplugins.fabled) { isTransitive = false } testImplementation(libs.rpgplugins.codex) { isTransitive = false } diff --git a/mimic-bukkit/src/main/kotlin/MimicImpl.kt b/mimic-bukkit/src/main/kotlin/MimicImpl.kt index 008a9521..f97fff49 100644 --- a/mimic-bukkit/src/main/kotlin/MimicImpl.kt +++ b/mimic-bukkit/src/main/kotlin/MimicImpl.kt @@ -1,7 +1,7 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION", "OVERRIDE_DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION", "OVERRIDE_DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic @@ -17,6 +17,7 @@ import ru.endlesscode.mimic.classes.* import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.mimic.MimicBlocks import ru.endlesscode.mimic.impl.mimic.MimicClasses +import ru.endlesscode.mimic.impl.mimic.MimicItems import ru.endlesscode.mimic.impl.mimic.MimicItemsRegistry import ru.endlesscode.mimic.impl.mimic.MimicLevels import ru.endlesscode.mimic.impl.mimic.MimicResources @@ -26,6 +27,10 @@ import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.internal.authorsMention import ru.endlesscode.mimic.inventory.WrappedPlayerInventoryProvider import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.Items +import ru.endlesscode.mimic.items.ItemsRegistryItemProvider +import ru.endlesscode.mimic.items.WrappedItemProvider import ru.endlesscode.mimic.items.WrappedItemsRegistry import ru.endlesscode.mimic.level.* import ru.endlesscode.mimic.resources.ResourceProvider @@ -62,10 +67,14 @@ internal class MimicImpl( "PlayerInventory", defaultId = MinecraftPlayerInventory.ID, ) - val itemsRegistries = registry( + private val itemsRegistries = registry( "ItemsRegistry", defaultId = MinecraftItemsRegistry.ID, - disabledIds = { config.disabledItemsRegistries }, + ) + val itemProviders = registry( + "ItemProvider", + defaultId = MinecraftItemProvider.ID, + disabledIds = { config.disabledItemProviders }, ) private val levelSystems = registry( "LevelSystem", @@ -87,6 +96,7 @@ internal class MimicImpl( classProviders, playerInventories, itemsRegistries, + itemProviders, levelSystems, levelProviders, resourceProviders, @@ -151,14 +161,38 @@ internal class MimicImpl( apiLevel: Int, plugin: Plugin, priority: ServicePriority, - ): BukkitItemsRegistry? = itemsRegistries.tryRegister(apiLevel, plugin, priority) { - WrappedItemsRegistry(registry, plugin) + ): BukkitItemsRegistry? { + val itemsRegistry = itemsRegistries.tryRegister(apiLevel, plugin, priority) { + WrappedItemsRegistry(registry, plugin) + } + if (itemsRegistry != null) { + itemProviders.registerBridge(ItemsRegistryItemProvider(itemsRegistry), plugin, priority) { + "ItemsRegistry '${itemsRegistry.id}' by $plugin uses deprecated ItemsRegistry API, " + + "so its items are available via Items API as '${itemsRegistry.id}:'. " + + "Please ask ${plugin.authorsMention} to migrate to ItemProvider." + } + } + return itemsRegistry } - override val itemsRegistry: BukkitItemsRegistry = MimicItemsRegistry(itemsRegistries) override fun getAllItemsRegistries(): Map = itemsRegistries.loadAll() // endregion + // region Items + override fun registerItemProvider( + provider: ItemProvider, + apiLevel: Int, + plugin: Plugin, + priority: ServicePriority, + ): ItemProvider? = itemProviders.tryRegister(apiLevel, plugin, priority) { + WrappedItemProvider(provider, plugin) + } + + private val mimicItems = MimicItems(itemProviders) + override val items: Items get() = mimicItems + override val itemsRegistry: BukkitItemsRegistry = MimicItemsRegistry(mimicItems) + // endregion + // region Level System override fun registerLevelSystem( provider: BukkitLevelSystem.Provider, diff --git a/mimic-bukkit/src/main/kotlin/MimicMetrics.kt b/mimic-bukkit/src/main/kotlin/MimicMetrics.kt index bf8a6db5..de087003 100644 --- a/mimic-bukkit/src/main/kotlin/MimicMetrics.kt +++ b/mimic-bukkit/src/main/kotlin/MimicMetrics.kt @@ -25,7 +25,7 @@ internal fun Plugin.initMetrics(mimic: MimicImpl) { metrics.addCustomChart(DrilldownPie("level_providers") { registryChartData(mimic.levelProviders) }) metrics.addCustomChart(DrilldownPie("class_providers") { registryChartData(mimic.classProviders) }) metrics.addCustomChart(DrilldownPie("resource_providers") { registryChartData(mimic.resourceProviders) }) - metrics.addCustomChart(DrilldownPie("items_registries") { registryChartData(mimic.itemsRegistries) }) + metrics.addCustomChart(DrilldownPie("item_providers") { registryChartData(mimic.itemProviders) }) metrics.addCustomChart(DrilldownPie("block_providers") { registryChartData(mimic.blockProviders) }) metrics.addCustomChart(SimplePie("inventory_provider") { mimic.getPlayerInventoryProvider().id }) metrics.addCustomChart(DrilldownPie("dependent_plugins") { dependentPluginsChartData() }) diff --git a/mimic-bukkit/src/main/kotlin/MimicPlugin.kt b/mimic-bukkit/src/main/kotlin/MimicPlugin.kt index 05ab9d36..7f50b192 100644 --- a/mimic-bukkit/src/main/kotlin/MimicPlugin.kt +++ b/mimic-bukkit/src/main/kotlin/MimicPlugin.kt @@ -1,7 +1,7 @@ // Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic @@ -19,7 +19,9 @@ import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.auraskills.AuraSkillsLevelProvider import ru.endlesscode.mimic.impl.auraskills.AuraSkillsResourceProvider import ru.endlesscode.mimic.impl.craftengine.CraftEngineBlockProvider +import ru.endlesscode.mimic.impl.craftengine.CraftEngineItemProvider import ru.endlesscode.mimic.impl.craftengine.CraftEngineItemsRegistry +import ru.endlesscode.mimic.impl.customitems.CustomItemsItemProvider import ru.endlesscode.mimic.impl.customitems.CustomItemsRegistry import ru.endlesscode.mimic.impl.fabled.FabledClassProvider import ru.endlesscode.mimic.impl.fabled.FabledLevelProvider @@ -37,12 +39,14 @@ import ru.endlesscode.mimic.impl.mmocore.MmoCoreClassSystem import ru.endlesscode.mimic.impl.mmocore.MmoCoreLevelProvider import ru.endlesscode.mimic.impl.mmocore.MmoCoreLevelSystem import ru.endlesscode.mimic.impl.mmocore.MmoCoreResourceProvider +import ru.endlesscode.mimic.impl.mmoitems.MmoItemsItemProvider import ru.endlesscode.mimic.impl.mmoitems.MmoItemsRegistry import ru.endlesscode.mimic.impl.valhallammo.ValhallaMmoLevelProvider import ru.endlesscode.mimic.impl.vanilla.* import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.inventory.BukkitPlayerInventory import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider import ru.endlesscode.mimic.level.BukkitLevelSystem import ru.endlesscode.mimic.level.LevelProvider import ru.endlesscode.mimic.resources.ResourceProvider @@ -86,6 +90,7 @@ public class MimicPlugin : JavaPlugin() { hookClasses(PermissionsClassSystem::Provider, priority = Lowest) hookResources(::MinecraftResourceProvider, priority = Lowest) hookInventory(MinecraftPlayerInventory::Provider, priority = Lowest) + hookItems(::MinecraftItemProvider, priority = Lowest) hookItems(::MinecraftItemsRegistry, priority = Lowest) hookBlocks(::MinecraftBlockProvider, priority = Lowest) @@ -106,14 +111,17 @@ public class MimicPlugin : JavaPlugin() { } pluginHooks("CustomItems", "com.jojodmo.customitems.api.CustomItemsAPI") { + hookItems(::CustomItemsItemProvider) hookItems(::CustomItemsRegistry) } pluginHooks("MMOItems", "net.Indyuce.mmoitems.MMOItems") { + hookItems(::MmoItemsItemProvider) hookItems(::MmoItemsRegistry) } pluginHooks("CraftEngine", "net.momirealms.craftengine.bukkit.api.CraftEngineBlocks") { + hookItems(::CraftEngineItemProvider) hookItems(::CraftEngineItemsRegistry) hookBlocks(::CraftEngineBlockProvider) } @@ -197,6 +205,14 @@ public class MimicPlugin : JavaPlugin() { mimic.registerPlayerInventoryProvider(constructor.invoke(), MimicApiLevel.CURRENT, this, priority) } + private fun hookItems( + constructor: () -> ItemProvider, + priority: ServicePriority = Normal, + ) { + mimic.registerItemProvider(constructor.invoke(), MimicApiLevel.CURRENT, this, priority) + } + + @JvmName("hookItems_deprecated") private fun hookItems( constructor: () -> BukkitItemsRegistry, priority: ServicePriority = Normal, diff --git a/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt b/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt index 13c73fe1..9eaae531 100644 --- a/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt +++ b/mimic-bukkit/src/main/kotlin/command/ConfigCommand.kt @@ -10,10 +10,11 @@ import ru.endlesscode.mimic.Mimic import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.mimic.getBlockProviderIds import ru.endlesscode.mimic.impl.mimic.getClassProviderIds +import ru.endlesscode.mimic.impl.mimic.getItemProviderIds import ru.endlesscode.mimic.impl.mimic.getLevelProviderIds import ru.endlesscode.mimic.impl.mimic.getResourceProviderIds import ru.endlesscode.mimic.impl.vanilla.MinecraftBlockProvider -import ru.endlesscode.mimic.impl.vanilla.MinecraftItemsRegistry +import ru.endlesscode.mimic.impl.vanilla.MinecraftItemProvider /** * Commands to see and change Mimic config. @@ -70,22 +71,22 @@ internal fun CommandBuilder.configSubcommand( } } - // Enable/Disable an item registry in Mimic - literal("disabled-items-registries") { + // Enable/Disable an item provider in Mimic + literal("disabled-item-providers") { literal(ACTION_ADD) { stringSetArgument( - ITEMS_REGISTRY, - "items registry", - { mimic.getAllItemsRegistries().keys - MinecraftItemsRegistry.ID }, - permanentOptions = setOf(MinecraftItemsRegistry.ID), - ) { sender, itemsRegistry -> - config.disabledItemsRegistries += itemsRegistry + ITEM_PROVIDER, + "item provider", + { mimic.getItemProviderIds() - MinecraftItemProvider.ID }, + permanentOptions = setOf(MinecraftItemProvider.ID), + ) { sender, itemProvider -> + config.disabledItemProviders += itemProvider showConfig(sender) } } literal(ACTION_REMOVE) { - stringSetArgument(ITEMS_REGISTRY, "disabled items registry", { config.disabledItemsRegistries }) { sender, itemsRegistry -> - config.disabledItemsRegistries -= itemsRegistry + stringSetArgument(ITEM_PROVIDER, "disabled item provider", { config.disabledItemProviders }) { sender, itemProvider -> + config.disabledItemProviders -= itemProvider showConfig(sender) } } @@ -142,7 +143,7 @@ private fun CommandBuilder.stringSetArgument( } private const val VALUE = "value" -private const val ITEMS_REGISTRY = "items-registry" +private const val ITEM_PROVIDER = "item-provider" private const val BLOCK_PROVIDER = "block-provider" private const val ACTION_ADD = "add" private const val ACTION_REMOVE = "remove" diff --git a/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt b/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt index 1f4c97e1..55464d76 100644 --- a/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt +++ b/mimic-bukkit/src/main/kotlin/command/ConfigMessage.kt @@ -12,13 +12,14 @@ import ru.endlesscode.mimic.config.StringConfigProperty import ru.endlesscode.mimic.config.StringSetConfigProperty import ru.endlesscode.mimic.impl.mimic.getBlockProviderIds import ru.endlesscode.mimic.impl.mimic.getClassProviderIds +import ru.endlesscode.mimic.impl.mimic.getItemProviderIds import ru.endlesscode.mimic.impl.mimic.getLevelProviderIds import ru.endlesscode.mimic.impl.mimic.getPrimaryClassProviderId import ru.endlesscode.mimic.impl.mimic.getPrimaryLevelProviderId import ru.endlesscode.mimic.impl.mimic.getPrimaryResourceProviderId import ru.endlesscode.mimic.impl.mimic.getResourceProviderIds import ru.endlesscode.mimic.impl.vanilla.MinecraftBlockProvider -import ru.endlesscode.mimic.impl.vanilla.MinecraftItemsRegistry +import ru.endlesscode.mimic.impl.vanilla.MinecraftItemProvider import ru.endlesscode.mimic.internal.append import ru.endlesscode.mimic.internal.appendLine import ru.endlesscode.mimic.internal.text @@ -51,10 +52,10 @@ internal fun buildConfigMessage(mimic: Mimic, config: MimicConfig): TextComponen options = mimic.getAllPlayerInventoryProviders().keys, ) appendSetPropertyConfig( - property = MimicConfig.DISABLED_ITEMS_REGISTRIES, - values = config.disabledItemsRegistries, - options = mimic.getAllItemsRegistries().keys, - permanentOptions = setOf(MinecraftItemsRegistry.ID), + property = MimicConfig.DISABLED_ITEM_PROVIDERS, + values = config.disabledItemProviders, + options = mimic.getItemProviderIds(), + permanentOptions = setOf(MinecraftItemProvider.ID), ) appendSetPropertyConfig( property = MimicConfig.DISABLED_BLOCK_PROVIDERS, diff --git a/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt b/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt index ec5d9c59..dffc4d82 100644 --- a/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt +++ b/mimic-bukkit/src/main/kotlin/command/ItemsSubcommand.kt @@ -6,19 +6,18 @@ package ru.endlesscode.mimic.command import com.mojang.brigadier.arguments.IntegerArgumentType import com.mojang.brigadier.arguments.StringArgumentType import io.papermc.paper.command.brigadier.argument.ArgumentTypes +import net.kyori.adventure.key.Key import net.kyori.adventure.text.Component import org.bukkit.command.CommandSender import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack -import ru.endlesscode.mimic.impl.mimic.MimicItemsRegistry -import ru.endlesscode.mimic.impl.mimic.registry import ru.endlesscode.mimic.internal.append import ru.endlesscode.mimic.internal.appendLine import ru.endlesscode.mimic.internal.text -import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.Items /** - * Commands to deal with items registries + * Commands to deal with items. * ``` * /mimic items (info) * /mimic items give [target] [item] (amount) (payload) @@ -26,41 +25,41 @@ import ru.endlesscode.mimic.items.BukkitItemsRegistry * /mimic items find [item] * ``` */ -internal fun CommandBuilder.itemsSubcommand(itemsRegistry: BukkitItemsRegistry) = literal("items") { - executesAny(infoExecutor(itemsRegistry)) +internal fun CommandBuilder.itemsSubcommand(items: Items) = literal("items") { + executesAny(infoExecutor(items)) - // Show information about items service + // Show information about items literal("info") { - executesAny(infoExecutor(itemsRegistry)) + executesAny(infoExecutor(items)) } // Give item to player literal("give") { argument(TARGET, ArgumentTypes.player()) { - itemArgument(itemsRegistry) { - executesAny(giveExecutor(itemsRegistry)) + itemArgument(items) { + executesAny(giveExecutor(items)) argument(AMOUNT, IntegerArgumentType.integer(1, 64)) { suggestsStrings { listOf("1", "64") } - executesAny(giveExecutor(itemsRegistry)) + executesAny(giveExecutor(items)) argument(PAYLOAD, StringArgumentType.greedyString()) { - executesAny(giveExecutor(itemsRegistry)) + executesAny(giveExecutor(items)) } } } } } - // Compare item in hand corresponds and given item + // Compare item in hand with the given item literal("compare") { - itemArgument(itemsRegistry) { + itemArgument(items) { executesPlayer { sender, context -> - val item = context.getArgument(ITEM) - val isSame = itemsRegistry.isSameItem(sender.requireItemInMainHand(), item) + val itemId = context.getArgument(ITEM) + val isSame = items.isItem(sender.requireItemInMainHand(), itemId) sender.sendMessage(successText { append("Item in hand ") appendVerdict(isSame, "matches", "doesn't match") append(" ") - appendId(item) + appendId(itemId.asString()) append(".") }) } @@ -69,13 +68,13 @@ internal fun CommandBuilder.itemsSubcommand(itemsRegistry: BukkitItemsRegistry) // Check that item with given ID exists literal("find") { - itemArgument(itemsRegistry) { + itemArgument(items) { executesAny { sender, context -> - val item = context.getArgument(ITEM) - val itemExists = itemsRegistry.isItemExists(item) + val itemId = context.getArgument(ITEM) + val itemExists = items.hasItem(itemId) sender.sendMessage(successText { append("Item ") - appendId(item) + appendId(itemId.asString()) append(" ") appendVerdict(itemExists, "exists", "doesn't exist") append(".") @@ -86,51 +85,42 @@ internal fun CommandBuilder.itemsSubcommand(itemsRegistry: BukkitItemsRegistry) } private fun CommandBuilder.itemArgument( - itemRegistry: BukkitItemsRegistry, + items: Items, configure: CommandBuilder.() -> Unit, -) = argument(ITEM, ResourceLocationArgumentType) { - suggestsIds({ context -> itemHints(itemRegistry, context.source.sender) }) { itemRegistry.knownIds } +) = argument(ITEM, KeyArgumentType("item", "minecraft:diamond")) { + suggestsIds({ context -> itemHints(items, context.source.sender) }) { items.itemIds() } configure() } -/** Suggests ID of the item in hand and namespaces of items registries. */ -private fun itemHints(itemRegistry: BukkitItemsRegistry, sender: CommandSender): List { - val itemInHandId = itemInHandId(itemRegistry, sender) - val namespaces = (itemRegistry as? MimicItemsRegistry)?.providers.orEmpty().map { it.registry.id } - val knownIds = itemRegistry.knownIds +private fun Items.itemIds(): List = getAllItems().map { it.asString() } - return listOfNotNull(itemInHandId?.let { SuggestionHint(it, Component.text("Item in hand")) }) + - namespaces.map { SuggestionHint(collapseFolders("$it:", knownIds), Component.text("Items from $it")) } -} +/** Suggests ID of the item in hand and namespaces of items. */ +private fun itemHints(items: Items, sender: CommandSender): List = listOfNotNull( + itemInHandId(items, sender)?.let { SuggestionHint(it.asString(), Component.text("Item in hand")) }, +) + namespaceHints(items.itemIds()) { "Items from $it" } /** Returns ID of the item in [sender]'s hand, or `null` if sender isn't a player or the hand is empty. */ -private fun itemInHandId(itemRegistry: BukkitItemsRegistry, sender: CommandSender): String? = - (sender as? Player)?.inventory?.itemInMainHand - ?.takeUnless { it.type.isAir } - ?.let(itemRegistry::getItemId) +private fun itemInHandId(items: Items, sender: CommandSender): Key? = + (sender as? Player)?.inventory?.itemInMainHand?.let(items::getItemId) private fun Player.requireItemInMainHand(): ItemStack { val item = inventory.itemInMainHand - if (item.type.isAir) throw commandError("You aren't holding an item.") + if (item.isEmpty) throw commandError("You aren't holding an item.") return item } -private fun infoExecutor(itemRegistry: BukkitItemsRegistry): CommandAction = { sender, _ -> - val providers = (itemRegistry as? MimicItemsRegistry)?.providers.orEmpty().map { it.registry } +private fun infoExecutor(items: Items): CommandAction = { sender, _ -> + val allItems = items.getAllItems() val message = text { appendHeader("Mimic Items") - appendStats( - "Item Registry" to itemRegistry.id, - "Known IDs amount" to itemRegistry.knownIds.size.toString(), - ) - - for (provider in providers) { - appendKey(" ${provider.id}: ") - appendValue(provider.knownIds.size.toString()) + appendStats("Items amount" to allItems.size.toString()) + for ((namespace, amount) in allItems.groupingBy { it.namespace() }.eachCount()) { + appendKey(" $namespace: ") + appendValue(amount.toString()) appendLine() } - appendIdStat("Item in hand", itemInHandId(itemRegistry, sender)) + appendIdStat("Item in hand", itemInHandId(items, sender)?.asString()) appendCommands( suggestedCommand("give", "/mimic items give [target] [item] (amount) (payload)", "Give item to player"), suggestedCommand("compare", "/mimic items compare [item]", "Compare item in hand with the given item"), @@ -140,18 +130,22 @@ private fun infoExecutor(itemRegistry: BukkitItemsRegistry): CommandAction = { sender, context -> +private fun giveExecutor(items: Items): CommandAction = { sender, context -> val target = context.getPlayer(TARGET) - val item = context.getArgument(ITEM) + val itemId = context.getArgument(ITEM) val amount = context.getArgumentOrNull(AMOUNT) ?: 1 val payload = context.getArgumentOrNull(PAYLOAD) - val itemStack = itemRegistry.getItem(item, payload, amount) ?: throw commandError("Unknown item '$item'.") + if (!items.hasItem(itemId)) throw commandError("Unknown item '${itemId.asString()}'.") + val itemStack = items.createItem(itemId, amount, target, payload) ?: run { + val payloadHint = if (payload != null) " The payload '$payload' may be invalid, see the console." else "" + throw commandError("Can't create item '${itemId.asString()}'.$payloadHint") + } val givenAmount = itemStack.amount // addItem may change the amount of the passed stack target.giveItem(itemStack) sender.sendMessage(successText { append("Gave $givenAmount ") - appendId(item) + appendId(itemId.asString()) append(" to ${target.name}.") }) if (givenAmount < amount) { diff --git a/mimic-bukkit/src/main/kotlin/command/MainCommand.kt b/mimic-bukkit/src/main/kotlin/command/MainCommand.kt index 72e7f166..cf4f55f4 100644 --- a/mimic-bukkit/src/main/kotlin/command/MainCommand.kt +++ b/mimic-bukkit/src/main/kotlin/command/MainCommand.kt @@ -38,7 +38,7 @@ private fun buildCommand( classesSubcommand(mimic) resourcesSubcommand(mimic) inventorySubcommand(mimic) - itemsSubcommand(mimic.itemsRegistry) + itemsSubcommand(mimic.items) blocksSubcommand(mimic.blocks) }.build() @@ -51,7 +51,7 @@ private fun infoExecutor(pluginFullName: String): CommandAction = executedCommand("classes", "/$COMMAND_NAME classes", "Player classes"), executedCommand("resources", "/$COMMAND_NAME resources", "Player resources: mana, stamina and similar"), executedCommand("inventory", "/$COMMAND_NAME inventory", "Player inventory provider"), - executedCommand("items", "/$COMMAND_NAME items", "Items registries"), + executedCommand("items", "/$COMMAND_NAME items", "Vanilla and custom items"), executedCommand("blocks", "/$COMMAND_NAME blocks", "Vanilla and custom blocks"), ) } diff --git a/mimic-bukkit/src/main/kotlin/command/brigadier.kt b/mimic-bukkit/src/main/kotlin/command/brigadier.kt index 38327167..fe3e1b61 100644 --- a/mimic-bukkit/src/main/kotlin/command/brigadier.kt +++ b/mimic-bukkit/src/main/kotlin/command/brigadier.kt @@ -92,7 +92,6 @@ internal fun RequiredArgumentBuilder.suggestsStrings(prov * Suggests namespaced IDs like `minecraft:stone`, matching the typed input against the path after namespace. * - Empty input: hints from [provideEmptyInputHints]. * - `namespace:path`: [path hints][pathHints] from the namespace, or similar namespaces if the namespace is unknown. - * Namespace `mimic` searches over all namespaces. * - `path` without namespace: [path hints][pathHints] from all namespaces and namespaces starting with `path`. */ internal fun RequiredArgumentBuilder.suggestsIds( @@ -130,7 +129,6 @@ private fun collectIdHints(input: String, ids: Collection): List pathHints(path, parsedIds) in namespaces -> pathHints(path, parsedIds.filter { it.namespace == namespace }) else -> namespaces .filter { namespace in it } @@ -174,10 +172,6 @@ internal fun namespaceHints(ids: List, tooltip: (namespace: String) -> S SuggestionHint(collapseFolders("$namespace:", namespaceIds), Component.text(tooltip(namespace))) } -/** Extends [prefix] with the folders shared by all [ids] starting with it, see [collapseFolders]. */ -internal fun collapseFolders(prefix: String, ids: Collection): String = - collapseFolders(prefix, ids.map(::ParsedId)) - /** * Extends [prefix] with the folders shared by all IDs starting with it, * so `craftengine:` becomes `craftengine:default/` if all IDs are inside `default/`. @@ -209,9 +203,6 @@ private class ParsedId(val id: String) { } } -/** Namespace used by Mimic registries to search IDs over all registries. */ -private const val SEARCH_ALL_NAMESPACE = "mimic" - internal fun CommandContext<*>.hasArgument(name: String): Boolean = nodes.any { it.node.name == name } internal inline fun CommandContext<*>.getArgument(name: String): T = @@ -242,26 +233,6 @@ internal fun CommandContext.getBlockLocation(name: String): internal fun commandError(message: String): CommandSyntaxException = SimpleCommandExceptionType(LiteralMessage(message)).create() -/** - * Resource location like `minecraft:stone`, shown to the client as a key. - * Unlike [ArgumentTypes.key], keeps an ID without namespace as is instead of adding the `minecraft` namespace. - */ -internal object ResourceLocationArgumentType : CustomArgumentType { - - private val expectedId = SimpleCommandExceptionType(LiteralMessage("Expected ID")) - - override fun parse(reader: StringReader): String { - val start = reader.cursor - while (reader.canRead() && reader.peek().isAllowedInResourceLocation()) reader.skip() - if (reader.cursor == start) throw expectedId.createWithContext(reader) - return reader.string.substring(start, reader.cursor) - } - - override fun getNativeType(): ArgumentType = ArgumentTypes.key() - - private fun Char.isAllowedInResourceLocation() = this in 'a'..'z' || this in '0'..'9' || this in "_-.:/" -} - /** * ID with namespace like `minecraft:level`, shown to the client as a key. * Unlike [ArgumentTypes.key], requires the namespace instead of adding `minecraft`. @@ -275,7 +246,8 @@ internal class KeyArgumentType(valueName: String, example: String) : CustomArgum override fun parse(reader: StringReader): Key { val start = reader.cursor - val id = ResourceLocationArgumentType.parse(reader) + while (reader.canRead() && reader.peek().isAllowedInKey()) reader.skip() + val id = reader.string.substring(start, reader.cursor) if (':' !in id || !Key.parseable(id)) { reader.cursor = start throw invalidId.createWithContext(reader, id) @@ -284,4 +256,6 @@ internal class KeyArgumentType(valueName: String, example: String) : CustomArgum } override fun getNativeType(): ArgumentType = ArgumentTypes.key() + + private fun Char.isAllowedInKey() = this in 'a'..'z' || this in '0'..'9' || this in "_-.:/" } diff --git a/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt b/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt index f5d32740..f7840b64 100644 --- a/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt +++ b/mimic-bukkit/src/main/kotlin/config/MimicConfig.kt @@ -8,7 +8,7 @@ import org.bukkit.configuration.file.FileConfiguration import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.plugin.Plugin import ru.endlesscode.mimic.impl.vanilla.MinecraftBlockProvider -import ru.endlesscode.mimic.impl.vanilla.MinecraftItemsRegistry +import ru.endlesscode.mimic.impl.vanilla.MinecraftItemProvider import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.internal.applyDefaults import ru.endlesscode.mimic.internal.setComments @@ -25,7 +25,7 @@ internal class MimicConfig( var classProvider: String by configuration.property(CLASS_PROVIDER) var resourceProvider: String by configuration.property(RESOURCE_PROVIDER) var inventoryProvider: String by configuration.property(INVENTORY_PROVIDER) - var disabledItemsRegistries: Set by configuration.property(DISABLED_ITEMS_REGISTRIES) + var disabledItemProviders: Set by configuration.property(DISABLED_ITEM_PROVIDERS) var disabledBlockProviders: Set by configuration.property(DISABLED_BLOCK_PROVIDERS) constructor(plugin: Plugin) : this(plugin.toString(), File(plugin.dataFolder, "config.yml")) @@ -52,6 +52,7 @@ internal class MimicConfig( configuration.load(file) migrateOption(LEGACY_LEVEL_SYSTEM_PATH, LEVEL_PROVIDER) migrateOption(LEGACY_CLASS_SYSTEM_PATH, CLASS_PROVIDER) + migrateOption(LEGACY_DISABLED_ITEMS_REGISTRIES_PATH, DISABLED_ITEM_PROVIDERS) migrateOption(LEGACY_DISABLED_BLOCK_REGISTRIES_PATH, DISABLED_BLOCK_PROVIDERS) validateConfigValues() } catch (e: Throwable) { @@ -69,12 +70,11 @@ internal class MimicConfig( } private fun validateConfigValues() { - val configuredDisabledItemsRegistries = disabledItemsRegistries - disabledItemsRegistries = configuredDisabledItemsRegistries - MinecraftItemsRegistry.ID - - val notDisabledRegistries = configuredDisabledItemsRegistries - disabledItemsRegistries - if (notDisabledRegistries.isNotEmpty()) { - Log.w("Config: Items registries $notDisabledRegistries can not be disabled. It will be removed from config.") + val configuredDisabledItemProviders = disabledItemProviders + disabledItemProviders = configuredDisabledItemProviders - MinecraftItemProvider.ID + val notDisabledItemProviders = configuredDisabledItemProviders - disabledItemProviders + if (notDisabledItemProviders.isNotEmpty()) { + Log.w("Config: Item providers $notDisabledItemProviders can not be disabled. It will be removed from config.") } val configuredDisabledBlockProviders = disabledBlockProviders @@ -119,6 +119,7 @@ internal class MimicConfig( private const val LEGACY_LEVEL_SYSTEM_PATH = "level-system" private const val LEGACY_CLASS_SYSTEM_PATH = "class-system" + private const val LEGACY_DISABLED_ITEMS_REGISTRIES_PATH = "disabled-items-registries" private const val LEGACY_DISABLED_BLOCK_REGISTRIES_PATH = "disabled-block-registries" val LEVEL_PROVIDER = StringConfigProperty( @@ -159,13 +160,13 @@ internal class MimicConfig( EMPTY_VALUE_MESSAGE, ), ) - val DISABLED_ITEMS_REGISTRIES = StringSetConfigProperty( - path = "disabled-items-registries", - title = "ItemsRegistry API", + val DISABLED_ITEM_PROVIDERS = StringSetConfigProperty( + path = "disabled-item-providers", + title = "Items API", comments = arrayOf( - "List here disabled items registry implementations.", - "You can't disable 'minecraft' items registry.", - "By default, all implementations are enabled.", + "List here plugins whose items should not be available via Mimic.", + "You can't disable 'minecraft' item provider.", + "By default, all item providers are enabled.", ), ) @@ -184,7 +185,7 @@ internal class MimicConfig( CLASS_PROVIDER, RESOURCE_PROVIDER, INVENTORY_PROVIDER, - DISABLED_ITEMS_REGISTRIES, + DISABLED_ITEM_PROVIDERS, DISABLED_BLOCK_PROVIDERS, ) } diff --git a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt new file mode 100644 index 00000000..a779e247 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemProvider.kt @@ -0,0 +1,44 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.craftengine + +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider for CraftEngine custom items. + * CraftEngine namespace becomes the first path segment of item ID: `default:palm_log` -> `default/palm_log`. + * Vanilla items modified by CraftEngine are left to the `minecraft` provider. + * Takes no payload. An item created for a player is built by CraftEngine for this player. + */ +internal class CraftEngineItemProvider( + private val craftEngine: CraftEngineWrapper = CraftEngineWrapper(), +) : ItemProvider { + + override val id: String = ID + override val isEnabled: Boolean get() = craftEngine.isEnabled + + /** A view of the loaded items, so checking that an item exists doesn't convert all IDs. */ + override val allItems: Set = object : AbstractSet() { + override val size: Int get() = craftEngine.loadedCustomItems.size + + override fun iterator(): Iterator = + craftEngine.loadedCustomItems.asSequence().map { it.id().toMimicId() }.iterator() + + override fun contains(element: String): Boolean = + craftEngineKey(element)?.let(craftEngine::getCustomItem) != null + } + + override fun getItemId(item: ItemStack): String? = craftEngine.getCustomItem(item)?.id()?.toMimicId() + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val key = craftEngineKey(itemId) ?: return null + return craftEngine.createCustomItem(key, amount, player) + } + + companion object { + const val ID: String = "craftengine" + } +} diff --git a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt index 68de5345..58d5b891 100644 --- a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.craftengine import net.momirealms.craftengine.bukkit.item.BukkitItemDefinition @@ -12,6 +14,7 @@ import ru.endlesscode.mimic.items.BukkitItemsRegistry * CraftEngine namespace becomes the first path segment of item ID: `default:palm_log` -> `default/palm_log`. * Vanilla items modified by CraftEngine are left to the vanilla registry. */ +@Deprecated("Use Items API instead, CraftEngine items have the same IDs there.") public class CraftEngineItemsRegistry private constructor( private val craftEngine: CraftEngineWrapper, ) : BukkitItemsRegistry { diff --git a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt index 3380380e..20333fb7 100644 --- a/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt +++ b/mimic-bukkit/src/main/kotlin/impl/craftengine/CraftEngineWrapper.kt @@ -16,6 +16,7 @@ import net.momirealms.craftengine.core.util.Key import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.block.Block +import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack /** @@ -35,9 +36,15 @@ internal class CraftEngineWrapper { fun getCustomItem(item: ItemStack): BukkitItemDefinition? = CraftEngineItems.byItemStack(item)?.takeUnless { it.isVanillaItem } - /** Creates custom item with the given [amount], limited to the item's maximum stack size. */ - fun createCustomItem(id: Key, amount: Int): ItemStack? = - getCustomItem(id)?.buildBukkitItem()?.also { it.amount = amount.coerceIn(1, it.maxStackSize) } + /** + * Creates custom item with the given [amount], limited to the item's maximum stack size. + * The item is built for the [player] if it is given. + */ + fun createCustomItem(id: Key, amount: Int, player: Player? = null): ItemStack? { + val definition = getCustomItem(id) ?: return null + val item = if (player != null) definition.buildBukkitItem(player) else definition.buildBukkitItem() + return item?.also { it.amount = amount.coerceIn(1, it.maxStackSize) } + } fun getBlock(id: Key): BlockDefinition? = CraftEngineBlocks.byId(id) fun getBlockState(block: Block): ImmutableBlockState? = CraftEngineBlocks.getCustomBlockState(block) diff --git a/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt new file mode 100644 index 00000000..de9e7674 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsItemProvider.kt @@ -0,0 +1,35 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.customitems + +import com.jojodmo.customitems.api.CustomItemsAPI +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider for CustomItems. Takes no payload, items don't depend on a player. + * + * CustomItems can't list its items, so [allItems] has nothing to iterate over, but still checks that an item exists. + */ +internal class CustomItemsItemProvider : ItemProvider { + + override val id: String = ID + override val isEnabled: Boolean get() = CustomItemsAPI.isEnabled() + + override val allItems: Set = object : AbstractSet() { + override val size: Int = 0 + override fun iterator(): Iterator = emptyList().iterator() + override fun contains(element: String): Boolean = CustomItemsAPI.getCustomItem(element) != null + } + + override fun getItemId(item: ItemStack): String? = CustomItemsAPI.getCustomItemID(item)?.lowercase() + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + CustomItemsAPI.getCustomItem(itemId, amount) + + companion object { + const val ID: String = "customitems" + } +} diff --git a/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt index cae4e343..ac7ca2aa 100644 --- a/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/customitems/CustomItemsRegistry.kt @@ -1,12 +1,15 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.customitems import com.jojodmo.customitems.api.CustomItemsAPI import org.bukkit.inventory.ItemStack import ru.endlesscode.mimic.items.BukkitItemsRegistry +@Deprecated("Use Items API instead, CustomItems items have the same IDs there.") public class CustomItemsRegistry : BukkitItemsRegistry { override val id: String = ID diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt deleted file mode 100644 index a3c1ae3d..00000000 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/ItemsRegistryProvider.kt +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2018 Osip Fatkullin, EndlessCode Group and contributors -// SPDX-License-Identifier: MIT - -package ru.endlesscode.mimic.impl.mimic - -import ru.endlesscode.mimic.ServiceEntry -import ru.endlesscode.mimic.items.BukkitItemsRegistry - -internal typealias ItemsRegistryProvider = ServiceEntry - -internal inline val ItemsRegistryProvider.registry: BukkitItemsRegistry - get() = service diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt new file mode 100644 index 00000000..98db2c31 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItems.kt @@ -0,0 +1,77 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mimic + +import net.kyori.adventure.key.Key +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.Mimic +import ru.endlesscode.mimic.ServiceEntry +import ru.endlesscode.mimic.ServiceRegistry +import ru.endlesscode.mimic.call +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.Items + +internal typealias ItemProviderEntry = ServiceEntry + +/** + * Items combining items of all item providers, using provider IDs as namespaces: + * `sword/excalibur` -> `mmoitems:sword/excalibur`. + * + * An item belongs to the provider with the highest priority recognizing it, + * so a custom item built on a vanilla item is not recognized as the vanilla item. + */ +internal class MimicItems(itemProviders: ServiceRegistry) : Items { + + val providers = NamespacedProviders(itemProviders, hasVanillaValues = true) + + override fun getAllItems(): List = providers.enabled.flatMap { it.getAllItems() } + + override fun hasItem(itemId: Key): Boolean = findProvider(itemId)?.hasItem(itemId.value()) == true + + override fun getItemId(item: ItemStack): Key? = owner(item)?.second + + override fun isItem(item: ItemStack, itemId: Key): Boolean = getItemId(item) == itemId + + override fun createItem(itemId: Key, amount: Int, player: Player?, payload: String?): ItemStack? = + findProvider(itemId)?.createItem(itemId.value(), amount, player, payload) + + /** Returns the provider owning the [item] paired with the ID of the item, or `null` if no provider recognizes it. */ + fun owner(item: ItemStack): Pair? = providers.owner(ITEM) { getItemId(item) } + + private fun findProvider(itemId: Key): ItemProviderEntry? = + providers.find(itemId, ITEM) { path -> hasItem(path) } + + // IDs are checked inside call, so a provider returning nulls from Java is skipped + private fun ItemProviderEntry.getAllItems(): List = + call(default = emptyList()) { validValues(allItems, ITEM) { it }.map { key(it) } } + + private companion object { + const val ITEM = "item" + } +} + +/** Returns `true` if this provider has the item with the given [path]. */ +internal fun ItemProviderEntry.hasItem(path: String): Boolean = call(default = false) { path in allItems } + +/** + * Creates the item with the given [path] via this provider, keeping the amount within `1` and the maximum stack size. + * Warns once if the provider can't create an existing item with the given [payload]. + */ +internal fun ItemProviderEntry.createItem(path: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val minAmount = amount.coerceAtLeast(1) + return call(default = null) { + val item = createItem(path, minAmount, player, payload) + if (item == null && payload != null && path in allItems) { + val itemId = key(path).asString() + warnings.warn("invalid-payload:$itemId:$payload") { + "Item '$itemId' isn't created, because $apiName '${service.id}' can't use payload '$payload'." + } + } + item?.also { it.amount = it.amount.coerceIn(1, it.maxStackSize) } + } +} + +/** IDs of all registered item providers, including bridged items registries, the values of `disabled-item-providers` config option. */ +internal fun Mimic.getItemProviderIds(): Set = (items as MimicItems).providers.allIds diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt index 4231d317..1974b618 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mimic/MimicItemsRegistry.kt @@ -1,63 +1,61 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mimic import org.bukkit.inventory.ItemStack -import ru.endlesscode.mimic.ServiceRegistry +import ru.endlesscode.mimic.call +import ru.endlesscode.mimic.impl.mmoitems.MmoItemsItemProvider import ru.endlesscode.mimic.internal.MimicId -import ru.endlesscode.mimic.internal.authorsMention +import ru.endlesscode.mimic.internal.OnceWarnings import ru.endlesscode.mimic.internal.parseMimicId import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemsRegistryItemProvider /** - * Items registry combining all items registries, using their IDs as namespaces: `acacia_boat` -> `minecraft:acacia_boat`. - * ID without namespace or with the `mimic` namespace is searched over all registries. - * Deprecated IDs with uppercase letters or more than one `:` are accepted with a warning. + * Items registry showing items of all item providers via the deprecated ItemsRegistry API, + * using provider IDs as namespaces: `acacia_boat` -> `minecraft:acacia_boat`. + * + * Unlike Items API, it accepts IDs deprecated there: + * - ID without namespace or with the `mimic` namespace is searched over all providers. + * - IDs with uppercase letters or more than one `:` are accepted with a warning. + * - MMOItems ID without item type (`mmoitems:excalibur`) is accepted with a warning if only one type has this item. */ -public class MimicItemsRegistry internal constructor( - private val registries: ServiceRegistry, -) : BukkitItemsRegistry { +@Deprecated("Use Items API instead.") +public class MimicItemsRegistry internal constructor(private val items: MimicItems) : BukkitItemsRegistry { override val id: String = ID override val knownIds: Collection - get() = providers.flatMap { provider -> - provider.tryGetKnownIds().mapNotNull { provider.namespaced(it) } - } + get() = items.getAllItems().map { it.asString() } - internal val providers: List - get() = registries.enabledEntries + private val warnings: OnceWarnings + get() = items.providers.registry.warnings override fun isSameItem(item: ItemStack, itemId: String): Boolean { - val id = parse(itemId) ?: return false - return getRegistries(id) - .any { provider -> provider.tryIsSameItem(item, id.path) } + val (owner, ownerId) = items.owner(item) ?: return false + return candidates(itemId).any { (provider, path) -> + provider == owner && (path == ownerId.value() || provider.isSameItemInRegistry(item, path)) + } } - override fun isItemExists(itemId: String): Boolean { - val id = parse(itemId) ?: return false - return getRegistries(id) - .any { provider -> provider.tryIsItemExists(id.path) } - } + override fun isItemExists(itemId: String): Boolean = + candidates(itemId).any { (provider, path) -> provider.hasItem(path) } - override fun getItemId(item: ItemStack): String? { - val (provider, itemId) = providers.firstNotNullOfOrNull { provider -> - provider.tryGetItemId(item)?.let { provider to it } - } ?: return null - return provider.namespaced(itemId) - } + override fun getItemId(item: ItemStack): String? = items.getItemId(item)?.asString() - override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? { - val id = parse(itemId) ?: return null - return getRegistries(id) - .mapNotNull { service -> service.tryGetItem(id.path, payload, amount) } - .firstOrNull() - } + override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? = + candidates(itemId).firstNotNullOfOrNull { (provider, path) -> provider.getItem(path, payload, amount) } - private fun getRegistries(id: MimicId): Sequence { - return providers.asSequence() - .filter { id.matches(it.registry.id) } + /** Returns providers that may have the item with the given [itemId], paired with the ID of the item in the provider. */ + private fun candidates(itemId: String): List> { + val id = parse(itemId) ?: return emptyList() + val path = id.path.replace(':', '/') + return items.providers.enabled + .filter { id.matches(it.service.id) } + .map { provider -> provider to provider.withMmoItemsType(path) } } /** Parses the given [itemId], or returns `null` if it is invalid. */ @@ -66,32 +64,56 @@ public class MimicItemsRegistry internal constructor( val id = parseMimicId(lowercaseId, allowLegacy = true) ?: return null if (lowercaseId != itemId) { - registries.warnings.warn("uppercase:$itemId") { "Item ID '$itemId' is deprecated, use '$lowercaseId' instead." } + warnings.warn("uppercase:$itemId") { "Item ID '$itemId' is deprecated, use '$lowercaseId' instead." } } if (id.isLegacy) { - registries.warnings.warn("legacy") { "Item ID '$itemId' contains more than one ':', this is deprecated." } + warnings.warn("legacy:$itemId") { + "Item ID '$itemId' contains more than one ':', this is deprecated. Use '/' instead of the next ones." + } } return id } - /** Returns the given [itemId] prefixed with the registry ID, or `null` if the result is invalid. */ - private fun ItemsRegistryProvider.namespaced(itemId: String): String? { - val namespacedId = "${registry.id}:$itemId" - val id = parseMimicId(namespacedId, allowLegacy = true) - when { - id == null -> warnings.warn("invalid:${registry.id}") { - "Items registry '${registry.id}' returned invalid ID '$itemId', such items are ignored. " + - "IDs may contain only a-z, 0-9, '.', '_', '-' and '/'. " + - "Please, report it to ${plugin.authorsMention}." + /** + * MMOItems IDs had no item type before Mimic 0.11: `mmoitems:excalibur` instead of `mmoitems:sword/excalibur`. + * Returns the [path] with the type if this is MMOItems provider and only one type has the item. + */ + private fun ItemProviderEntry.withMmoItemsType(path: String): String { + if (service.id != MmoItemsItemProvider.ID || '/' in path) return path + val paths = call(default = emptyList()) { allItems.filter { it.substringAfter('/') == path } } + when (paths.size) { + 0 -> Unit + 1 -> warnings.warn("mmoitems-type:$path") { + "Item ID '${service.id}:$path' without item type is deprecated, use '${service.id}:${paths.single()}' instead." } - id.isLegacy -> warnings.warn("legacy:${registry.id}") { - "Items registry '${registry.id}' returned ID '$itemId' containing ':', this is deprecated. " + - "Use '/' instead: '${itemId.replace(':', '/')}'. " + - "Please, report it to ${plugin.authorsMention}." + else -> warnings.warn("mmoitems-type:$path") { + "Item ID '${service.id}:$path' is ambiguous, specify item type: ${paths.joinToString { "'${service.id}:$it'" }}." + } + } + return paths.singleOrNull() ?: path + } + + /** Asks the registry behind this provider to compare items, so its own rules still work, like ignoring a part of the ID. */ + private fun ItemProviderEntry.isSameItemInRegistry(item: ItemStack, path: String): Boolean { + val registry = service as? ItemsRegistryItemProvider ?: return false + return call(default = false) { registry.isSameItem(item, path) } + } + + /** Payload may be of any type in ItemsRegistry API, but only registries may take a payload which isn't a string. */ + private fun ItemProviderEntry.getItem(path: String, payload: Any?, amount: Int): ItemStack? { + val registry = service as? ItemsRegistryItemProvider + return when { + payload == null || payload is String -> createItem(path, amount, player = null, payload as String?) + registry != null -> call(default = null) { registry.getItem(path, payload, amount) } + else -> { + warnings.warn("payload-type:${service.id}:${payload.javaClass.name}") { + "$apiName '${service.id}' takes only string payloads, but got ${payload.javaClass.name}. " + + "Items with such payloads aren't created." + } + null } } - return namespacedId.takeIf { id != null } } public companion object { diff --git a/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt deleted file mode 100644 index 3fdac80a..00000000 --- a/mimic-bukkit/src/main/kotlin/impl/mimic/SafeBukkitItemsRegistry.kt +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2021 Osip Fatkullin, EndlessCode Group and contributors -// SPDX-License-Identifier: MIT - -package ru.endlesscode.mimic.impl.mimic - -import org.bukkit.inventory.ItemStack -import ru.endlesscode.mimic.call - -internal fun ItemsRegistryProvider.tryGetKnownIds(): Collection = - call(default = emptyList()) { knownIds } - -internal fun ItemsRegistryProvider.tryIsSameItem(itemStack: ItemStack, itemId: String): Boolean = - call(default = false) { isSameItem(itemStack, itemId) } - -internal fun ItemsRegistryProvider.tryIsItemExists(itemId: String): Boolean = - call(default = false) { isItemExists(itemId) } - -internal fun ItemsRegistryProvider.tryGetItemId(itemStack: ItemStack): String? = - call(default = null) { getItemId(itemStack) } - -internal fun ItemsRegistryProvider.tryGetItem(itemId: String, payload: Any?, amount: Int): ItemStack? = - call(default = null) { getItem(itemId, payload, amount) } diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt new file mode 100644 index 00000000..b485ae07 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsItemProvider.kt @@ -0,0 +1,46 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mmoitems + +import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider for MMOItems. + * MMOItems IDs are unique only within an item type, so the type is the first path segment of item ID: + * `EXCALIBUR` of the type `SWORD` -> `sword/excalibur`. + * Takes no payload. An item created for a player is built by MMOItems for this player. + */ +internal class MmoItemsItemProvider( + private val mmoItems: MmoItemsWrapper = MmoItemsWrapper(), +) : ItemProvider { + + override val id: String = ID + override val isEnabled: Boolean get() = mmoItems.isEnabled + + override val allItems: Collection + get() = mmoItems.templates.map { it.mimicId } + + override fun getItemId(item: ItemStack): String? { + val type = mmoItems.getTypeName(item) ?: return null + val id = mmoItems.getId(item) ?: return null + return mimicId(type, id) + } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val template = mmoItems.templates.find { it.mimicId == itemId } ?: return null + return mmoItems.buildItem(template, player)?.also { it.amount = amount } + } + + private val MMOItemTemplate.mimicId: String + get() = mimicId(mmoItems.getTypeName(this), id) + + private fun mimicId(type: String, id: String): String = "${type.lowercase()}/${id.lowercase()}" + + companion object { + const val ID: String = "mmoitems" + } +} diff --git a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt index 7253701c..e196c1f1 100644 --- a/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/mmoitems/MmoItemsRegistry.kt @@ -1,12 +1,15 @@ // Copyright (c) 2021 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mmoitems import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate import org.bukkit.inventory.ItemStack import ru.endlesscode.mimic.items.BukkitItemsRegistry +@Deprecated("Use Items API instead, MMOItems IDs include the item type there: `mmoitems:sword/excalibur`.") public class MmoItemsRegistry private constructor(private val mmoItems: MmoItemsWrapper) : BukkitItemsRegistry { internal constructor() : this(MmoItemsWrapper()) diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt new file mode 100644 index 00000000..404b9b0c --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt @@ -0,0 +1,58 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.vanilla + +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import ru.endlesscode.mimic.internal.Log +import ru.endlesscode.mimic.items.ItemProvider + +/** + * Item provider using material name as item ID. It recognizes any item, so it is asked last. + * + * Payload formats: + * - [Item components](https://minecraft.wiki/w/Data_component_format) in the format of the `/give` command, + * for example `[damage=10,unbreakable={}]`. Components syntax depends on the server version. + * - [ItemMetaPayload] in HOCON format, see [ItemMetaPayload.parse]. Name and lore support MiniMessage formatting. + */ +internal class MinecraftItemProvider : ItemProvider { + + override val id: String = ID + + override val allItems: Set by lazy { + Material.entries.asSequence() + .filter { it.isObtainableItem } + .mapTo(LinkedHashSet()) { it.name.lowercase() } + } + + override fun getItemId(item: ItemStack): String? = if (item.isEmpty) null else item.type.name.lowercase() + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + val material = Material.getMaterial(itemId.uppercase())?.takeIf { it.isObtainableItem } ?: return null + if (payload == null) return ItemStack(material, amount) + + if (payload.startsWith("[")) { + return try { + Bukkit.getItemFactory().createItemStack("${material.key.asString()}$payload") + .apply { this.amount = amount } + } catch (cause: IllegalArgumentException) { + Log.w(cause, "[$TAG] Invalid components for item $itemId: $payload") + null + } + } + + val metaPayload = ItemMetaPayload.parse(payload) ?: return null + return ItemStack(material, amount).apply { itemMeta = itemMeta?.applyPayload(metaPayload) } + } + + private val Material.isObtainableItem: Boolean + get() = !isLegacy && !isAir && isItem + + companion object { + const val ID: String = "minecraft" + private const val TAG = "MinecraftItemProvider" + } +} diff --git a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt index 53155cba..718a9554 100644 --- a/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.vanilla import org.bukkit.Bukkit @@ -21,6 +23,7 @@ import ru.endlesscode.mimic.items.BukkitItemsRegistry * Name and lore support MiniMessage formatting. * - [ItemMetaPayload] instance. */ +@Deprecated("Use Items API instead, vanilla items have the `minecraft` namespace there too.") public class MinecraftItemsRegistry : BukkitItemsRegistry { override val id: String = ID diff --git a/mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt b/mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt new file mode 100644 index 00000000..a19fc259 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/items/ItemsRegistryItemProvider.kt @@ -0,0 +1,45 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + +package ru.endlesscode.mimic.items + +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack + +/** + * Exposes the given [ItemsRegistry][BukkitItemsRegistry] as an item provider. + * + * Registries may return IDs containing `:`, like `itemsadder:ruby_sword`. Such IDs are exposed with `/` instead. + * A registry may return a shared stack, so created items are cloned. + * The player is ignored, the registry can't create an item for a player. + */ +internal class ItemsRegistryItemProvider(private val registry: BukkitItemsRegistry) : ItemProvider { + + override val id: String get() = registry.id + override val isEnabled: Boolean get() = registry.isEnabled + + override val allItems: Collection + get() = registry.knownIds.map(::toPath) + + override fun getItemId(item: ItemStack): String? = registry.getItemId(item)?.let(::toPath) + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + getItem(itemId, payload, amount) + + /** Creates item with a payload of any type, as [ItemsRegistry] allows. */ + fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? = + registry.getItem(toRegistryId(itemId), payload, amount)?.clone() + + /** Compares the [item] with the [itemId] in the way of the registry, for example, ignoring a part of the ID. */ + fun isSameItem(item: ItemStack, itemId: String): Boolean = registry.isSameItem(item, toRegistryId(itemId)) + + private fun toPath(registryId: String): String = registryId.replace(':', '/') + + /** Returns ID of the registry for the [path], restoring `:` replaced by [toPath]. */ + private fun toRegistryId(path: String): String { + if ('/' !in path || registry.isItemExists(path)) return path + return registry.knownIds.find { toPath(it) == path } ?: path + } +} diff --git a/mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt b/mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt new file mode 100644 index 00000000..bfecf389 --- /dev/null +++ b/mimic-bukkit/src/main/kotlin/items/WrappedItemProvider.kt @@ -0,0 +1,23 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.items + +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import org.bukkit.plugin.Plugin +import ru.endlesscode.mimic.WrappedMimicService + +internal class WrappedItemProvider( + private val delegate: ItemProvider, + plugin: Plugin, +) : WrappedMimicService(delegate, plugin.name), ItemProvider { + + override val allItems: Collection + get() = delegate.allItems + + override fun getItemId(item: ItemStack): String? = delegate.getItemId(item) + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + delegate.createItem(itemId, amount, player, payload) +} diff --git a/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt b/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt index 3b92b539..9cd0030f 100644 --- a/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt +++ b/mimic-bukkit/src/main/kotlin/items/WrappedItemsRegistry.kt @@ -1,6 +1,8 @@ // Copyright (c) 2022 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.items import org.bukkit.inventory.ItemStack @@ -16,6 +18,8 @@ internal class WrappedItemsRegistry( override val knownIds: Collection by delegate::knownIds + override fun isSameItem(item: ItemStack, itemId: String) = delegate.isSameItem(item, itemId) + override fun isItemExists(itemId: String) = delegate.isItemExists(itemId) override fun getItemId(item: ItemStack) = delegate.getItemId(item) diff --git a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt index dd311dff..c7cf0603 100644 --- a/mimic-bukkit/src/test/kotlin/MimicImplTest.kt +++ b/mimic-bukkit/src/test/kotlin/MimicImplTest.kt @@ -1,7 +1,7 @@ // Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT -@file:Suppress("DEPRECATION") // LevelSystem and ClassSystem APIs are deprecated but still supported +@file:Suppress("DEPRECATION") // LevelSystem, ClassSystem and ItemsRegistry APIs are deprecated but still supported package ru.endlesscode.mimic @@ -9,12 +9,15 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.maps.shouldBeEmpty import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import net.kyori.adventure.text.Component +import org.bukkit.Material import org.bukkit.entity.Player import org.bukkit.event.server.PluginDisableEvent +import org.bukkit.inventory.ItemStack import org.bukkit.plugin.Plugin import org.bukkit.plugin.ServicePriority.* import ru.endlesscode.mimic.classes.BukkitClassSystem @@ -23,6 +26,8 @@ import ru.endlesscode.mimic.config.MimicConfig import ru.endlesscode.mimic.impl.mimic.MimicLevels import ru.endlesscode.mimic.impl.mimic.getPrimaryClassProviderId import ru.endlesscode.mimic.impl.vanilla.MinecraftLevelProvider +import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider import ru.endlesscode.mimic.level.* import kotlin.test.Test @@ -38,6 +43,7 @@ internal class MimicImplTest : BukkitTestBase() { private val config: MimicConfig = mockk { every { levelProvider } answers { preferredLevelProvider } every { classProvider } answers { preferredClassProvider } + every { disabledItemProviders } returns emptySet() } // SUT @@ -213,6 +219,49 @@ internal class MimicImplTest : BukkitTestBase() { mimic.getClassSystemProvider().id shouldBe "permissions" } + @Test + fun `when items registry is registered - should provide its items via items`() { + mimic.registerItemsRegistry(TestItemsRegistry("legacy"), MimicApiLevel.CURRENT, thirdParty, Normal) + + mimic.items.getAllItems().map { it.asString() } shouldContainExactly listOf("legacy:registry_item") + mimic.itemsRegistry.knownIds shouldContainExactly listOf("legacy:registry_item") + mimic.getAllItemsRegistries().keys shouldContainExactly listOf("legacy") + } + + // https://github.com/EndlessCodeGroup/Mimic/issues/85 + @Test + fun `when items registry is registered - should keep its own way to compare items`() { + val registry = mimic.registerItemsRegistry(TestItemsRegistry("legacy"), MimicApiLevel.CURRENT, thirdParty, Normal) + + registry?.isSameItem(ItemStack(Material.STONE), "any").shouldBeTrue() + } + + @Test + fun `when item provider is registered after items registry by another plugin - should replace it`() { + mimic.registerItemsRegistry(TestItemsRegistry("custom"), MimicApiLevel.CURRENT, thirdParty, High) + mimic.registerItemProvider(TestItemProvider("custom"), MimicApiLevel.CURRENT, otherPlugin, Normal) + + mimic.items.getAllItems().map { it.asString() } shouldContainExactly listOf("custom:provider_item") + } + + @Test + fun `when items registry is registered after item provider with the same ID - should not bridge it`() { + mimic.registerItemProvider(TestItemProvider("custom"), MimicApiLevel.CURRENT, thirdParty, Normal) + mimic.registerItemsRegistry(TestItemsRegistry("custom"), MimicApiLevel.CURRENT, otherPlugin, High) + + mimic.items.getAllItems().map { it.asString() } shouldContainExactly listOf("custom:provider_item") + } + + @Test + fun `when plugin is disabled - should unregister its items registries and item providers`() { + mimic.registerItemsRegistry(TestItemsRegistry("legacy"), MimicApiLevel.CURRENT, thirdParty, Normal) + mimic.registerItemProvider(TestItemProvider("custom"), MimicApiLevel.CURRENT, thirdParty, Normal) + + mimic.onPluginDisable(PluginDisableEvent(thirdParty)) + + mimic.items.getAllItems().shouldBeEmpty() + } + private fun List.keys() = map { it.key().asString() } private fun Levels.trackName(id: String) = getAllTracks().single { it.key().asString() == id }.name() @@ -242,6 +291,20 @@ internal class MimicImplTest : BukkitTestBase() { override fun getPrimarySlot(player: Player): ClassProvider.Slot? = null } + private class TestItemProvider(override val id: String) : ItemProvider { + override val allItems: Collection = listOf("provider_item") + override fun getItemId(item: ItemStack): String? = null + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = null + } + + private class TestItemsRegistry(override val id: String) : BukkitItemsRegistry { + override val knownIds: Collection = listOf("registry_item") + override fun isSameItem(item: ItemStack, itemId: String): Boolean = true + override fun isItemExists(itemId: String): Boolean = itemId in knownIds + override fun getItemId(item: ItemStack): String? = null + override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? = null + } + private class TestClassSystemProvider(override val id: String) : BukkitClassSystem.Provider { override fun getSystem(player: Player): BukkitClassSystem = mockk { every { primaryClass } returns "Mage" diff --git a/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt b/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt index 4d7e0960..f8099104 100644 --- a/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt +++ b/mimic-bukkit/src/test/kotlin/command/IdHintsTest.kt @@ -76,8 +76,6 @@ internal class IdHintsTest { arguments("craftengine:default/t", listOf("craftengine:default/trees/palm_sapling")), arguments("craftengine:default/trees/", listOf("craftengine:default/trees/palm_sapling")), arguments("minecraft:", listOf("minecraft:stone", "minecraft:stone_stairs")), - // Search over all namespaces - arguments("mimic:def", listOf("craftengine:default/palm_log", "craftengine:default/palm_planks", "craftengine:default/trees/palm_sapling", "craftengine:default/")), // Unknown namespace arguments("craft:palm", listOf("craftengine:palm", "minecraft:palm")), ) diff --git a/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt b/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt index f8fc456f..ddf275cf 100644 --- a/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt +++ b/mimic-bukkit/src/test/kotlin/config/MimicConfigTest.kt @@ -36,6 +36,21 @@ internal class MimicConfigTest : BukkitTestBase() { file.readText() shouldNotContain "disabled-block-registries" } + @Test + fun `when load disabled item providers - should remove default providers`() { + file.writeText("disabled-item-providers: [custom, minecraft]\n") + + loadConfig().disabledItemProviders shouldBe setOf("custom") + } + + @Test + fun `when load legacy disabled items registries option - should move it to disabled item providers`() { + file.writeText("disabled-items-registries: [custom, minecraft]\n") + + loadConfig().disabledItemProviders shouldBe setOf("custom") + file.readText() shouldNotContain "disabled-items-registries" + } + @Test fun `when load legacy level system option - should move it to level provider`() { file.writeText("level-system: custom\n") diff --git a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt index 85dbf4e8..e3797be7 100644 --- a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsRegistryTest.kt @@ -1,9 +1,12 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.mimic import io.kotest.assertions.assertSoftly +import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder @@ -11,10 +14,13 @@ import io.kotest.matchers.collections.shouldNotContain import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.types.shouldNotBeSameInstanceAs import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.bukkit.Material +import org.bukkit.entity.Player import org.bukkit.inventory.ItemStack import org.bukkit.plugin.ServicePriority.Lowest import org.bukkit.plugin.ServicePriority.Normal @@ -25,25 +31,57 @@ import ru.endlesscode.mimic.BukkitTestBase import ru.endlesscode.mimic.ServiceRegistry import ru.endlesscode.mimic.internal.Log import ru.endlesscode.mimic.items.BukkitItemsRegistry +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.ItemsRegistryItemProvider import kotlin.test.Test internal class MimicItemsRegistryTest : BukkitTestBase() { + private val providers = ServiceRegistry("ItemProvider", plugin, defaultId = "test") + // SUT - private val registries = ServiceRegistry("ItemsRegistry", plugin, defaultId = "minecraft") - private val itemsService: BukkitItemsRegistry = MimicItemsRegistry(registries) + private val itemsService: BukkitItemsRegistry = MimicItemsRegistry(MimicItems(providers)) init { - registries.register(TestItemRegistry(), plugin, Lowest) + providers.register(VanillaItemProvider(), plugin, Lowest) } @ParameterizedTest - @ValueSource(strings = ["acacia_boat", "test:acacia_boat"]) + @ValueSource(strings = ["acacia_boat", "test:acacia_boat", "mimic:acacia_boat"]) fun `when check is same item - should return true`(itemId: String) { val item = ItemStack(Material.ACACIA_BOAT) itemsService.isSameItem(item, itemId).shouldBeTrue() } + // https://github.com/EndlessCodeGroup/Mimic/issues/86 + @ParameterizedTest + @CsvSource( + "test:emerald, false", + "emerald, false", + "custom:ruby, true", + "ruby, true", + ) + fun `when check is same item - should not match custom item with its vanilla base`(itemId: String, isSame: Boolean) { + providers.register(RubyItemProvider(), plugin, Normal) + + itemsService.isSameItem(ItemStack(Material.EMERALD), itemId) shouldBe isSame + } + + // https://github.com/EndlessCodeGroup/Mimic/issues/85 + @ParameterizedTest + @CsvSource( + "quantum:gems/ruby, true", + "quantum:ruby, true", + "ruby, true", + "quantum:emerald, false", + "test:ruby, false", + ) + fun `when registry compares items in its own way - should use it`(itemId: String, isSame: Boolean) { + registerRegistry(ModularItemRegistry()) + + itemsService.isSameItem(ItemStack(Material.EMERALD), itemId) shouldBe isSame + } + @ParameterizedTest @ValueSource(strings = ["acacia_boat", "test:acacia_boat", "mimic:acacia_boat", "test:ACACIA_BOAT", "Test:acacia_boat"]) fun `when get item - should return item stack`(itemId: String) { @@ -61,6 +99,33 @@ internal class MimicItemsRegistryTest : BukkitTestBase() { itemsService.getItem(itemId).shouldBeNull() } + @Test + fun `when get item with payload - should pass string payload to provider`() { + val provider = VanillaItemProvider() + providers.register(provider, plugin, Lowest) + + assertSoftly { + itemsService.getItem("test:stone", "[damage=10]", 5)?.amount shouldBe 5 + provider.lastPayload shouldBe "[damage=10]" + // Item providers can't take a payload which isn't a string + itemsService.getItem("test:stone", 42, 5).shouldBeNull() + } + } + + @Test + fun `when get item from registry - should pass payload of any type and copy the stack`() { + val registry = ModularItemRegistry() + registerRegistry(registry) + + val item = itemsService.getItem("quantum:gems/ruby", 42, 5) + + assertSoftly { + registry.lastPayload shouldBe 42 + item?.type shouldBe Material.EMERALD + item shouldNotBeSameInstanceAs registry.sharedStack + } + } + @Test fun `when get id - should return id`() { val item = ItemStack(Material.ACACIA_BOAT) @@ -69,15 +134,15 @@ internal class MimicItemsRegistryTest : BukkitTestBase() { @ParameterizedTest @CsvSource( - "air, true", - "ns:air, false", - "test:air, true", + "stone, true", + "ns:stone, false", + "test:stone, true", "unknown, false", "gold_sword, false", "golden_sword, true", - "mimic:air, true", - "test:AIR, true", - "test:air!, false", + "mimic:stone, true", + "test:STONE, true", + "test:stone!, false", ) fun `when check is item exists`(itemId: String, shouldExist: Boolean) { itemsService.isItemExists(itemId) shouldBe shouldExist @@ -85,12 +150,12 @@ internal class MimicItemsRegistryTest : BukkitTestBase() { @ParameterizedTest @ValueSource(strings = ["test:acacia boat", ":acacia_boat", "test:", "test:acacia_boat!"]) - fun `when use invalid id - should not query registries`(itemId: String) { - val registry = mockk(relaxed = true) { + fun `when use invalid id - should not query providers`(itemId: String) { + val provider = mockk(relaxed = true) { every { id } returns "mock" every { isEnabled } returns true } - registries.register(registry, plugin, Normal) + providers.register(provider, plugin, Normal) assertSoftly { itemsService.isItemExists(itemId) shouldBe false @@ -98,71 +163,169 @@ internal class MimicItemsRegistryTest : BukkitTestBase() { itemsService.isSameItem(ItemStack(Material.ACACIA_BOAT), itemId) shouldBe false } verify(exactly = 0) { - registry.isItemExists(any()) - registry.getItem(any(), any(), any()) - registry.isSameItem(any(), any()) + provider.allItems + provider.createItem(any(), any(), any(), any()) + } + } + + @ParameterizedTest + @ValueSource(strings = ["ia:itemsadder:ruby_sword", "ia:itemsadder/ruby_sword", "mimic:itemsadder:ruby_sword"]) + fun `when registry uses ids with colon - should accept both forms`(itemId: String) { + registerRegistry(LegacyItemRegistry()) + + assertSoftly { + itemsService.isItemExists(itemId).shouldBeTrue() + itemsService.getItem(itemId)?.type shouldBe Material.EMERALD + itemsService.isSameItem(ItemStack(Material.EMERALD), itemId).shouldBeTrue() } } @Test - fun `when registry uses legacy ids - should pass them through`() { - registries.register(LegacyItemRegistry(), plugin, Normal) + fun `when registry uses ids with colon - should return them with slash`() { + registerRegistry(LegacyItemRegistry()) assertSoftly { - itemsService.knownIds shouldContain "ia:itemsadder:ruby_sword" - itemsService.getItemId(ItemStack(Material.EMERALD)) shouldBe "ia:itemsadder:ruby_sword" - itemsService.isItemExists("ia:itemsadder:ruby_sword").shouldBeTrue() - itemsService.getItem("ia:itemsadder:ruby_sword")?.type shouldBe Material.EMERALD + itemsService.knownIds shouldContain "ia:itemsadder/ruby_sword" + itemsService.getItemId(ItemStack(Material.EMERALD)) shouldBe "ia:itemsadder/ruby_sword" } } @Test fun `when registry returns invalid id - should ignore it`() { - registries.register(InvalidIdItemRegistry(), plugin, Normal) + registerRegistry(InvalidIdItemRegistry()) assertSoftly { itemsService.knownIds shouldNotContain "invalid:Ruby Sword" itemsService.knownIds shouldContain "invalid:emerald" - // Should not fall back to the registry with lower priority + // Should not fall back to the provider with lower priority itemsService.getItemId(ItemStack(Material.EMERALD)).shouldBeNull() } } + // https://github.com/EndlessCodeGroup/Mimic/issues/87 + @ParameterizedTest + @ValueSource(strings = ["mmoitems:katana", "katana", "mmoitems:KATANA", "mmoitems:sword/katana"]) + fun `when MMOItems id has no type and is unique - should resolve it`(itemId: String) { + providers.register(MmoItemProvider(), plugin, Normal) + + assertSoftly { + itemsService.isItemExists(itemId).shouldBeTrue() + itemsService.getItem(itemId)?.type shouldBe Material.IRON_SWORD + itemsService.isSameItem(ItemStack(Material.IRON_SWORD), itemId).shouldBeTrue() + itemsService.getItemId(ItemStack(Material.IRON_SWORD)) shouldBe "mmoitems:sword/katana" + } + } + + @Test + fun `when MMOItems id has no type and is not unique - should not resolve it`() { + providers.register(MmoItemProvider(), plugin, Normal) + + assertSoftly { + itemsService.isItemExists("mmoitems:excalibur").shouldBeFalse() + itemsService.getItem("mmoitems:excalibur").shouldBeNull() + } + } + + @Test + fun `when MMOItems id has no type - should warn once`() { + val warnings = mutableListOf() + Log.init({ _, message, _ -> warnings += message.orEmpty() }) + providers.register(MmoItemProvider(), plugin, Normal) + + repeat(2) { + itemsService.getItem("mmoitems:katana") + itemsService.getItem("mmoitems:excalibur") + itemsService.getItem("mmoitems:sword/katana") + } + + warnings.size shouldBe 2 + warnings[0] shouldContain "use 'mmoitems:sword/katana' instead" + warnings[1] shouldContain "'mmoitems:sword/excalibur', 'mmoitems:dagger/excalibur'" + } + @Test fun `when ids are deprecated or invalid - should warn once`() { val warnings = mutableListOf() Log.init({ _, message, _ -> warnings += message.orEmpty() }) - registries.register(LegacyItemRegistry(), plugin, Normal) - registries.register(InvalidIdItemRegistry(), plugin, Normal) + registerRegistry(LegacyItemRegistry()) + registerRegistry(InvalidIdItemRegistry()) repeat(2) { itemsService.knownIds itemsService.getItem("ia:itemsadder:ruby_sword") - itemsService.getItem("ia:itemsadder:ruby_axe") itemsService.getItem("test:ACACIA_BOAT") } - // The first quoted value is the registry ID for registry warnings, and the item ID for input warnings + // The first quoted value is the provider ID for provider warnings, and the item ID for input warnings warnings.map { it.substringAfter("'").substringBefore("'") } shouldContainExactlyInAnyOrder listOf( - "ia", "invalid", "ia:itemsadder:ruby_sword", "test:ACACIA_BOAT", ) } + + private fun registerRegistry(registry: BukkitItemsRegistry) { + providers.register(ItemsRegistryItemProvider(registry), plugin, Normal, isBridge = true) + } } -private class TestItemRegistry : BukkitItemsRegistry { +/** Provider imitating vanilla items. */ +private class VanillaItemProvider : ItemProvider { override val id = "test" - override val knownIds = Material.entries.map { it.name.lowercase() } + override val allItems = Material.entries.filterNot { it.isLegacy }.mapTo(HashSet()) { it.name.lowercase() } - override fun isItemExists(itemId: String): Boolean = itemId in knownIds + var lastPayload: String? = null override fun getItemId(item: ItemStack): String = item.type.name.lowercase() - override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack { - val material = Material.valueOf(itemId.uppercase()) - return ItemStack(material, amount) + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + lastPayload = payload + return if (itemId in allItems) ItemStack(Material.valueOf(itemId.uppercase()), amount) else null + } +} + +/** Provider imitating a plugin with a custom item built on emerald. */ +private class RubyItemProvider : ItemProvider { + override val id = "custom" + override val allItems = listOf("ruby") + + override fun getItemId(item: ItemStack): String? = "ruby".takeIf { item.type == Material.EMERALD } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + if (itemId == "ruby") ItemStack(Material.EMERALD, amount) else null +} + +/** Provider imitating MMOItems, where IDs are unique only within an item type. */ +private class MmoItemProvider : ItemProvider { + override val id = "mmoitems" + override val allItems = listOf("sword/excalibur", "dagger/excalibur", "sword/katana") + + override fun getItemId(item: ItemStack): String? = "sword/katana".takeIf { item.type == Material.IRON_SWORD } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = + if (itemId == "sword/katana") ItemStack(Material.IRON_SWORD, amount) else null +} + +/** + * Registry imitating QuantumRPG: an item may be referred without its module, and the same stack is returned every time. + */ +private class ModularItemRegistry : BukkitItemsRegistry { + override val id = "quantum" + override val knownIds = listOf("gems/ruby") + + val sharedStack = ItemStack(Material.EMERALD) + var lastPayload: Any? = null + + override fun isSameItem(item: ItemStack, itemId: String): Boolean = + item.type == Material.EMERALD && itemId.substringAfter('/') == "ruby" + + override fun isItemExists(itemId: String): Boolean = itemId.substringAfter('/') == "ruby" + + override fun getItemId(item: ItemStack): String? = knownIds.first().takeIf { item.type == Material.EMERALD } + + override fun getItem(itemId: String, payload: Any?, amount: Int): ItemStack? { + lastPayload = payload + return sharedStack.takeIf { isItemExists(itemId) } } } diff --git a/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt new file mode 100644 index 00000000..b10ceb57 --- /dev/null +++ b/mimic-bukkit/src/test/kotlin/impl/mimic/MimicItemsTest.kt @@ -0,0 +1,326 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mimic + +import io.kotest.assertions.assertSoftly +import io.kotest.matchers.booleans.shouldBeFalse +import io.kotest.matchers.collections.shouldBeEmpty +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.types.shouldBeSameInstanceAs +import io.kotest.matchers.types.shouldNotBeSameInstanceAs +import net.kyori.adventure.key.Key +import org.bukkit.Material +import org.bukkit.entity.Player +import org.bukkit.inventory.ItemStack +import org.bukkit.plugin.ServicePriority.* +import org.junit.jupiter.api.assertNotNull +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.ValueSource +import ru.endlesscode.mimic.BukkitTestBase +import ru.endlesscode.mimic.ServiceRegistry +import ru.endlesscode.mimic.internal.Log +import ru.endlesscode.mimic.items.ItemProvider +import ru.endlesscode.mimic.items.Items +import kotlin.test.Test + +internal class MimicItemsTest : BukkitTestBase() { + + private val minecraft = TestItemProvider() + private val custom = CustomItemProvider() + + private var disabledProviders = emptySet() + private val itemProviders = ServiceRegistry( + "ItemProvider", plugin, defaultId = "minecraft", + ) { disabledProviders } + + // SUT + private val items: Items = MimicItems(itemProviders) + + init { + itemProviders.register(minecraft, plugin, Lowest) + itemProviders.register(custom, plugin, Normal) + } + + @Test + fun `when get all items - should return namespaced items of all providers`() { + items.getAllItems().map { it.asString() } shouldContainExactly listOf( + "custom:ruby", + "custom:default/ruby_sword", + "minecraft:stone", + "minecraft:diamond", + "minecraft:ender_pearl", + ) + } + + @Test + fun `when get all items - should skip invalid and duplicated paths`() { + itemProviders.register(InvalidIdItemProvider(), plugin, High) + + val invalidItems = items.getAllItems().filter { it.namespace() == "invalid" } + invalidItems.map { it.asString() } shouldContainExactly listOf("invalid:emerald") + } + + @ParameterizedTest + @CsvSource( + "minecraft:stone, true", + "ns:stone, false", + "mimic:stone, false", + "minecraft:unknown, false", + "custom:default/ruby_sword, true", + "custom:stone, false", + "minecraft:default/ruby_sword, false", + "minecraft:ruby, false", + ) + fun `when check has item`(itemId: String, shouldExist: Boolean) { + items.hasItem(Key.key(itemId)) shouldBe shouldExist + } + + @ParameterizedTest + @CsvSource( + "STONE, minecraft:stone", + "DIAMOND, custom:ruby", + ) + fun `when get item id - should return id of the provider with the highest priority`( + material: Material, + expectedId: String, + ) { + items.getItemId(ItemStack(material)) shouldBe Key.key(expectedId) + } + + @Test + fun `when get id of unknown item - should return null`() { + items.getItemId(ItemStack(Material.AIR)).shouldBeNull() + } + + // https://github.com/EndlessCodeGroup/Mimic/issues/86 + @ParameterizedTest + @CsvSource( + "STONE, minecraft:stone, true", + "STONE, minecraft:diamond, false", + "DIAMOND, custom:ruby, true", + "DIAMOND, minecraft:diamond, false", + "DIAMOND, custom:diamond, false", + ) + fun `when check is item - should compare with id of the owner`( + material: Material, + itemId: String, + shouldBeSame: Boolean, + ) { + items.isItem(ItemStack(material, 5), Key.key(itemId)) shouldBe shouldBeSame + } + + @ParameterizedTest + @CsvSource( + "minecraft:stone, STONE", + "custom:ruby, DIAMOND", + ) + fun `when create item - should return item from the provider`(itemId: String, expected: Material) { + itemProviders.register(FailingItemProvider(), plugin, High) + + val item = items.createItem(Key.key(itemId), amount = 5) + assertNotNull(item, "Item should not be null") + // Not assertSoftly(item), it prints ItemStack requiring ItemFactory which isn't mocked + assertSoftly { + item.type shouldBe expected + item.amount shouldBe 5 + } + } + + @ParameterizedTest + @CsvSource( + "minecraft:stone, 0, 1", + "minecraft:stone, -5, 1", + "minecraft:stone, 64, 64", + "minecraft:stone, 100, 64", + "minecraft:ender_pearl, 64, 16", + ) + fun `when create item - should keep amount within stack size`(itemId: String, amount: Int, expectedAmount: Int) { + val item = items.createItem(Key.key(itemId), amount) + + assertNotNull(item, "Item should not be null") + item.amount shouldBe expectedAmount + } + + @ParameterizedTest + @ValueSource(strings = ["minecraft:unknown", "custom:stone", "ns:stone", "mimic:stone", "failing:stone"]) + fun `when create unknown item - should return null`(itemId: String) { + itemProviders.register(FailingItemProvider(), plugin, High) + + items.createItem(Key.key(itemId), amount = 1).shouldBeNull() + } + + @Test + fun `when create item - should pass player and payload only to the provider of the item`() { + items.createItem(Key.key("minecraft:stone"), amount = 1, player, payload = "[damage=10]") + + assertSoftly { + minecraft.lastPlayer shouldBeSameInstanceAs player + minecraft.lastPayload shouldBe "[damage=10]" + custom.createdItems shouldBe 0 + } + } + + @Test + fun `when use short forms - should use defaults`() { + assertSoftly { + items.createItem(Key.key("minecraft:stone"))?.amount shouldBe 1 + items.createItem(Key.key("minecraft:stone"), 5)?.amount shouldBe 5 + minecraft.lastPlayer.shouldBeNull() + minecraft.lastPayload.shouldBeNull() + } + } + + @Test + fun `when provider can't parse payload - should return null and warn with id and payload once`() { + val warnings = mutableListOf() + Log.init({ _, message, _ -> warnings += message.orEmpty() }) + + repeat(2) { + items.createItem(Key.key("minecraft:stone"), amount = 1, player = null, payload = "[invalid").shouldBeNull() + // Unknown item is not a payload problem + items.createItem(Key.key("minecraft:unknown"), amount = 1, player = null, payload = "[invalid").shouldBeNull() + } + + warnings.single() shouldContain "'minecraft:stone'" + warnings.single() shouldContain "'[invalid'" + } + + @Test + fun `when provider takes no payload - should ignore it`() { + val item = items.createItem(Key.key("custom:ruby"), amount = 1, player = null, payload = "[invalid") + + item?.type shouldBe Material.DIAMOND + } + + @Test + fun `when create item twice - should return different stacks`() { + val first = items.createItem(Key.key("minecraft:stone")) + val second = items.createItem(Key.key("minecraft:stone")) + + first shouldNotBeSameInstanceAs second + } + + @Test + fun `when provider is disabled in config - should ignore it`() { + disabledProviders = setOf(custom.id) + + assertSoftly { + items.hasItem(Key.key("custom:ruby")).shouldBeFalse() + items.createItem(Key.key("custom:ruby")).shouldBeNull() + items.getItemId(ItemStack(Material.DIAMOND)) shouldBe Key.key("minecraft:diamond") + } + } + + @Test + fun `when provider fails to identify item - should not fall back to the default provider`() { + itemProviders.register(FailingItemProvider(), plugin, High) + val item = ItemStack(Material.STONE) + + assertSoftly { + items.getItemId(item).shouldBeNull() + items.isItem(item, Key.key("minecraft:stone")).shouldBeFalse() + } + } + + @Test + fun `when provider fails to identify item - should fall back to other custom providers`() { + itemProviders.register(FailingItemProvider(), plugin, High) + + items.getItemId(ItemStack(Material.DIAMOND)) shouldBe Key.key("custom:ruby") + } + + @Test + fun `when provider fails - should return defaults`() { + itemProviders.register(FailingItemProvider(), plugin, High) + + assertSoftly { + items.getAllItems().filter { it.namespace() == "failing" }.shouldBeEmpty() + items.hasItem(Key.key("failing:stone")).shouldBeFalse() + items.createItem(Key.key("failing:stone")).shouldBeNull() + } + } + + @Test + fun `when provider returns invalid id - should ignore it`() { + itemProviders.register(InvalidIdItemProvider(), plugin, High) + + assertSoftly { + // Should not fall back to the default provider + items.getItemId(ItemStack(Material.STONE)).shouldBeNull() + items.getItemId(ItemStack(Material.DIAMOND)) shouldBe Key.key("custom:ruby") + } + } + + @Test + fun `when minecraft item is unknown - should warn once only if other provider has it`() { + val warnings = mutableListOf() + Log.init({ _, message, _ -> warnings += message.orEmpty() }) + + repeat(2) { + items.hasItem(Key.key("minecraft:ruby")).shouldBeFalse() + items.hasItem(Key.key("minecraft:unknown")).shouldBeFalse() + } + + warnings.single() shouldContain "'minecraft:ruby' doesn't exist" + warnings.single() shouldContain "Did you mean 'custom:ruby'?" + } +} + +/** Provider imitating vanilla items. Takes payload starting with `[`. */ +private class TestItemProvider : ItemProvider { + override val id = "minecraft" + + // Material.isItem requires a server, so the known items are listed explicitly + override val allItems = listOf(Material.STONE, Material.DIAMOND, Material.ENDER_PEARL).map { it.name.lowercase() } + + var lastPlayer: Player? = null + var lastPayload: String? = null + + override fun getItemId(item: ItemStack): String? = item.type.name.lowercase().takeIf { it in allItems } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + lastPlayer = player + lastPayload = payload + if (itemId !in allItems || payload == "[invalid") return null + return ItemStack(Material.valueOf(itemId.uppercase()), amount) + } +} + +/** Provider imitating a plugin with custom items built on diamond. Takes no payload. */ +private class CustomItemProvider : ItemProvider { + override val id = "custom" + override val allItems = listOf("ruby", "default/ruby_sword") + + var createdItems = 0 + + override fun getItemId(item: ItemStack): String? = "ruby".takeIf { item.type == Material.DIAMOND } + + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? { + createdItems++ + return if (itemId == "ruby") ItemStack(Material.DIAMOND, amount) else null + } +} + +/** Provider returning invalid IDs. */ +private class InvalidIdItemProvider : ItemProvider { + override val id = "invalid" + override val allItems = listOf("Ruby Sword", "emerald", "ns:item", "", "emerald") + + override fun getItemId(item: ItemStack): String = allItems.first() + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack? = null +} + +/** Provider failing on every call. */ +private class FailingItemProvider : ItemProvider { + override val id = "failing" + override val allItems: List get() = error("Failure") + + override fun getItemId(item: ItemStack): String = error("Failure") + override fun createItem(itemId: String, amount: Int, player: Player?, payload: String?): ItemStack = + error("Failure") +} diff --git a/mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt b/mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt new file mode 100644 index 00000000..534c06f6 --- /dev/null +++ b/mimic-bukkit/src/test/kotlin/impl/mmoitems/MmoItemsItemProviderTest.kt @@ -0,0 +1,78 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.mmoitems + +import io.kotest.matchers.collections.shouldContainExactly +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.shouldBe +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import net.Indyuce.mmoitems.api.item.template.MMOItemTemplate +import org.bukkit.Material +import org.bukkit.inventory.ItemStack +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.ValueSource +import ru.endlesscode.mimic.BukkitTestBase +import kotlin.test.Test + +internal class MmoItemsItemProviderTest : BukkitTestBase() { + + private val typeNames = mutableMapOf() + private val swordExcalibur = mockTemplate("SWORD", "EXCALIBUR") + private val daggerExcalibur = mockTemplate("DAGGER", "EXCALIBUR") + + private val mmoItems: MmoItemsWrapper = mockk { + every { templates } returns listOf(swordExcalibur, daggerExcalibur) + every { getTypeName(any()) } answers { typeNames.getValue(firstArg()) } + every { getTypeName(any()) } returns null + every { getId(any()) } returns null + every { buildItem(swordExcalibur, any()) } answers { ItemStack(Material.DIAMOND_SWORD) } + every { buildItem(daggerExcalibur, any()) } answers { ItemStack(Material.IRON_SWORD) } + } + + // SUT + private val provider = MmoItemsItemProvider(mmoItems) + + @Test + fun `when get all items - should return ids with item types`() { + provider.allItems shouldContainExactly listOf("sword/excalibur", "dagger/excalibur") + } + + @ParameterizedTest + @CsvSource( + "sword/excalibur, DIAMOND_SWORD", + "dagger/excalibur, IRON_SWORD", + ) + fun `when create item - should use the template of the given type`(itemId: String, expected: Material) { + val item = provider.createItem(itemId, amount = 2, player, payload = null) + + item?.type shouldBe expected + item?.amount shouldBe 2 + verify { mmoItems.buildItem(any(), player) } + } + + @ParameterizedTest + @ValueSource(strings = ["excalibur", "sword/unknown", "axe/excalibur", "sword/excalibur/extra"]) + fun `when create item without type or unknown item - should return null`(itemId: String) { + provider.createItem(itemId, amount = 1, player = null, payload = null).shouldBeNull() + } + + @Test + fun `when get item id - should return id with item type`() { + every { mmoItems.getTypeName(any()) } returns "DAGGER" + every { mmoItems.getId(any()) } returns "EXCALIBUR" + + provider.getItemId(ItemStack(Material.IRON_SWORD)) shouldBe "dagger/excalibur" + } + + @Test + fun `when get id of not MMOItems item - should return null`() { + provider.getItemId(ItemStack(Material.IRON_SWORD)).shouldBeNull() + } + + private fun mockTemplate(type: String, id: String): MMOItemTemplate = + mockk { every { this@mockk.id } returns id }.also { typeNames[it] = type } +} diff --git a/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt new file mode 100644 index 00000000..9532ba45 --- /dev/null +++ b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemProviderTest.kt @@ -0,0 +1,122 @@ +// Copyright (c) 2026 Osip Fatkullin, EndlessCode Group and contributors +// SPDX-License-Identifier: MIT + +package ru.endlesscode.mimic.impl.vanilla + +import io.kotest.assertions.assertSoftly +import io.kotest.matchers.nulls.shouldBeNull +import io.kotest.matchers.nulls.shouldNotBeNull +import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeSameInstanceAs +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.mockkStatic +import io.mockk.unmockkObject +import io.mockk.unmockkStatic +import io.mockk.verify +import net.kyori.adventure.text.Component.text +import org.bukkit.Bukkit +import org.bukkit.Material +import org.bukkit.inventory.ItemFactory +import org.bukkit.inventory.ItemStack +import org.bukkit.inventory.meta.ItemMeta +import ru.endlesscode.mimic.BukkitTestBase +import kotlin.test.AfterTest +import kotlin.test.Test + +internal class MinecraftItemProviderTest : BukkitTestBase() { + + private val itemMeta: ItemMeta = mockk(relaxed = true) { + every { clone() } returns this + } + private val itemFactory: ItemFactory = mockk(relaxed = true) { + every { getItemMeta(any()) } returns itemMeta + every { isApplicable(any(), any()) } returns true + every { asMetaFor(any(), any()) } returns itemMeta + } + + // SUT + private val provider = MinecraftItemProvider() + + init { + mockkStatic(Bukkit::class) + every { Bukkit.getItemFactory() } returns itemFactory + // Material.isItem and Material.isAir require Paper registries which aren't available in tests + mockkObject(Material.STONE, Material.AIR) + every { Material.STONE.isItem } returns true + every { Material.STONE.isAir } returns false + every { Material.AIR.isAir } returns true + } + + @AfterTest + fun tearDown() { + unmockkStatic(Bukkit::class) + unmockkObject(Material.STONE, Material.AIR) + } + + @Test + fun `when create item - should return new stack with amount`() { + val item = provider.createItem("stone", amount = 5, player = null, payload = null).shouldNotBeNull() + + assertSoftly { + item.type shouldBe Material.STONE + item.amount shouldBe 5 + } + } + + @Test + fun `when create unknown item - should return null`() { + assertSoftly { + provider.createItem("unknown", amount = 1, player = null, payload = null).shouldBeNull() + provider.createItem("air", amount = 1, player = null, payload = null).shouldBeNull() + provider.createItem("legacy_stone", amount = 1, player = null, payload = null).shouldBeNull() + } + } + + @Test + fun `when get item id - should return material name`() { + assertSoftly { + provider.getItemId(ItemStack(Material.STONE)) shouldBe "stone" + provider.getItemId(ItemStack(Material.AIR)).shouldBeNull() + } + } + + @Test + fun `when create item with components payload - should create item from components`() { + val createdItem = ItemStack(Material.STONE) + every { itemFactory.createItemStack("minecraft:stone[damage=10]") } returns createdItem + + val item = provider.createItem("stone", amount = 5, player = null, payload = "[damage=10]").shouldNotBeNull() + + assertSoftly { + item shouldBeSameInstanceAs createdItem + item.amount shouldBe 5 + } + verify(exactly = 0) { itemFactory.getItemMeta(any()) } + } + + @Test + fun `when create item with invalid components payload - should return null`() { + every { itemFactory.createItemStack(any()) } throws IllegalArgumentException("Invalid components") + + provider.createItem("stone", amount = 5, player = null, payload = "[unknown=1]").shouldBeNull() + } + + @Test + fun `when create item with HOCON payload - should apply item meta payload`() { + val item = provider.createItem("stone", amount = 5, player = null, payload = "name = Name").shouldNotBeNull() + + assertSoftly { + item.type shouldBe Material.STONE + item.amount shouldBe 5 + } + verify { itemMeta.displayName(text("Name")) } + verify(exactly = 0) { itemFactory.createItemStack(any()) } + } + + @Test + fun `when create item with invalid HOCON payload - should return null`() { + provider.createItem("stone", amount = 5, player = null, payload = "name = {").shouldBeNull() + } +} diff --git a/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt index 4f26be21..8786a27f 100644 --- a/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt +++ b/mimic-bukkit/src/test/kotlin/impl/vanilla/MinecraftItemsRegistryTest.kt @@ -1,6 +1,8 @@ // Copyright (c) 2020 Osip Fatkullin, EndlessCode Group and contributors // SPDX-License-Identifier: MIT +@file:Suppress("DEPRECATION") // ItemsRegistry API is deprecated but still supported + package ru.endlesscode.mimic.impl.vanilla import io.kotest.assertions.assertSoftly From bf2d9c20ed40908addf5be729e5955aa583e44b7 Mon Sep 17 00:00:00 2001 From: Osip Fatkullin Date: Mon, 16 Nov 2026 10:21:35 +0100 Subject: [PATCH 3/3] docs: Document Items API Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 23 ++++++ README.md | 4 +- mimic-bukkit-api/README.md | 160 ++++++++++++++++++++++++++++++++----- mimic-bukkit/README.md | 32 ++++---- 4 files changed, 185 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e31026fa..bb0d6e6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ ## [Unreleased] +### Items API + +New Items API replaces `ItemsRegistry` ([#95](https://github.com/EndlessCodeGroup/Mimic/issues/95)). +See [Items](https://github.com/EndlessCodeGroup/Mimic/blob/develop/mimic-bukkit-api/README.md#items) for details and examples. + +- `Mimic.getItems()` creates and identifies items, `Mimic.registerItemProvider()` makes a plugin's items available. + Requires Mimic API level `MimicApiLevel.VERSION_0_11`. The API is stable. +- Item IDs are `Key`s with a required namespace: `minecraft:diamond`, `craftengine:default/palm_log`. + There is no search over all providers in the new API. +- An item belongs to the provider with the highest priority recognizing it, + so a custom item no longer matches the ID of its vanilla base ([#86](https://github.com/EndlessCodeGroup/Mimic/issues/86)). +- Items can be created for a player, MMOItems and CraftEngine use it. +- The payload is a `String` in the format of the item's provider. An item is not created if its payload is invalid. +- `ItemsRegistry` API is deprecated but keeps working, every items registry is available via Items API. + `Mimic.getItemsRegistry()` shows items of all item providers and still accepts IDs without a namespace. +- Items registries' own `isSameItem` is used again ([#85](https://github.com/EndlessCodeGroup/Mimic/issues/85)). +- **Changed:** MMOItems IDs include the item type: `mmoitems:sword/excalibur` instead of `mmoitems:excalibur` ([#87](https://github.com/EndlessCodeGroup/Mimic/issues/87)). + `ItemsRegistry` API still accepts IDs without the type if only one type has the item, but logs a warning. +- **Changed:** `ItemsRegistry.getItem` returns `null` if an item provider can't use the payload. Previously, the payload was ignored. +- **Changed:** Empty stacks have no ID, and `minecraft:air` is not an item. +- Config option `disabled-items-registries` is renamed to `disabled-item-providers`, the old value is moved automatically. +- `/mimic items` requires item IDs with a namespace and gives items created for the target player. + ### Blocks API New Blocks API replaces the experimental `BlockRegistry` ([#96](https://github.com/EndlessCodeGroup/Mimic/issues/96)). diff --git a/README.md b/README.md index 916cdfe5..cf6a43b7 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,8 @@ With Mimic, you don't need to download all RPG plugins and write specific code f - [ClassSystem] *(deprecated, use [Classes])* - API to work with player's classes. - [Resources] - API to work with player's resources: mana, stamina and similar. Read them, take costs, give them back. - [PlayerInventory] *(experimental)* - API to access player's inventories content. -- [ItemsRegistry] - API adding the possibility to create and validate custom items created with plugins. +- [Items] - API to create and identify vanilla items and custom items created with plugins. +- [ItemsRegistry] *(deprecated, use [Items])* - API to create and validate custom items created with plugins. - [Blocks] - API to identify, set and break vanilla blocks and custom blocks created with plugins. ### Implementations @@ -97,5 +98,6 @@ Please make sure to update tests as appropriate. [ClassSystem]: mimic-api/src/main/kotlin/classes/ClassSystem.kt [Resources]: mimic-bukkit-api/src/main/kotlin/resources/Resources.kt [PlayerInventory]: mimic-api/src/main/kotlin/inventory/PlayerInventory.kt +[Items]: mimic-bukkit-api/src/main/kotlin/items/Items.kt [ItemsRegistry]: mimic-api/src/main/kotlin/items/ItemsRegistry.kt [Blocks]: mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt diff --git a/mimic-bukkit-api/README.md b/mimic-bukkit-api/README.md index 47416e4b..7065f9f7 100644 --- a/mimic-bukkit-api/README.md +++ b/mimic-bukkit-api/README.md @@ -12,7 +12,8 @@ Available services: - [ClassProvider] - [BukkitClassSystem.Provider] *(deprecated, use [ClassProvider])* - [BukkitPlayerInventory.Provider] *(experimental)* -- [BukkitItemsRegistry] +- [ItemProvider] +- [BukkitItemsRegistry] *(deprecated, use [ItemProvider])* - [BlockProvider] > Experimental APIs may change in future versions. @@ -59,7 +60,7 @@ Levels levels = mimic.getLevels(); Classes classes = mimic.getClasses(); Resources resources = mimic.getResources(); BukkitPlayerInventory inventory = mimic.getPlayerInventory(player); -BukkitItemsRegistry itemsRegistry = mimic.getItemsRegistry(); +Items items = mimic.getItems(); Blocks blocks = mimic.getBlocks(); ``` @@ -77,10 +78,9 @@ CharacterClass playerClass = classes.getPrimaryClass(player); // See the "Resources" section below for details boolean isPaid = resources.take(player, Key.key("mmocore:mana"), 20.0); -// ItemsRegistry is not related to player so it can be used without provider -ItemStack stick = itemsRegistry.getItem("minecraft:stick"); -boolean isPalmLogInHand = itemsRegistry.isSameItem(player.getInventory().getItemInMainHand(), "craftengine:default/palm_log"); -boolean isPalmLogExists = itemsRegistry.isItemExists("craftengine:default/palm_log"); +// See the "Items" section below for details +ItemStack sword = items.createItem(Key.key("mmoitems:sword/excalibur"), 1, player, null); +boolean isSwordInHand = items.isItem(player.getInventory().getItemInMainHand(), Key.key("mmoitems:sword/excalibur")); // See the "Blocks" section below for details boolean isPalmLog = blocks.isBlock(block, Key.key("craftengine:default/palm_log")); @@ -93,14 +93,15 @@ Mimic identifies items, blocks, level tracks, classes and resources by [resource where the namespace is the ID of the plugin's implementation: `minecraft:acacia_boat`, `craftengine:default/palm_log`, `auraskills:mining`. The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. -- **Items:** ID without namespace, or with the `mimic` namespace, is searched over all registries in order of priority. +- **Items:** the namespace is required, see [Item IDs](#item-ids). - **Blocks:** the namespace is required, see [Block IDs](#block-ids). - **Level tracks:** the namespace is required, see [Track IDs](#track-ids). - **Classes and class slots:** the namespace is required, see [Class IDs](#class-ids). - **Resources:** the namespace is required, see [Resource IDs](#resource-ids). -> Item IDs with uppercase letters (`minecraft:DIAMOND_SWORD`) or with more than one `:` (`ia:itemsadder:ruby_sword`) are deprecated. -> They still work but log a warning. +> The deprecated `ItemsRegistry` API still searches an item ID without namespace, or with the `mimic` namespace, over all plugins. +> It also accepts item IDs with uppercase letters (`minecraft:DIAMOND_SWORD`), with more than one `:` (`ia:itemsadder:ruby_sword`) +> and MMOItems IDs without item type (`mmoitems:excalibur`), but logs a warning.
Full example @@ -112,7 +113,7 @@ The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. import ru.endlesscode.mimic.Mimic; import ru.endlesscode.mimic.MimicApiLevel; import ru.endlesscode.mimic.classes.Classes; - import ru.endlesscode.mimic.items.BukkitItemsRegistry; + import ru.endlesscode.mimic.items.Items; import ru.endlesscode.mimic.level.Levels; import net.kyori.adventure.key.Key; @@ -128,8 +129,8 @@ The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. return mimic.getClasses(); } - public static BukkitItemsRegistry getItemsRegistry() { - return mimic.getItemsRegistry(); + public static Items getItems() { + return mimic.getItems(); } @Override @@ -166,11 +167,9 @@ The path may contain lowercase letters, digits, `.`, `_`, `-` and `/`. boolean isWarrior = getClasses().hasClass(player, Key.key("fabled:warrior")); - // ItemsRegistry is not related to player so it can be used without provider - BukkitItemsRegistry itemsRegistry = getItemsRegistry(); - ItemStack stick = itemsRegistry.getItem("minecraft:stick"); - boolean isPalmLogInHand = itemsRegistry.isSameItem(player.getInventory().getItemInMainHand(), "craftengine:default/palm_log"); - boolean isPalmLogExists = itemsRegistry.isItemExists("craftengine:default/palm_log"); + Key excalibur = Key.key("mmoitems:sword/excalibur"); + ItemStack sword = getItems().createItem(excalibur, 1, player, null); + boolean isSwordInHand = getItems().isItem(player.getInventory().getItemInMainHand(), excalibur); } } ``` @@ -420,6 +419,81 @@ To make resources of your plugin available, implement [ResourceProvider]: only r `minecraft:health` is changed directly, as a cost and not as damage: no damage or regain events are fired, armor and absorption hearts are ignored, and taking all health kills the player. +### Items + +[Items] gives access to vanilla items and custom items of all supported plugins: +create an item by its ID, get the ID of a stack, check that a stack is a specific item. + +#### Item IDs + +An item ID is a `Key` like `mmoitems:sword/excalibur`: the namespace is the ID of the plugin providing the item, +the path is the item within that plugin. +The namespace is required, there is no search over all plugins. +`Key.key("excalibur")` turns into `minecraft:excalibur`, so validate IDs read from configs: + +```java +Key itemId = Key.key(config.getString("item")); +if (!items.hasItem(itemId)) { + getLogger().warning("Unknown item " + itemId.asString()); +} +``` + +`items.getAllItems()` lists all IDs, for example, for tab completion. +See ID formats of the supported plugins in [Supported Implementations](../mimic-bukkit/README.md#supported-implementations). + +#### Identifying items + +An item belongs to the plugin with the highest priority that recognizes it, and vanilla items belong to `minecraft`. +So a ruby built on a diamond is never `minecraft:diamond`. +Items are compared by ID only: amount, stats, durability and lore of the stack are ignored. + +```java +Key itemId = items.getItemId(stack); // null if no plugin recognizes the item +boolean isExcalibur = items.isItem(stack, Key.key("mmoitems:sword/excalibur")); +// Any diamond, vanilla or a custom item built on it +boolean isDiamond = stack.getType() == Material.DIAMOND; +``` + +#### Creating items + +```java +// A new stack with a single item, or null if the item doesn't exist +ItemStack stick = items.createItem(Key.key("minecraft:stick")); +ItemStack palmLogs = items.createItem(Key.key("craftengine:default/palm_log"), 16); + +// Create the item for the player: some plugins scale items to the player's level. +// The payload is in the format of the plugin providing the item, with an invalid payload the item is not created +ItemStack sword = items.createItem(Key.key("minecraft:diamond_sword"), 1, player, "[damage=10]"); +``` + +The amount is kept within `1` and the maximum stack size of the item. +Each call returns a new stack, so it is safe to change it. + +#### Rules + +- Call `createItem` on the main thread. Other methods may be called from any thread. +- Item IDs may be unknown until their plugins finish loading, and may change when a plugin reloads. + Don't keep created stacks across reloads. +- A payload is passed only to the plugin named by the item ID. Plugins taking no payload ignore it. + +#### Migration from ItemsRegistry + +`ItemsRegistry` API is deprecated but keeps working: every registered items registry is available via [Items], +and `Mimic.getItemsRegistry()` shows items of all item providers. + +| ItemsRegistry | Items | +|--------------------------------------|-----------------------------------------------------| +| `getItem(id, payload, amount)` | `createItem(id, amount, player, payload)` | +| `getItemId(item)` | `getItemId(item)` | +| `isSameItem(item, id)` | `isItem(item, id)` | +| `isItemExists(id)` | `hasItem(id)` | +| `getKnownIds()` | `getAllItems()` | + +- IDs are `Key`s with a required namespace. To keep accepting IDs without a namespace in your configs, + look them up in `getAllItems()` yourself. +- MMOItems IDs include the item type: `mmoitems:sword/excalibur` instead of `mmoitems:excalibur`. +- The payload is a `String`. + ### Blocks [Blocks] gives access to vanilla blocks and custom blocks of all supported plugins: @@ -537,10 +611,55 @@ public class MyClassProvider implements ClassProvider { } ``` -Items registries and block providers receive and return IDs without the namespace, Mimic adds it. +Item providers and block providers receive and return IDs without the namespace, Mimic adds it. Mapping the plugin's own IDs to valid Mimic IDs is up to the implementation, for example `default:palm_log` → `default/palm_log`. Invalid IDs returned by an implementation are ignored with a warning. -See [BlockProvider] for the rules about block IDs, ownership of blocks and threading. +See [ItemProvider] and [BlockProvider] for the rules about IDs, ownership of items and blocks, and threading. + +
+ Item provider example + + ```java + import org.bukkit.entity.Player; + import org.bukkit.inventory.ItemStack; + import org.jetbrains.annotations.NotNull; + import org.jetbrains.annotations.Nullable; + import ru.endlesscode.mimic.items.ItemProvider; + + import java.util.Collection; + + public class MyItemProvider implements ItemProvider { + + @NotNull + @Override + public String getId() { + return "myplugin"; + } + + // Read on every request, so it can change on the plugin reload + @NotNull + @Override + public Collection getAllItems() { + return MyItems.getIds(); + } + + // Return null for items of other plugins and for vanilla items + @Nullable + @Override + public String getItemId(@NotNull ItemStack item) { + return MyItems.getId(item); + } + + // Return a new stack on every call, or null if the item is unknown. + // This provider takes no payload, so it is ignored + @Nullable + @Override + public ItemStack createItem(@NotNull String itemId, int amount, @Nullable Player player, @Nullable String payload) { + return MyItems.create(itemId, amount, player); + } + } + ``` +
Block provider example @@ -696,6 +815,7 @@ public void onLoad() { // Register your implementations and specify minimal required Mimic version for it. mimic.registerClassProvider(new MyClassProvider(), MimicApiLevel.CURRENT, this); + mimic.registerItemProvider(new MyItemProvider(), MimicApiLevel.CURRENT, this); mimic.registerBlockProvider(new MyBlockProvider(), MimicApiLevel.CURRENT, this); mimic.registerLevelProvider(new MyLevelProvider(), MimicApiLevel.CURRENT, this); } @@ -723,6 +843,8 @@ IDs of the default implementations (`mimic`, `minecraft`, `permissions`) are res [BukkitClassSystem]: src/main/kotlin/classes/BukkitClassSystem.kt [BukkitPlayerInventory.Provider]: src/main/kotlin/inventory/BukkitPlayerInventory.kt [BukkitItemsRegistry]: src/main/kotlin/items/BukkitItemsRegistry.kt +[Items]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.items/-items/index.html +[ItemProvider]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.items/-item-provider/index.html [Blocks]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.blocks/-blocks/index.html [BlockProvider]: https://endlesscodegroup.github.io/Mimic/mimic-bukkit-api/ru.endlesscode.mimic.blocks/-block-provider/index.html diff --git a/mimic-bukkit/README.md b/mimic-bukkit/README.md index 17faf834..fca1492f 100644 --- a/mimic-bukkit/README.md +++ b/mimic-bukkit/README.md @@ -30,7 +30,7 @@ You can configure in `config.yml` what APIs implementations should be used, or u | `/mimic classes` | Manage player's classes | | `/mimic resources` | Manage player's mana and similar | | `/mimic inventory` | Player's inventory info | -| `/mimic items` | Deal with items | +| `/mimic items` | Give, find and compare items | | `/mimic blocks` | Deal with blocks | Commands without arguments show info and list available subcommands: click a subcommand to use it, hover to see usage. @@ -74,17 +74,18 @@ You can find code of all built-in implementations [here](src/main/kotlin/impl). - **[Minecraft][minecraft-inv]** _(Default)_ - **[RPGInventory]** -### [Items Registries][BukkitItemsRegistry] +### [Item Providers][ItemProvider] -#### [MimicItemsRegistry] +Items of all providers are available via [Items], with the provider ID as a namespace of item IDs. +The namespace is required. +An item belongs to the provider with the highest priority that recognizes it, vanilla items belong to `minecraft`. -Items registry combining all others items registries. -It uses registry ID as a namespace for items IDs.\ -For example: `acacia_boat -> minecraft:acacia_boat`. +> The deprecated [ItemsRegistry][MimicItemsRegistry] API also accepts item ID without a namespace or with the `mimic` namespace +> and searches it over all providers. Plugins using this API accept MMOItems IDs without item type too, if only one type has the item. -> If you use item ID without a namespace or with the `mimic` namespace, it will search over all registries. +Providers marked with _(deprecated API)_ are provided by the plugin itself via the deprecated [ItemsRegistry][BukkitItemsRegistry] API. -#### [Minecraft][MinecraftItemsRegistry] +#### [Minecraft][MinecraftItemProvider] **ID Format:** `minecraft:[id]`\ **Payload:** [Item components][item-components] in the format of `/give` command, for example `[damage=10,unbreakable={}]`.\ @@ -102,20 +103,21 @@ Alternatively, [ItemMetaPayload] in HOCON format with MiniMessage support for na #### [MMOItems] -**ID Format:** `mmoitems:[id]`\ -**Payload:** *Not supported* +**ID Format:** `mmoitems:[type]/[id]`, for example `mmoitems:sword/excalibur`\ +**Payload:** *Not supported*\ +An item given to a player is built by MMOItems for this player. -#### [ProRPGItems] +#### [ProRPGItems] _(deprecated API)_ **ID Format:** `prorpgitems:[type]/[id]`\ **Payload:** *Not supported* -#### [RPGInventory] +#### [RPGInventory] _(deprecated API)_ **ID Format:** `rpginventory:[id]`\ **Payload:** *Not supported* -#### [ItemsAdder] +#### [ItemsAdder] _(deprecated API)_ **ID Format:** `ia:[id]`\ **Payload:** *Not supported* @@ -165,5 +167,7 @@ A block belongs to the provider with the highest priority that recognizes it, va [Blocks]: ../mimic-bukkit-api/src/main/kotlin/blocks/Blocks.kt [MinecraftBlockProvider]: src/main/kotlin/impl/vanilla/MinecraftBlockProvider.kt [MimicItemsRegistry]: src/main/kotlin/impl/mimic/MimicItemsRegistry.kt -[MinecraftItemsRegistry]: src/main/kotlin/impl/vanilla/MinecraftItemsRegistry.kt +[ItemProvider]: ../mimic-bukkit-api/src/main/kotlin/items/ItemProvider.kt +[Items]: ../mimic-bukkit-api/src/main/kotlin/items/Items.kt +[MinecraftItemProvider]: src/main/kotlin/impl/vanilla/MinecraftItemProvider.kt [ItemMetaPayload]: src/main/kotlin/impl/vanilla/ItemMetaPayload.kt