মিরাজু ইসলাম

Create a Spigot plugin for Minecraft version 1.26 named Item Adder. It must include a command '/itemadder menu' that opens a GUI for registered custom items with diverse model formats, including block and item models, and assigned CustomModelData. The plugin should have a dedicated folder where these models can be uploaded and automatically loaded upon server start or restart. Include logic to generate separate texture or resource pack files for both Java and Bedrock editions via GeyserMC

Kodari AI
KodariOct 24 at 7:29 pm 2
ItemAdderManager
ItemAdderManager is a Spigot plugin for Minecraft 1.26 that provides a comprehensive custom item management system. It features a '/itemadder menu' command opening a GUI displaying registered custom items with diverse model formats including block and item models with assigned CustomModelData values. The plugin maintains a dedicated models folder where users can upload custom model files that are automatically loaded during server startup or restart. It includes intelligent logic to generate separate texture and resource pack files compatible with both Java and Bedrock editions through GeyserMC integration, ensuring cross-platform item visibility and functionality.

Plan:

  • Add the Gradle project and Spigot plugin metadata.

  • Implement custom item loading, model/texture registration, and /itemadder menu.

  • Generate Java and Bedrock resource-pack archives and Geyser item mappings on startup.

Created the ItemAdder Spigot plugin with /itemadder menu. Players can browse registered items and click one to receive it.

Add each item to plugins/ItemAdder/models/ using three matching filenames, for example crystal_sword.yml and crystal_sword.png; a matching .json model is optional. The YAML specifies base-material, display-name, custom-model-data, and model-type (item or block). Without a JSON model, the plugin generates a basic one from the PNG texture.

On startup, it generates plugins/ItemAdder/generated/ItemAdder-Java.zip, ItemAdder-Bedrock.mcpack, and Geyser mappings. If plugins/Geyser-Spigot/ exists, it copies the pack and mappings into Geyser’s pack and custom-mappings folders. Restart after adding or changing item files so they reload.

Geyser’s Bedrock pack uses the PNG as the item icon; Geyser does not convert Java JSON model geometry into Bedrock geometry.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle.kts
manifest.kod
settings.gradle.kts
Code
13 430
src/main/kotlin/com/kodari/itemadder/PackGenerator.kt
package com.kodari.itemadder

import org.bukkit.Material
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.Comparator
import java.util.Locale
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

class PackGenerator(private val plugin: ItemAdderPlugin) {
    fun generate(items: List<ItemDefinition>) {
        val output = plugin.dataFolder.toPath().resolve("generated")
        val javaRoot = output.resolve("java-pack")
        val bedrockRoot = output.resolve("bedrock-pack")
        resetDirectory(javaRoot)
        resetDirectory(bedrockRoot)

        writeJavaPack(javaRoot, items)
        writeBedrockPack(bedrockRoot, items)

        val javaArchive = output.resolve("ItemAdder-Java.zip")
        val bedrockArchive = output.resolve("ItemAdder-Bedrock.mcpack")
        zipDirectory(javaRoot, javaArchive)
        zipDirectory(bedrockRoot, bedrockArchive)

        val geyserFolder = plugin.dataFolder.parentFile.toPath().resolve("Geyser-Spigot")
        if (Files.isDirectory(geyserFolder)) {
            val packsFolder = geyserFolder.resolve("packs")
            val mappingsFolder = geyserFolder.resolve("custom_mappings")
            Files.createDirectories(packsFolder)
            Files.createDirectories(mappingsFolder)
            Files.copy(bedrockArchive, packsFolder.resolve("ItemAdder.mcpack"), StandardCopyOption.REPLACE_EXISTING)
            Files.copy(
                output.resolve("geyser-mappings.json"),
                mappingsFolder.resolve("ItemAdder.json"),
                StandardCopyOption.REPLACE_EXISTING
            )
        }

        plugin.logger.info("Generated Java and Bedrock packs for ${items.size} custom item(s).")
    }

    private fun writeJavaPack(root: Path, items: List<ItemDefinition>) {
        writeJson(
            root.resolve("pack.mcmeta"),
            """{"pack":{"pack_format":${plugin.config.getInt("java-pack-format", 46)},"description":"${escapeJson(plugin.config.getString("java-pack-description") ?: "ItemAdder generated custom items")}"}}"""
        )

        items.forEach { definition ->
            val textureName = "itemadder:${definition.modelType.textureDirectory}/${definition.id}"
            val modelResourcePath = "itemadder:${definition.modelType.modelDirectory}/${definition.id}"
            val modelPath = root.resolve("assets/itemadder/models/${definition.modelType.modelDirectory}/${definition.id}.json")
            Files.createDirectories(modelPath.parent)
            if (definition.modelFile.isFile) {
                Files.copy(definition.modelFile.toPath(), modelPath, StandardCopyOption.REPLACE_EXISTING)
            } else {
                val modelJson = if (definition.modelType == ModelType.BLOCK) {
                    """{"parent":"minecraft:block/cube_all","textures":{"all":"$textureName"}}"""
                } else {
                    """{"parent":"minecraft:item/generated","textures":{"layer0":"$textureName"}}"""
                }
                writeJson(modelPath, modelJson)
            }

            val texturePath = root.resolve(
                "assets/itemadder/textures/${definition.modelType.textureDirectory}/${definition.id}.png"
            )
            Files.createDirectories(texturePath.parent)
            Files.copy(definition.textureFile.toPath(), texturePath, StandardCopyOption.REPLACE_EXISTING)
        }

        items.groupBy { it.material.name.lowercase(Locale.ROOT) }.forEach { (materialName, definitions) ->
            val blockMaterial = definitions.first().material.isBlock
            val modelParent = when {
                blockMaterial -> "minecraft:block/cube_all"
                isHandheld(definitions.first().material) -> "minecraft:item/handheld"
                else -> "minecraft:item/generated"
            }
            val textureKey = if (blockMaterial) "all" else "layer0"
            val textureValue = if (blockMaterial) "minecraft:block/$materialName" else "minecraft:item/$materialName"
            val overrides = definitions.joinToString(",") { definition ->
                """{"predicate":{"custom_model_data":${definition.customModelData}},"model":"itemadder:${definition.modelType.modelDirectory}/${definition.id}"}"""
            }
            val modelJson = """{"parent":"$modelParent","textures":{"$textureKey":"$textureValue"},"overrides":[$overrides]}"""
            writeJson(root.resolve("assets/minecraft/models/item/$materialName.json"), modelJson)
        }
    }

    private fun writeBedrockPack(root: Path, items: List<ItemDefinition>) {
        writeJson(
            root.resolve("manifest.json"),
            """{"format_version":2,"header":{"name":"ItemAdder","description":"Generated custom items","uuid":"a36d9b9a-9045-4fb1-9bc9-a44d8cc6c3a1","version":[1,0,0],"min_engine_version":[1,20,0]},"modules":[{"type":"resources","uuid":"d59ac9f2-81b0-411f-9b29-1ab234bccde8","version":[1,0,0]}]}"""
        )

        val textureData = items.joinToString(",") { definition ->
            val icon = bedrockIcon(definition.id)
            """"$icon":{"textures":"textures/items/${definition.id}"}"""
        }
        writeJson(
            root.resolve("textures/item_texture.json"),
            """{"resource_pack_name":"ItemAdder","texture_name":"atlas.items","texture_data":{$textureData}}"""
        )

        items.forEach { definition ->
            val texturePath = root.resolve("textures/items/${definition.id}.png")
            Files.createDirectories(texturePath.parent)
            Files.copy(definition.textureFile.toPath(), texturePath, StandardCopyOption.REPLACE_EXISTING)
        }

        val mappingEntries = items.groupBy { "minecraft:${it.material.name.lowercase(Locale.ROOT)}" }
            .entries
            .joinToString(",") { (javaItem, definitions) ->
                val entries = definitions.joinToString(",") { definition ->
                    """{"type":"legacy","custom_model_data":${definition.customModelData},"bedrock_identifier":"itemadder:${definition.id}","display_name":"${escapeJson(definition.displayName)}","bedrock_options":{"icon":"${bedrockIcon(definition.id)}"}}"""
                }
                """"${escapeJson(javaItem)}":[$entries]"""
            }
        writeJson(
            plugin.dataFolder.toPath().resolve("generated/geyser-mappings.json"),
            """{"format_version":2,"items":{$mappingEntries}}"""
        )
    }

    private fun isHandheld(material: Material): Boolean {
        val name = material.name.lowercase(Locale.ROOT)
        return listOf("_sword", "_pickaxe", "_axe", "_shovel", "_hoe", "_rod", "_trident", "_bow", "_crossbow")
            .any(name::endsWith)
    }

    private fun bedrockIcon(id: String): String = "itemadder.${id.replace('-', '_').replace('.', '_')}"

    private fun writeJson(path: Path, content: String) {
        Files.createDirectories(path.parent)
        Files.writeString(path, content, StandardCharsets.UTF_8)
    }

    private fun escapeJson(value: String): String = buildString {
        value.forEach { character ->
            when (character) {
                '\\' -> append("\\\\")
                '"' -> append("\\\"")
                '\n' -> append("\\n")
                '\r' -> append("\\r")
                '\t' -> append("\\t")
                else -> if (character.code < 0x20) append("\\u%04x".format(character.code)) else append(character)
            }
        }
    }

    private fun resetDirectory(path: Path) {
        if (Files.exists(path)) {
            Files.walk(path).use { paths ->
                paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) }
            }
        }
        Files.createDirectories(path)
    }

    private fun zipDirectory(source: Path, destination: Path) {
        Files.createDirectories(destination.parent)
        ZipOutputStream(Files.newOutputStream(destination)).use { zip ->
            Files.walk(source).use { paths ->
                paths.filter { Files.isRegularFile(it) }.forEach { file ->
                    val entryName = source.relativize(file).toString().replace(File.separatorChar, '/')
                    zip.putNextEntry(ZipEntry(entryName))
                    Files.copy(file, zip)
                    zip.closeEntry()
                }
            }
        }
    }
}