From 833c36f8a662a32aa9d124a81028cecc5f6c4bdb Mon Sep 17 00:00:00 2001 From: QiuYe Date: Fri, 20 Nov 2026 15:57:19 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E5=AF=BC=E5=85=A5=20Minecraft=2026.1.2=20?= =?UTF-8?q?=E5=9F=BA=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 基于 26.1 分支的 fe1a030355b6761b88351cda6abbbab7f9f33e23 源码快照。 --- .devcontainer/devcontainer.json | 47 + .gitattributes | 20 + .github/ISSUE_TEMPLATE/000-bug-report.yml | 113 ++ .../ISSUE_TEMPLATE/001-feature-request.yml | 29 + .github/ISSUE_TEMPLATE/config.yml | 5 + .github/actions/build_setup/action.yml | 32 + .github/json/config-latest.json | 35 + .github/json/config.json | 45 + .github/labeler.yml | 3 + .github/pull_request_template.md | 26 + .github/release.yml | 26 + .github/workflows/auto-build.yml | 71 + .github/workflows/build-on-push.yml | 54 + .github/workflows/clean.yml | 20 + .github/workflows/format-java.yml | 41 + .github/workflows/labeler.yml | 12 + .github/workflows/manage-issue-labels.yml | 23 + .github/workflows/manage-pr-labels.yml | 43 + .github/workflows/publish-on-release.yml | 44 + .github/workflows/publish.yml | 180 +++ .github/workflows/sync.yml | 23 + .github/workflows/test-on-push.yml | 62 + .github/workflows/update-gradle-cache.yml | 28 + .gitignore | 27 + CHANGELOG.md | 19 + CODEOWNERS | 7 + CONTRIBUTING.md | 42 + LICENSE | 373 +++++ README.md | 170 +++ build.gradle | 129 ++ dependencies.gradle | 17 + docs/advanced.md | 339 +++++ docs/architecture.md | 90 ++ docs/builders.md | 331 +++++ docs/entries.md | 262 ++++ docs/getting-started.md | 101 ++ docs/index.md | 45 + docs/providers.md | 272 ++++ gradle.properties | 15 + gradle/forge.versions.toml | 13 + gradle/libs.versions.toml | 25 + gradle/scripts/jars.gradle | 40 + gradle/scripts/moddevgradle.gradle | 138 ++ gradle/scripts/publishing.gradle | 21 + gradle/scripts/repositories.gradle | 35 + gradle/scripts/resources.gradle | 53 + gradle/scripts/spotless.gradle | 44 + gradle/spotless/spotless.eclipseformat.xml | 400 +++++ gradle/spotless/spotless.importorder | 8 + gradle/spotless/spotless.ktlint | 10 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 49154 bytes gradle/wrapper/gradle-wrapper.properties | 9 + gradlew | 248 ++++ gradlew.bat | 112 ++ lombok.config | 16 + settings.gradle | 28 + shell.nix | 20 + .../registrate/AbstractRegistrate.java | 1320 +++++++++++++++++ .../com/modularmc/registrate/Registrate.java | 43 + .../modularmc/registrate/RegistrateLib.java | 27 + .../registrate/builders/BlockBuilder.java | 392 +++++ .../builders/BlockEntityBuilder.java | 166 +++ .../registrate/builders/EntityBuilder.java | 294 ++++ .../registrate/builders/FluidBuilder.java | 660 +++++++++ .../registrate/builders/ItemBuilder.java | 357 +++++ .../registrate/builders/MenuBuilder.java | 80 + .../builders/base/AbstractBuilder.java | 183 +++ .../registrate/builders/base/Builder.java | 282 ++++ .../builders/base/BuilderCallback.java | 62 + .../builders/base/NoConfigBuilder.java | 22 + .../builders/base/package-info.java | 5 + .../registrate/builders/package-info.java | 10 + .../internal/RegistrationTracker.java | 243 +++ .../datagen/RegistrateDatagenBootstrap.java | 22 + .../internal/event/OneTimeEventReceiver.java | 111 ++ .../internal/event/package-info.java | 6 + .../lifecycle/RegistrateLifecycle.java | 86 ++ .../internal/lifecycle/package-info.java | 6 + .../registrate/internal/package-info.java | 9 + .../internal/util/DebugMarkers.java | 19 + .../internal/util/RegistrateDistExecutor.java | 17 + .../internal/util/RegistrateLogger.java | 40 + .../internal/util/package-info.java | 5 + .../modularmc/registrate/package-info.java | 10 + .../registrate/providers/DataGenContext.java | 47 + .../RegistrateAdvancementProvider.java | 122 ++ .../providers/RegistrateDataMapProvider.java | 48 + .../providers/RegistrateDatapackProvider.java | 30 + .../providers/RegistrateGenericProvider.java | 72 + .../providers/RegistrateItemTagsProvider.java | 50 + .../providers/RegistrateLangProvider.java | 204 +++ .../providers/RegistrateTagsProvider.java | 139 ++ .../core/DataProviderInitializer.java | 57 + .../providers/core/GeneratorType.java | 3 + .../providers/core/ProviderType.java | 153 ++ .../core/RegistrateDataProvider.java | 121 ++ .../core/RegistrateLookupFillerProvider.java | 10 + .../providers/core/RegistrateProvider.java | 9 + .../core/RegistrateProviderDelegate.java | 13 + .../providers/core/package-info.java | 6 + .../RegistrateBlockModelGenerator.java | 526 +++++++ .../RegistrateItemModelGenerator.java | 128 ++ .../RegistrateLegacyBlockModelBuilder.java | 126 ++ .../generators/RegistrateModelProvider.java | 44 + .../generators/RegistrateRecipeProvider.java | 714 +++++++++ .../generators/RegistrateRecipeRunner.java | 45 + .../providers/generators/package-info.java | 9 + .../loot/RegistrateBlockLootTables.java | 303 ++++ .../loot/RegistrateEntityLootTables.java | 86 ++ .../loot/RegistrateLootTableProvider.java | 129 ++ .../providers/loot/RegistrateLootTables.java | 11 + .../providers/loot/package-info.java | 9 + .../registrate/providers/package-info.java | 10 + .../util/CreativeModeTabModifier.java | 53 + .../registrate/util/DataIngredient.java | 93 ++ .../util/entry/BlockEntityEntry.java | 74 + .../registrate/util/entry/BlockEntry.java | 26 + .../registrate/util/entry/EntityEntry.java | 30 + .../registrate/util/entry/FluidEntry.java | 53 + .../registrate/util/entry/ItemEntry.java | 17 + .../util/entry/ItemProviderEntry.java | 45 + .../util/entry/LazyRegistryEntry.java | 25 + .../registrate/util/entry/MenuEntry.java | 46 + .../registrate/util/entry/RegistryEntry.java | 81 + .../registrate/util/entry/package-info.java | 9 + .../nullness/FieldsAreNonnullByDefault.java | 25 + .../util/nullness/NonNullBiConsumer.java | 14 + .../util/nullness/NonNullBiFunction.java | 10 + .../util/nullness/NonNullConsumer.java | 23 + .../util/nullness/NonNullFunction.java | 16 + .../util/nullness/NonNullSupplier.java | 33 + .../util/nullness/NonNullUnaryOperator.java | 16 + .../registrate/util/nullness/NonnullType.java | 18 + .../util/nullness/NullableSupplier.java | 32 + .../util/nullness/NullableType.java | 18 + .../util/nullness/package-info.java | 9 + .../registrate/util/package-info.java | 11 + .../resources/META-INF/accesstransformer.cfg | 0 .../resources/META-INF/enum_extensions.json | 3 + .../templates/META-INF/neoforge.mods.toml | 35 + .../testmod/blockstates/magic_item_model.json | 7 + .../assets/testmod/blockstates/testblock.json | 7 + .../testmod/blockstates/testbucketfluid.json | 7 + .../assets/testmod/blockstates/testfluid.json | 7 + .../testmod/items/magic_item_model.json | 6 + .../assets/testmod/items/testblock.json | 12 + .../testmod/items/testbucketfluid_bucket.json | 12 + .../testmod/items/testentity_spawn_egg.json | 6 + .../assets/testmod/items/testitem.json | 6 + .../resources/assets/testmod/lang/en_ud.json | 23 + .../resources/assets/testmod/lang/en_us.json | 23 + .../block/subfolder/magic_item_model.json | 6 + .../testmod/models/block/testbucketfluid.json | 5 + .../testmod/models/block/testfluid.json | 5 + .../models/item/testentity_spawn_egg.json | 6 + .../minecraft/tags/block/dragon_immune.json | 5 + .../minecraft/tags/block/supports_bamboo.json | 5 + .../minecraft/tags/block/wither_immune.json | 5 + .../minecraft/tags/entity_type/raiders.json | 5 + .../data/minecraft/tags/item/beds.json | 5 + ...diamond_block_from_testblock_campfire.json | 32 + ...diamond_block_from_testblock_smelting.json | 32 + .../diamond_block_from_testblock_smoking.json | 32 + .../advancement/recipes/misc/testblock.json | 32 + .../data/testmod/advancement/root.json | 32 + .../testmod/dimension/test_dimension.json | 11 + .../dimension_type/test_dimension_type.json | 55 + .../loot_table/blocks/magic_item_model.json | 21 + .../testmod/loot_table/blocks/testblock.json | 21 + .../loot_table/entities/testentity.json | 36 + .../testmod/loot_table/entities/testitem.json | 4 + ...diamond_block_from_testblock_campfire.json | 10 + ...diamond_block_from_testblock_smelting.json | 10 + .../diamond_block_from_testblock_smoking.json | 10 + .../data/testmod/recipe/testblock.json | 16 + .../test/gametests/CustomItemTests.java | 24 + .../gametests/RegistrationRuntimeTests.java | 45 + .../test/gametests/package-info.java | 5 + .../registrate/test/meta/MethodGenerator.java | 103 ++ .../test/meta/ProtectedMethodScraper.java | 127 ++ .../test/meta/UpdateBlockLootTables.java | 12 + .../test/meta/UpdateEntityLootTables.java | 13 + .../test/meta/UpdateRecipeProvider.java | 13 + .../registrate/test/meta/package-info.java | 8 + .../registrate/test/mod/TestMod.java | 481 ++++++ .../registrate/test/mod/package-info.java | 5 + .../resources/META-INF/neoforge.mods.toml | 45 + .../textures/item/testentity_spawn_egg.png | Bin 0 -> 220 bytes .../textures/item/testfluid_bucket.png | Bin 0 -> 634 bytes src/test/resources/pack.mcmeta | 9 + 190 files changed, 14364 insertions(+) create mode 100644 .devcontainer/devcontainer.json create mode 100644 .gitattributes create mode 100644 .github/ISSUE_TEMPLATE/000-bug-report.yml create mode 100644 .github/ISSUE_TEMPLATE/001-feature-request.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/actions/build_setup/action.yml create mode 100644 .github/json/config-latest.json create mode 100644 .github/json/config.json create mode 100644 .github/labeler.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/release.yml create mode 100644 .github/workflows/auto-build.yml create mode 100644 .github/workflows/build-on-push.yml create mode 100644 .github/workflows/clean.yml create mode 100644 .github/workflows/format-java.yml create mode 100644 .github/workflows/labeler.yml create mode 100644 .github/workflows/manage-issue-labels.yml create mode 100644 .github/workflows/manage-pr-labels.yml create mode 100644 .github/workflows/publish-on-release.yml create mode 100644 .github/workflows/publish.yml create mode 100644 .github/workflows/sync.yml create mode 100644 .github/workflows/test-on-push.yml create mode 100644 .github/workflows/update-gradle-cache.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CODEOWNERS create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 build.gradle create mode 100644 dependencies.gradle create mode 100644 docs/advanced.md create mode 100644 docs/architecture.md create mode 100644 docs/builders.md create mode 100644 docs/entries.md create mode 100644 docs/getting-started.md create mode 100644 docs/index.md create mode 100644 docs/providers.md create mode 100644 gradle.properties create mode 100644 gradle/forge.versions.toml create mode 100644 gradle/libs.versions.toml create mode 100644 gradle/scripts/jars.gradle create mode 100644 gradle/scripts/moddevgradle.gradle create mode 100644 gradle/scripts/publishing.gradle create mode 100644 gradle/scripts/repositories.gradle create mode 100644 gradle/scripts/resources.gradle create mode 100644 gradle/scripts/spotless.gradle create mode 100644 gradle/spotless/spotless.eclipseformat.xml create mode 100644 gradle/spotless/spotless.importorder create mode 100644 gradle/spotless/spotless.ktlint create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 lombok.config create mode 100644 settings.gradle create mode 100644 shell.nix create mode 100644 src/main/java/com/modularmc/registrate/AbstractRegistrate.java create mode 100644 src/main/java/com/modularmc/registrate/Registrate.java create mode 100644 src/main/java/com/modularmc/registrate/RegistrateLib.java create mode 100644 src/main/java/com/modularmc/registrate/builders/BlockBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/EntityBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/FluidBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/ItemBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/MenuBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/Builder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/builders/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java create mode 100644 src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java create mode 100644 src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java create mode 100644 src/main/java/com/modularmc/registrate/internal/event/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java create mode 100644 src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/internal/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java create mode 100644 src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java create mode 100644 src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java create mode 100644 src/main/java/com/modularmc/registrate/internal/util/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/providers/DataGenContext.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/ProviderType.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/providers/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java create mode 100644 src/main/java/com/modularmc/registrate/util/DataIngredient.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NullableType.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/package-info.java create mode 100644 src/main/java/com/modularmc/registrate/util/package-info.java create mode 100644 src/main/resources/META-INF/accesstransformer.cfg create mode 100644 src/main/resources/META-INF/enum_extensions.json create mode 100644 src/main/templates/META-INF/neoforge.mods.toml create mode 100644 src/test/generated/resources/assets/testmod/blockstates/magic_item_model.json create mode 100644 src/test/generated/resources/assets/testmod/blockstates/testblock.json create mode 100644 src/test/generated/resources/assets/testmod/blockstates/testbucketfluid.json create mode 100644 src/test/generated/resources/assets/testmod/blockstates/testfluid.json create mode 100644 src/test/generated/resources/assets/testmod/items/magic_item_model.json create mode 100644 src/test/generated/resources/assets/testmod/items/testblock.json create mode 100644 src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json create mode 100644 src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json create mode 100644 src/test/generated/resources/assets/testmod/items/testitem.json create mode 100644 src/test/generated/resources/assets/testmod/lang/en_ud.json create mode 100644 src/test/generated/resources/assets/testmod/lang/en_us.json create mode 100644 src/test/generated/resources/assets/testmod/models/block/subfolder/magic_item_model.json create mode 100644 src/test/generated/resources/assets/testmod/models/block/testbucketfluid.json create mode 100644 src/test/generated/resources/assets/testmod/models/block/testfluid.json create mode 100644 src/test/generated/resources/assets/testmod/models/item/testentity_spawn_egg.json create mode 100644 src/test/generated/resources/data/minecraft/tags/block/dragon_immune.json create mode 100644 src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json create mode 100644 src/test/generated/resources/data/minecraft/tags/block/wither_immune.json create mode 100644 src/test/generated/resources/data/minecraft/tags/entity_type/raiders.json create mode 100644 src/test/generated/resources/data/minecraft/tags/item/beds.json create mode 100644 src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_campfire.json create mode 100644 src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smelting.json create mode 100644 src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smoking.json create mode 100644 src/test/generated/resources/data/testmod/advancement/recipes/misc/testblock.json create mode 100644 src/test/generated/resources/data/testmod/advancement/root.json create mode 100644 src/test/generated/resources/data/testmod/dimension/test_dimension.json create mode 100644 src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json create mode 100644 src/test/generated/resources/data/testmod/loot_table/blocks/magic_item_model.json create mode 100644 src/test/generated/resources/data/testmod/loot_table/blocks/testblock.json create mode 100644 src/test/generated/resources/data/testmod/loot_table/entities/testentity.json create mode 100644 src/test/generated/resources/data/testmod/loot_table/entities/testitem.json create mode 100644 src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json create mode 100644 src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json create mode 100644 src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json create mode 100644 src/test/generated/resources/data/testmod/recipe/testblock.json create mode 100644 src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java create mode 100644 src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java create mode 100644 src/test/java/com/modularmc/registrate/test/gametests/package-info.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/package-info.java create mode 100644 src/test/java/com/modularmc/registrate/test/mod/TestMod.java create mode 100644 src/test/java/com/modularmc/registrate/test/mod/package-info.java create mode 100644 src/test/resources/META-INF/neoforge.mods.toml create mode 100644 src/test/resources/assets/testmod/textures/item/testentity_spawn_egg.png create mode 100644 src/test/resources/assets/testmod/textures/item/testfluid_bucket.png create mode 100644 src/test/resources/pack.mcmeta diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..44440af --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,47 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/python +{ + "name": "Docs Codespace", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/base:ubuntu", + "workspaceMount": "source=${localWorkspaceFolder},target=/modern,type=bind", + "workspaceFolder": "/modern/docs", + "features": { + "ghcr.io/devcontainers/features/python:1": { + "installTools": true, + "version": "3.11" + } + }, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + "forwardPorts": [8000], + + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": "pip3 install --user -r requirements.txt", + + // Configure tool-specific properties. + "customizations": { + "vscode": { + "settings": { + "yaml.schemas": { + "https://squidfunk.github.io/mkdocs-material/schema.json": "mkdocs.yml" + }, + "yaml.customTags": [ + "!ENV scalar", + "!ENV sequence", + "tag:yaml.org,2002:python/name:material.extensions.emoji.to_svg", + "tag:yaml.org,2002:python/name:material.extensions.emoji.twemoji", + "tag:yaml.org,2002:python/name:pymdownx.superfences.fence_code_format" + ], + "git.openRepositoryInParentFolders": "always", + "git.autofetch": "all", + "git.autoStash": true + }, + "extensions": ["redhat.vscode-yaml"] + } + } + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} + diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..67572fd --- /dev/null +++ b/.gitattributes @@ -0,0 +1,20 @@ +# Auto detect text files and normalize to LF +* text=auto eol=lf + +# Ensure these are always LF +*.java text eol=lf +*.kt text eol=lf +*.json text eol=lf +*.gradle text eol=lf +*.properties text eol=lf +*.xml text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.md text eol=lf +*.txt text eol=lf + +# Binary files +*.png binary +*.jpg binary +*.jar binary +*.ogg binary diff --git a/.github/ISSUE_TEMPLATE/000-bug-report.yml b/.github/ISSUE_TEMPLATE/000-bug-report.yml new file mode 100644 index 0000000..126b7a7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/000-bug-report.yml @@ -0,0 +1,113 @@ +name: Bug Report / 错误报告 +description: Report a bug where something is not working as expected. / 报告某物未按预期工作的错误。 +labels: [ "type: bug" ] +body: + - type: checkboxes + id: existing-issue + attributes: + label: Checked for existing issues / 已检查现有问题 + description: You have checked for existing reports of this issue, open or closed. / 您已检查过此问题的现有报告(开放或已关闭)。 + options: + - label: "I have checked for existing issues, and have found none. / 我已检查现有问题,未发现相同报告。" + required: true + - type: checkboxes + id: tried-latest + attributes: + label: Tested latest version / 已测试最新版本 + description: You have checked that this issue occurs on the latest version of Mekanism Extras. / 您已确认此问题在 Mekanism Extras 的最新版本中出现。 + options: + - label: "I have checked that this occurs on the latest version. / 我已确认此问题在最新版本中出现。" + required: true + - type: input + id: mekanismextras-version + attributes: + label: SyncedData Version / SyncedData 版本 + description: The version of SyncedData you were using when this bug was encountered. If you do not know where to find this, look for the mod jar file in the mods folder, or in the mods viewer in-game. / 遇到此错误时使用的 SyncedData 版本。如果不知道如何查找,请查看 mods 文件夹中的 mod jar 文件,或游戏内的模组查看器。 + placeholder: "Example: v2.3.4 / 例如:v2.3.4" + validations: + required: true + - type: dropdown + id: mc-version + attributes: + label: Minecraft Version / Minecraft 版本 + description: The version of Minecraft you were using when this bug was encountered. If you do not know where to find this, it is in the bottom left of the main menu. Any version not listed is not supported. / 遇到此错误时使用的 Minecraft 版本。如果不知道如何查找,它位于主菜单的左下角。未列出的任何版本均不受支持。 + options: + - "26.1 NeoForge" + validations: + required: true + - type: dropdown + id: recipe-viewer + attributes: + label: Recipe Viewer Installed + description: The recipe viewer installed. + options: + - "JEI" + - "REI" + - "EMI" + validations: + required: false + - type: dropdown + id: environment + attributes: + label: Environment / 环境 + description: How you were playing on the world. Hybrid servers are unsupported. / 您在世界中游玩的方式。不支持混合服务器。 + options: + - "Singleplayer / 单人游戏" + - "Multiplayer - Open to LAN / 多人游戏 - 开放局域网" + - "Multiplayer - Dedicated Server / 多人游戏 - 专用服务器" + validations: + required: true + - type: dropdown + id: cross-mod + attributes: + label: Cross-Mod Interaction / 跨模组交互 + description: Does this bug occur because of another mod installed alongside Mekanism Extras? / 此错误是否由于与 Mekanism Extras 同时安装的其他模组引起? + options: + - "Yes / 是" + - "No / 否" + - "Unsure / 不确定" + validations: + required: true + - type: textarea + id: other-mods + attributes: + label: Other Installed Mods / 其他已安装模组 + description: Enter the name of the modpack you're playing, or list all mods you have installed here. / 输入您正在游玩的整合包名称,或在此处列出所有已安装的模组。 + placeholder: "Example: Cosmic Frontiers, Monifactory, Embeddium, NuclearCraft Neoteric, AE2,... / 例如:Cosmic Frontiers, Monifactory, Embeddium, NuclearCraft Neoteric, AE2,..." + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected Behavior / 预期行为 + description: What you expected to happen. Attach screenshots here as necessary. / 您期望发生什么。必要时在此处附加截图。 + placeholder: "Example: Expected to produce X by consuming Y. / 例如:期望通过消耗 Y 来生产 X。" + validations: + required: true + - type: textarea + id: result + attributes: + label: Actual Behavior / 实际行为 + description: What happened despite your expectations. Attach screenshots here as necessary. / 与您预期不符的实际发生情况。必要时在此处附加截图。 + placeholder: "Example: Produced one X but Y was not consumed. / 例如:生产了一个 X 但 Y 未被消耗。" + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Steps to Reproduce / 重现步骤 + description: How to reproduce the bug. / 如何重现此错误。 + placeholder: "Example: 1) I did X... / 例如:1) 我做了 X..." + validations: + required: true + - type: textarea + id: additional-info + attributes: + label: Additional Information / 附加信息 + description: Any additional information you wish to provide. Please add anything which did not fit into the other sections here. / 您希望提供的任何附加信息。请将不适合其他部分的内容添加在此处。 + placeholder: "Example: This is likely caused by X because... / 例如:这很可能由 X 引起,因为..." + validations: + required: false + - type: markdown + attributes: + value: Thank you for taking the time to fill out this bug report. / 感谢您抽出时间填写此错误报告。 \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/001-feature-request.yml b/.github/ISSUE_TEMPLATE/001-feature-request.yml new file mode 100644 index 0000000..883702c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/001-feature-request.yml @@ -0,0 +1,29 @@ +name: Feature Request / 功能请求 +description: Request a new feature. / 请求新功能。 +labels: [ "type: feature" ] +body: + - type: input + id: cross-mod + attributes: + label: Cross-mod Integration / 跨模组集成 + description: "Does this feature involve integration with another mod? If so specify the mod(s). Otherwise, leave this blank. / 此功能是否涉及与其他模组的集成?如果是,请指定模组名称。否则留空。" + placeholder: "Example: Create Mod / 例如:Create Mod" + - type: dropdown + id: mc-version + attributes: + label: Minecraft Version / Minecraft 版本 + description: The version of Minecraft you wish this feature was added for. / 您希望此功能添加到的 Minecraft 版本。 + options: + - "Both" + - "26.1 NeoForge" + - type: textarea + id: description + attributes: + label: Feature Description / 功能描述 + description: "What feature would you like to have? Please describe it here. / 您希望拥有什么功能?请在此描述。" + placeholder: "Example: I want to be able to do... / 例如:我希望能够做..." + validations: + required: true + - type: markdown + attributes: + value: Thank you for taking the time to fill out this feature request. / 感谢您抽出时间填写此功能请求。 \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..e4c90c4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Discord / Discord 服务器 + url: https://discord.gg/KqQx9DEJGm + about: Join us on Discord to chat, discuss the game, and more. For bug reports, please use GitHub issues. / 加入我们的 Discord 服务器来闲聊、讨论游戏等。错误报告请使用 GitHub issues。 \ No newline at end of file diff --git a/.github/actions/build_setup/action.yml b/.github/actions/build_setup/action.yml new file mode 100644 index 0000000..c1bf4ed --- /dev/null +++ b/.github/actions/build_setup/action.yml @@ -0,0 +1,32 @@ +name: Build Setup +description: Setup for standard Java builds + +inputs: + update-cache: + description: If cache should be updated + required: false + default: 'false' + ref: + description: 'Ref to checkout' + required: false + +runs: + using: 'composite' + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.ref || github.ref }} + - name: Set up JDK + uses: actions/setup-java@v4 + env: + REF: ${{ inputs.ref || github.ref }} + with: + distribution: temurin + java-version: 25 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + with: + cache-write-only: ${{ inputs.update-cache }} + cache-read-only: ${{ github.ref != 'refs/heads/26.1' }} + add-job-summary: 'on-failure' diff --git a/.github/json/config-latest.json b/.github/json/config-latest.json new file mode 100644 index 0000000..862e013 --- /dev/null +++ b/.github/json/config-latest.json @@ -0,0 +1,35 @@ +{ + "categories": [ + { + "title": "### Added", + "labels": ["type: feature"] + }, + { + "title": "### Fixed", + "labels": ["type: bugfix"] + }, + { + "title": "### Changed", + "labels": ["type: refactor", "type: translation"] + } + ], + "sort": "ASC", + "template": "## What's Changed since #{{FROM_TAG}}\n#{{CHANGELOG}}\n#{{UNCATEGORIZED}}\n#{{CHANGES}} lines changed - see the [full diff here](#{{RELEASE_DIFF}})", + "pr_template": "- #{{TITLE}} by @#{{AUTHOR}} in [##{{NUMBER}}](#{{URL}})", + "empty_template": "", + "ignore_labels": ["ignore changelog"], + "tag_resolver": { + "method": "semver", + "filter": { + "pattern": "^(?!v?[0-9\\.]+(-26\\.1)?$).+$", + "flags": "gu" + }, + "transformer": { + "pattern": "v?([0-9\\.]+)(-[0-9\\.]+)?", + "target": "$1" + } + }, + "max_pull_requests": 1000, + "max_back_track_time_days": 365, + "base_branches": ["26.1"] +} diff --git a/.github/json/config.json b/.github/json/config.json new file mode 100644 index 0000000..400626e --- /dev/null +++ b/.github/json/config.json @@ -0,0 +1,45 @@ +{ + "categories": [ + { + "title": "### Added", + "labels": ["type: feature"] + }, + { + "title": "### Fixed", + "labels": ["type: bugfix"] + }, + { + "title": "### Changed", + "labels": ["type: refactor", "type: translation"] + } + ], + "sort": "ASC", + "template": "## Version [v#{{VERSION}}](#{{RELEASE_DIFF}})\n#{{CHANGELOG}} ", + "pr_template": "- #{{TITLE}} by @#{{AUTHOR}} in [##{{NUMBER}}](#{{URL}})", + "custom_placeholders": [ + { + "name": "VERSION", + "source": "TO_TAG", + "transformer": { + "pattern": "v?([0-9\\.]+)(-[0-9\\.]+)?", + "target": "$1" + } + } + ], + "empty_template": "", + "ignore_labels": ["ignore changelog"], + "tag_resolver": { + "method": "semver", + "filter": { + "pattern": "^(?!v?[0-9\\.]+(-26\\.1)?$).+$", + "flags": "gu" + }, + "transformer": { + "pattern": "v?([0-9\\.]+)(-[0-9\\.]+)?", + "target": "$1" + } + }, + "max_pull_requests": 1000, + "max_back_track_time_days": 365, + "base_branches": ["26.1"] +} diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000..26bb812 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,3 @@ +# https://github.com/github/issue-labeler#usage +26.1: + - '/^26\.1 NeoForge$/m' \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..e4d6702 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,26 @@ +## What / 目的 +_This section describes what this PR is about. It should be a clear and concise description concerning what this PR is for, why this PR is needed, and why it should be accepted._ +_Linking an issue can be used alternatively to writing a description._ +_此部分描述该 PR 的内容。它应清晰简洁地说明该 PR 的目的、必要性以及为何应该被接受。_ +_也可以通过链接相关 Issue 来替代描述。_ + +## Implementation Details / 实现细节 +_Any implementations in this PR that should be carefully looked over, or that could/should have alternate solutions proposed._ +_本 PR 中任何需要仔细审查的实现细节,或者可能/应该提出替代解决方案的部分。_ + +## Outcome / 结果 +_A short description of what this PR added/fixed/changed/removed._ +_For correct linking of issues please use any of the Closes/Fixes/Resolves keywords. Example: When a PR is fixing a bug use "Fixes: #number-of-bug"_ +_简要描述此 PR 添加/修复/更改/删除了什么。_ +_为了正确链接 Issue,请使用 Closes/Fixes/Resolves 等关键词。例如:当 PR 修复一个 bug 时,使用 "Fixes: #bug编号"_ + +## Additional Information / 附加信息 +_This section is for screenshots to demonstrate any GUI or rendering changes, or any other additional information that reviewers should be aware of._ +_此部分用于放置展示 GUI 或渲染更改的截图,或任何其他审阅者应了解的其他信息。_ + +## Potential Compatibility Issues / 潜在兼容性问题 +_This section is for defining possible compatibility issues. It must be used when there are API changes, item/block/material/machine changes, or recipe changes._ +_此部分用于定义可能的兼容性问题。当存在 API 更改、物品/方块/材料/机器更改或配方更改时,必须使用此部分。_ + +**Please fill in as much useful information as possible. Also, please remove all unused sections, including this and the other explanations.** +**请尽可能填写有用的信息。同时,请删除所有未使用的部分,包括此说明和其他解释。** \ No newline at end of file diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..3f89d47 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,26 @@ +changelog: + + exclude: + labels: + - "ignore changelog" + + categories: + - title: New Features + labels: + - "type: feature" + + - title: Bug Fixes + labels: + - "type: bug" + + - title: Internal Changes + labels: + - "type: refactor" + + - title: Translation Changes + labels: + - "type: translation" + + - title: Other Changes + labels: + - "*" diff --git a/.github/workflows/auto-build.yml b/.github/workflows/auto-build.yml new file mode 100644 index 0000000..11a480b --- /dev/null +++ b/.github/workflows/auto-build.yml @@ -0,0 +1,71 @@ +name: Latest Build + +on: + push: + branches: ['26.1'] + paths: ['src/**', '**/*.gradle', 'gradle.properties'] + +concurrency: + group: auto-build-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + env: + GITHUB_TOKEN: ${{ github.token }} + PUBLISH: ${{ !contains(github.event.commits[0].message, '[no-snapshot]') }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + MAVEN_USER: ${{ secrets.MAVEN_USER }} + SNAPSHOT: true + CI: true + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # do a full checkout instead of a shallow clone of HEAD so spotless's ratchetFrom works + - name: Setup Build + uses: ./.github/actions/build_setup + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Get Mod Version + id: ver + run: echo "version=$(./gradlew -q printVersion)" >> $GITHUB_OUTPUT + - name: Version Suffix + id: suffix + run: echo "VERSION_SUFFIX=$(echo "${{ github.sha }}" | cut -c 1-7)" >> $GITHUB_ENV + - name: Build + run: ./gradlew build + - name: Rename Jars + if: ${{ env.PUBLISH == 'true' }} + run: for file in build/libs/*; do mv "$file" "${file/SHOT/SHOT+$(date --utc '+%Y%m%d-%H%M%S')-${{ env.VERSION_SUFFIX }}}"; done; + - name: Upload Artifacts + if: ${{ env.PUBLISH == 'true' }} + uses: actions/upload-artifact@v4 + with: + name: build-artifacts + path: build/libs/* + if-no-files-found: error + retention-days: 90 + - name: Changelog + id: changelog + if: ${{ env.PUBLISH == 'true' }} + uses: mikepenz/release-changelog-builder-action@v5 + with: + configuration: "./.github/json/config-latest.json" + toTag: ${{ github.ref }} + fetchViaCommits: true + failOnError: false + - name: Release Latest + if: ${{ env.PUBLISH == 'true' }} + uses: andelf/nightly-release@46e2d5f80828ecc5c2c3c819eb31186a7cf2156c + with: + tag_name: latest-${{ github.ref_name }} + name: '${{ github.ref_name }}-${{ steps.ver.outputs.version}} SNAPSHOT ${{ env.VERSION_SUFFIX }}' + prerelease: true + body: | + The latest build of RegistrateLib for Minecraft ${{ github.ref_name }}. + Please report any [issues](https://github.com/ModularMCLib/Registrate-Lib/issues). + ${{ steps.changelog.outputs.changelog }} + files: build/libs/*.jar diff --git a/.github/workflows/build-on-push.yml b/.github/workflows/build-on-push.yml new file mode 100644 index 0000000..accf677 --- /dev/null +++ b/.github/workflows/build-on-push.yml @@ -0,0 +1,54 @@ +name: Build pull request on push + +on: + pull_request: + paths: ['**'] + +# Cancel previous jobs if PR gets another push +concurrency: + group: PR-build-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + env: + VERSION_SUFFIX: "PR-${{ github.event.number }}" + steps: + - uses: actions/checkout@v4 + - name: Check Path Filter + uses: dorny/paths-filter@v3 + id: filter + with: + filters: | + code: + - 'src/**' + - '*.gradle' + - 'gradle.properties' + - 'gradlew*' + - 'gradle/**' + - name: Setup Build + if: steps.filter.outputs.code == 'true' + uses: ./.github/actions/build_setup + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Build + if: steps.filter.outputs.code == 'true' + run: ./gradlew assemble + - name: Rename Jars + if: steps.filter.outputs.code == 'true' + run: for file in build/libs/*; do mv "$file" "${file/.jar/-${{ env.VERSION_SUFFIX }}.jar}"; done; + - name: Upload All Artifacts + if: steps.filter.outputs.code == 'true' + uses: actions/upload-artifact@v4.0.0 + with: + name: Full Package + path: build/libs/* + retention-days: 15 + - name: Upload Main Jar + if: steps.filter.outputs.code == 'true' + uses: actions/upload-artifact@v4.0.0 + with: + name: Main Jar + path: build/libs/*[0-9]-PR-*.jar + retention-days: 15 diff --git a/.github/workflows/clean.yml b/.github/workflows/clean.yml new file mode 100644 index 0000000..8e35795 --- /dev/null +++ b/.github/workflows/clean.yml @@ -0,0 +1,20 @@ +name: Clean Gradle + +on: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - name: Setup Build + uses: ./.github/actions/build_setup + with: + update-cache: true + - name: Make gradlew executable + run: chmod +x ./gradlew + - name: Clean + run: ./gradlew clean diff --git a/.github/workflows/format-java.yml b/.github/workflows/format-java.yml new file mode 100644 index 0000000..2abb8cd --- /dev/null +++ b/.github/workflows/format-java.yml @@ -0,0 +1,41 @@ +# Runs formatting requirements +name: Java Formatting + +on: + push: + branches: ['26.1'] + paths: ['src/main/java/**', 'src/test/**'] + pull_request: + paths: ['**'] + +concurrency: + group: formatting-${{ github.ref }} + cancel-in-progress: true + +jobs: + formatting: + name: Formatting + runs-on: ubuntu-latest + permissions: + pull-requests: read + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 # do a full checkout instead of a shallow clone of HEAD so spotless's ratchetFrom works + - name: Check Path Filter + uses: dorny/paths-filter@v3 + id: filter + with: + filters: | + code: + - 'src/main/java/**' + - 'src/test/**' + - name: Setup Build + if: steps.filter.outputs.code == 'true' + uses: ./.github/actions/build_setup + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Run Spotless Formatting Check with Gradle + if: steps.filter.outputs.code == 'true' + run: ./gradlew spotlessCheck --warning-mode all diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 0000000..48cbd8b --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,12 @@ +name: Label PRs + +on: + - pull_request_target + +jobs: + labeler: + permissions: + pull-requests: write + contents: read + uses: ModularMCLib/GithubActions/.github/workflows/labeler.yml@main + secrets: inherit diff --git a/.github/workflows/manage-issue-labels.yml b/.github/workflows/manage-issue-labels.yml new file mode 100644 index 0000000..ec7b5cd --- /dev/null +++ b/.github/workflows/manage-issue-labels.yml @@ -0,0 +1,23 @@ +# Manages labels on new issues +name: Issue Labels + +on: + issues: + types: [opened] + +permissions: + issues: write + contents: read + +jobs: + labels: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: '26.1' + sparse-checkout: '.github/labeler.yml' + - uses: github/issue-labeler@v3.3 + with: + configuration-path: .github/labeler.yml + enable-versioned-regex: 0 diff --git a/.github/workflows/manage-pr-labels.yml b/.github/workflows/manage-pr-labels.yml new file mode 100644 index 0000000..c0dc5b6 --- /dev/null +++ b/.github/workflows/manage-pr-labels.yml @@ -0,0 +1,43 @@ +# Manages labels on PRs before allowing merging +name: Pull Request Labels + +# Checks for label once PR has been reviewed or label is applied +on: + pull_request: + types: [opened, labeled, unlabeled] + +concurrency: + group: pr-labels-${{ github.head_ref }} + cancel-in-progress: true + +jobs: + labels: + name: Label Check + runs-on: ubuntu-latest + permissions: + pull-requests: read # needed to utilize required-labels + steps: + - name: Check for Merge-Blocking Labels # blocks merge if present + uses: mheap/github-action-required-labels@v5 + with: + mode: exactly + count: 0 + labels: 'do not merge, admin merge' + exit_type: failure + + - name: Check for Required Type Labels # require at least one of these labels + uses: mheap/github-action-required-labels@v5 + with: + mode: minimum + count: 1 + labels: 'type: feature, type: bugfix, type: refactor, type: translation, type: tests, ignore changelog' + exit_type: failure + + - name: Check for Required Release Label # require exactly one of these labels + uses: mheap/github-action-required-labels@v5 + with: + mode: exactly + count: 1 + labels: 'release: api - X.0.0, release: major - 0.X.0, release: Patch - 0.0.X, release: stale' + exit_type: failure + diff --git a/.github/workflows/publish-on-release.yml b/.github/workflows/publish-on-release.yml new file mode 100644 index 0000000..ecd72fb --- /dev/null +++ b/.github/workflows/publish-on-release.yml @@ -0,0 +1,44 @@ +name: Publish on Release + +on: + release: + types: [released] + +jobs: + meta: + name: Metadata + runs-on: ubuntu-latest + outputs: + CHANGELOG: ${{ steps.changelog.outputs.changelog }} + permissions: + contents: write + pull-requests: read + steps: + - name: Get Config + uses: actions/checkout@v4 + with: + ref: ${{ github.ref_name }} + sparse-checkout: '.github/json' + - name: Generate changelog + id: changelog + env: + GITHUB_TOKEN: ${{ github.token }} + uses: mikepenz/release-changelog-builder-action@v5 + with: + configuration: './.github/json/config.json' + ignorePreReleases: true + fetchViaCommits: true + failOnError: true + + publish-26: + name: '26.1' + needs: [ meta ] + if: ${{ contains(github.ref_name, '26.1') }} + secrets: inherit + uses: ./.github/workflows/publish.yml + with: + simulate: ${{ startsWith(github.event.release.name, 'simulate') || github.repository_owner != 'ModularMCLib' }} + tag-name: ${{ github.ref_name }} + version: '26.1' + release-body: ${{ github.event.release.body }} + changelog-body: ${{ needs.meta.outputs.CHANGELOG }} \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..c822ec7 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,180 @@ +name: Publish Version + +on: + workflow_call: + inputs: + simulate: + required: false + type: boolean + tag-name: + description: 'Tag to build from and upload to' + required: true + type: string + version: + description: 'Version identifier;' + required: true + type: string + release-body: + description: 'Body for published release notes' + required: false + type: string + changelog-body: + description: 'Body of change notes to insert into CHANGELOG.md' + required: false + type: string + +jobs: + build: + name: Build and Publish to Maven + runs-on: ubuntu-latest + permissions: + contents: write + env: + CI: 'true' + outputs: + ver: ${{ steps.ver.outputs.version }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.branch }} + - name: Setup Build + uses: ./.github/actions/build_setup + with: + ref: ${{ inputs.branch }} + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Get Version + id: ver + run: echo "version=$(./gradlew -q printVersion)" >> $GITHUB_OUTPUT + - name: Build + run: ./gradlew assemble + - name: Upload Build Artifacts + uses: actions/upload-artifact@v4 + with: + name: build-artifacts-${{ inputs.tag-name }} + path: build/libs/* + if-no-files-found: error + retention-days: 3 + - name: Publish + if: ${{ !inputs.simulate }} + env: + MAVEN_USER: ${{ secrets.MAVEN_USER }} + MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }} + run: ./gradlew publish + + upload-release-artifacts: + name: Upload Artifacts + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Download artifacts + uses: actions/download-artifact@v4 + with: + name: build-artifacts-${{ inputs.tag-name }} + - name: Upload artifacts to release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ inputs.tag-name }} + files: ./*.jar + fail_on_unmatched_files: true + +# publish-modrinth: +# name: Publish to Modrinth +# needs: build +# if: ${{ !inputs.simulate }} +# runs-on: ubuntu-latest +# permissions: +# contents: write +# steps: +# - name: Download artifacts +# uses: actions/download-artifact@v4 +# with: +# name: build-artifacts-${{ inputs.branch }} +# - name: Publish Mod +# env: +# MC_VERSION: ${{ inputs.branch == '1.21' && '1.21.1' || '1.20.1' }} +# LOADER: ${{ inputs.branch == '1.21' && 'neoforge' || 'forge' }} +# JAVA: ${{ inputs.branch == '1.21' && '21' || '17' }} +# VERSION_TYPE: ${{ inputs.branch == '1.21' && 'beta' || 'beta' }} +# uses: Kir-Antipov/mc-publish@v3.3.0 +# with: +# modrinth-id: aADDBrNC +# modrinth-token: ${{ secrets.MODRINTH_TOKEN }} +# files: | +# ./registrate-${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}.jar +# ./!(registrate-${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}.jar) +# name: 'RegistrateLib ${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}' +# version: 'mc${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}' +# version-type: ${{ env.VERSION_TYPE }} +# changelog: ${{ inputs.release-body }} +# loaders: ${{ env.LOADER }} +# java: ${{ env.JAVA }} +# fail-mode: fail +# +# publish-cf: +# name: Publish to CF +# needs: build +# if: ${{ !inputs.simulate }} +# runs-on: ubuntu-latest +# permissions: +# contents: write +# steps: +# - name: Download artifacts +# uses: actions/download-artifact@v4 +# with: +# name: build-artifacts-${{ inputs.branch }} +# - name: Publish Mod +# env: +# MC_VERSION: ${{ inputs.branch == '1.21' && '1.21.1' || '1.20.1' }} +# LOADER: ${{ inputs.branch == '1.21' && 'neoforge' || 'forge' }} +# JAVA: ${{ inputs.branch == '1.21' && '21' || '17' }} +# VERSION_TYPE: ${{ inputs.branch == '1.21' && 'alpha' || 'beta' }} +# uses: Kir-Antipov/mc-publish@v3.3.0 +# with: +# curseforge-id: 1397216 +# curseforge-token: ${{ secrets.CURSEFORGE_TOKEN }} +# files: | +# ./registrate-${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}.jar +# ./!(registrate-${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}.jar) +# name: 'RegistrateLib ${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}' +# version: 'mc${{ env.MC_VERSION }}-${{ needs.build.outputs.ver }}' +# version-type: ${{ env.VERSION_TYPE }} +# changelog: ${{ inputs.release-body }} +# loaders: ${{ env.LOADER }} +# java: ${{ env.JAVA }} +# fail-mode: fail + + # After successful release, PR version bump and changelog + bump-version-and-changelog: + name: Bump Version and Build Changelog + needs: [ build, upload-release-artifacts ] + if: ${{ always() && !failure() && !cancelled() }} + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.branch }} + - name: Bump Version + run: | + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git switch -C gh/release-${{ inputs.version }} + BUMPED=$(echo ${{ needs.build.outputs.ver }} | awk -F. '/[0-9]+\./{$NF++;print}' OFS=.) + sed -i "s/= ${{ needs.build.outputs.ver }}/= ${BUMPED}/" gradle.properties + git commit -am "Bump version to ${BUMPED}" + - name: Prepend to CHANGELOG + if: inputs.changelog-body + run: | + { head -n 2 CHANGELOG.md; echo -e "${{ inputs.changelog-body }}"; tail -n +3 CHANGELOG.md; } > temp.md && mv temp.md CHANGELOG.md + git commit -am "Updated CHANGELOG" + - name: Push and PR + env: + GH_TOKEN: ${{ github.token }} + run: | + git push --force --set-upstream origin gh/release-${{ inputs.version }} + gh pr create -B ${{ inputs.version }} -H gh/release-${{ inputs.version }} --title "RELEASE for ${{ inputs.version }} [no-snapshot]" --body "Created by GH Workflow" --label "ignore changelog" diff --git a/.github/workflows/sync.yml b/.github/workflows/sync.yml new file mode 100644 index 0000000..4890463 --- /dev/null +++ b/.github/workflows/sync.yml @@ -0,0 +1,23 @@ +name: Sync Github Folder + +on: + push: + branches: ['26.1'] + paths: ['.github/**'] + +jobs: + sync: + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4 + - run: | + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git switch -C gh/workflow-sync + git fetch origin + git checkout origin/26.1 -- .github + git add .github + git commit --allow-empty -m "Sync Workflows" + git push --force --set-upstream origin gh/workflow-sync diff --git a/.github/workflows/test-on-push.yml b/.github/workflows/test-on-push.yml new file mode 100644 index 0000000..871ebe2 --- /dev/null +++ b/.github/workflows/test-on-push.yml @@ -0,0 +1,62 @@ +name: Test pull request on push + +on: + pull_request: + paths: ['**'] + +# Cancel previous jobs if PR gets another push +concurrency: + group: PR-test-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + runs-on: ubuntu-latest + env: + VERSION_SUFFIX: "PR-${{ github.event.number }}" + steps: + - uses: actions/checkout@v4 + - name: Check Path Filter + uses: dorny/paths-filter@v3 + id: filter + with: + filters: | + code: + - 'src/**' + - '*.gradle' + - 'gradle.properties' + - 'gradlew*' + - 'gradle/**' + - name: Setup Build + if: steps.filter.outputs.code == 'true' + uses: ./.github/actions/build_setup + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Run GameTests + if: steps.filter.outputs.code == 'true' + id: gametest + continue-on-error: true + run: ./gradlew runGameTestServer + - name: Update “Tests Passed” / “Tests Failed” labels + if: steps.filter.outputs.code == 'true' && github.event.pull_request.head.repo.full_name == github.repository + uses: actions/github-script@v7 + with: + script: | + const [add, remove] = { + success: ['Tests: Passed','Tests: Failed'], + failure: ['Tests: Failed','Tests: Passed'] + }['${{ steps.gametest.outcome }}']; + + const { owner, repo } = context.repo; + const issue_number = context.payload.pull_request.number; + + await github.rest.issues + .addLabels({ owner, repo, issue_number, labels: [add] }) + .catch(() => {}); + + await github.rest.issues + .removeLabel({ owner, repo, issue_number, name: remove }) + .catch(() => {}); + - name: Fail on GameTest failures + if: steps.filter.outputs.code == 'true' && steps.gametest.outcome == 'failure' + run: exit 1 \ No newline at end of file diff --git a/.github/workflows/update-gradle-cache.yml b/.github/workflows/update-gradle-cache.yml new file mode 100644 index 0000000..1146b6b --- /dev/null +++ b/.github/workflows/update-gradle-cache.yml @@ -0,0 +1,28 @@ +# Updates the Gradle Cache when necessary +name: Update Gradle Cache + +on: + push: + branches: ['26.1'] + paths: ['gradle/**', '**/*.gradle', 'gradle.properties', 'gradlew*', 'src/main/resources/META-INF/accesstransformer.cfg'] + workflow_dispatch: + +concurrency: + group: gradle-cache-${{ github.ref }} + cancel-in-progress: true + +jobs: + update-cache: + name: Update Grade Cache + runs-on: ubuntu-latest + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + - name: Setup Build + uses: ./.github/actions/build_setup + with: + update-cache: true + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: Build Project with Gradle + run: ./gradlew assemble --warning-mode all diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..01a89a8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +build/ +*.ipr +run/ +*.iws +out/ +*.iml +.gradle/ +output/ +bin/ +libs/ + +.classpath +*/.factorypath +.project +.idea/ +.kotlin/ +classes/ +.metadata +.vscode +.eclipse +.settings +*.launch +.architectury-transformer/debug.log +**/resources/.cache/ + +*.patch +*.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9fc1328 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,19 @@ +# ChangeLog + +## Version [v2.0.0](https://github.com/ModularMCLib/Registrate-Lib/compare/v1.0.0-26.1...v2.0.0-26.1) +### Added + +- Fix GitHub workflow copy and repository links by @QiuYe-123 in [#2](https://github.com/ModularMCLib/Registrate-Lib/pull/2) + +### Fixed + +- Fix chengelog config by @QiuYe-123 in [#4](https://github.com/ModularMCLib/Registrate-Lib/pull/4) + +### Changed + +- 重构 by @QiuYe-123 in [#1](https://github.com/ModularMCLib/Registrate-Lib/pull/1) + + + + +- no changes diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..12eca1e --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,7 @@ +# All other changes require the primary team +* @ModularMCLib/registratedevs + +# Specific files requiring admin approval +CODEOWNERS @ModularMCLib/admin +LICENSE @ModularMCLib/admin +/README.md @ModularMCLib/admin diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ba9f119 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# 贡献指南 / Contributing + +## 开发基线 / Development Baseline + +- Java: `25` +- 构建工具 / Build tool: Gradle wrapper +- 推荐 IDE / Recommended IDE: IntelliJ IDEA(使用生成的运行配置 / with the generated run configurations) +- 换行符 / Line endings: `LF`(通过 `.gitattributes` 和 `.editorconfig` / via `.gitattributes` and `.editorconfig`) + +## 本地工作流程 / Local Workflow + +1. 使用 Java 25 运行时同步 Gradle 项目 / Sync the Gradle project with a Java 25 runtime +2. 在你所接触的行为所属的包层内进行修改 / Make changes inside the package layer that owns the behavior you are touching +3. 使用 `./gradlew build` 或 `gradlew.bat build` 验证 / Validate with `./gradlew build` or `gradlew.bat build` +4. 使用 IDEA 运行配置进行交互式验证 / Use the IDEA run configurations for interactive verification: + - `Client` / 客户端 + - `Server` / 服务端 + - `Data Generation` / 数据生成 + - `Game Tests` / 游戏测试 + - `Game Tests (Client)` / 游戏测试(客户端) + +## 包边界 / Package Boundaries + +- 流式注册 API 放在 `com.modularmc.registrate.builders` + Put fluent registration APIs in `com.modularmc.registrate.builders` +- 数据生成连接放在 `com.modularmc.registrate.providers` + Put data generation wiring in `com.modularmc.registrate.providers` +- 通用运行时支持代码放在 `com.modularmc.registrate.util` + Put generic runtime support code in `com.modularmc.registrate.util` +- 类型化注册包装器保持在 `com.modularmc.registrate.util.entry` + Keep typed registry wrappers in `com.modularmc.registrate.util.entry` +- 当概念属于 builder 或 provider 时,避免向 `util` 添加新的公开 API 表面 + Avoid adding new public API surface to `util` when the concept belongs in a builder or provider + +## 维护说明 / Maintenance Notes + +- `RegistrateLib` 是本分支的库模组入口点,同时持有共享元数据/常量 + `RegistrateLib` is the library mod entrypoint for the fork and also holds shared metadata/constants +- `src/test/java/com/modularmc/registrate/test/meta` 包含用于生成的桥接方法的维护辅助工具 + `src/test/java/com/modularmc/registrate/test/meta` contains maintenance helpers for generated bridge methods +- 当上游 Registrate 变更时,先更新实现类,然后对照 `docs/architecture.md` 重新验证包所有权 + When upstream Registrate changes, update implementation classes first and then re-verify package ownership against `docs/architecture.md` diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c935c6a --- /dev/null +++ b/README.md @@ -0,0 +1,170 @@ +# RegistrateLib [![License](https://img.shields.io/github/license/ModularMCLib/RegistrateLib?cacheSeconds=36000)](https://www.tldrlegal.com/l/mpl-2.0) ![Minecraft Version](https://img.shields.io/badge/minecraft-26.1.1-blue) + + + + +[![Build Status](#)]() +[![Maven Version](#)]() + +一个用于在你的模组中创建和注册对象的强大封装。 +A powerful wrapper for creating and registering objects in your mod. + +--- + +## 分支状态 / Fork Status + +本仓库是 `com.modularmc.registrate` 命名空间下的 Registrate 分支,为 ModularMCLib 生态维护。它追踪上游 Registrate 的设计,同时面向现代 NeoForge + Minecraft `26.1` 工具链,并保留可安全嵌入下游项目的包命名空间。 +This repository is the `com.modularmc.registrate` fork maintained for the ModularMCLib ecosystem. It tracks the upstream Registrate design while targeting the modern NeoForge + Minecraft `26.1` toolchain and preserving a package namespace that can be safely embedded in downstream projects. + +--- + +## 快速链接 / Quick Links + + +- Javadocs(待定 / TBD) +- [维基 / Wiki](https://github.com/ModularMCLib/RegistrateLib/wiki) +- [贡献指南 / Contributing](CONTRIBUTING.md) + +--- + +## 为什么使用 Registrate? / Why Registrate? + +- 你可以按照自己的方式组织模组内容,无需将每个对象的定义分散在各处 + Allows you to organize your mod content however you like, rather than having pieces of each object defined in scattered places +- 简洁的流式 API / Simple fluent API +- 可扩展,支持构建和注册自定义对象及数据 + Open to extension, build and register custom objects and data +- 自动数据生成,提供合理的默认值 + Automatic data generation with sane defaults +- 既可作为独立的 NeoForge 库模组使用,也可作为下游模组的声明依赖使用 + Usable as a standalone NeoForge library mod and as a declared dependency for downstream mods + +--- + +## 代码分类 / Code Classification + +- `com.modularmc.registrate` — 公开 API 入口、最小化的库引导、注册协调中心 / public API roots, minimal library bootstrap, and the central registration coordinator +- `com.modularmc.registrate.builders` — 下游模组用于注册内容的流式 DSL / the fluent DSL used by downstream mods to register content +- `com.modularmc.registrate.providers` — 数据生成编排与提供者生命周期管理 / data generation orchestration and provider lifecycle management +- `com.modularmc.registrate.providers.generators` — 方块状态、模型和配方生成器适配器 / blockstate, model, and recipe generator adapters +- `com.modularmc.registrate.providers.loot` — 战利品表提供者封装 / loot-table focused provider wrappers +- `com.modularmc.registrate.util` — 公开的共享辅助工具 / public shared helpers that remain part of the reusable library surface +- `com.modularmc.registrate.util.entry` — 构建器返回的强类型注册句柄 / strongly-typed registry handles returned by builders +- `com.modularmc.registrate.util.nullness` — 空安全的函数式辅助与包级默认值 / null-safe functional helpers and package defaults +- `com.modularmc.registrate.internal` — 核心运行时的非 API 实现细节 / non-API implementation details extracted from the core runtime +- `com.modularmc.registrate.internal.event` — 用于构建器和注册生命周期钩子的一次性事件连接 / one-shot event wiring used by builders and registration lifecycle hooks +- `com.modularmc.registrate.internal.lifecycle` — 实例级生命周期桥接 / per-instance lifecycle bridges +- `com.modularmc.registrate.internal.util` — 分发限制执行与内部日志辅助 / dist-gated execution and internal logging helpers +- `com.modularmc.registrate.test.mod` — 集成测试示例模组 / the integration-style sample mod +- `com.modularmc.registrate.test.gametests` — 可执行的运行时验证场景 / executable validation scenarios for runtime behavior +- `com.modularmc.registrate.test.meta` — 维护工具,使生成的桥接方法与上游 API 保持一致 / maintenance utilities that keep generated bridge methods aligned with upstream APIs + +--- + +## 使用方法 / How to Use + +首先,创建一个 `Registrate` 对象,该对象将在整个项目中使用。 +First, create a `Registrate` object which will be used across your entire project. + +```java +public static final Registrate REGISTRATE = Registrate.create(MOD_ID); +``` + +不一定要使用常量字段,可以在注册设置完成后传递或丢弃。 +Using a constant field is not necessary, it can be passed around and thrown away after registration is setup. + +如果在 `@Mod` 类中声明为 `static`,必须延迟创建 `Registrate` 对象,避免在加载过程中过早创建。可以这样轻松实现: +If declared static in your `@Mod` class, you must create the `Registrate` object lazily so it is not created too early during loading. This can be done easily like so: + +```java +public static final NonNullSupplier REGISTRATE = NonNullSupplier.lazy(() -> Registrate.create(MOD_ID)); +``` + +接下来,开始添加对象。 +Next, begin adding objects. + +如果你有一个方块类: +If you have a block class such as: + +```java +public class MyBlock extends Block { + + public MyBlock(Block.Properties properties) { + super(properties); + } + + ... +} +``` + +可以这样注册: +then register it like so: + +```java +public static final RegistryEntry MY_BLOCK = REGISTRATE.block("my_block", MyBlock::new).register(); +``` + +Registrate 会创建一个方块,并生成默认的简单方块状态、模型、战利品表和语言条目。所有这些方面都可以轻松配置为自定义数据。例如: +Registrate will create a block, with a default simple blockstate, model, loot table, and lang entry. However, all of these facets can be configured easily to use whatever custom data you may want. Example: + +```java +public static final RegistryEntry MY_STAIRS = REGISTRATE.block("my_block", MyStairsBlock::new) + .defaultItem() + .tag(BlockTags.STAIRS) + .blockstate(ctx -> ctx.getProvider() + .stairsBlock(ctx.getEntry(), ctx.getProvider().modLoc(ctx.getName()))) + .lang("Special Stairs") + .register(); +``` + +这个自定义版本会创建 BlockItem(含默认模型和语言条目)、将方块添加到标签、配置楼梯属性方块状态,并添加自定义本地化。 +This customized version will create a BlockItem (with its own default model and lang entry), add the block to a tag, configure the blockstate for stair properties, and add a custom localization. + + +有关不同 API 和方法的概述,请查阅 Javadocs(待定)。更高级的用法请阅读 [维基](https://github.com/ModularMCLib/RegistrateLib/wiki)(编写中)。 + +To get an overview of the different APIs and methods, check out the Javadocs (TBD). For more advanced usage, read the [wiki](https://github.com/ModularMCLib/RegistrateLib/wiki) (WIP). + +--- + +## 项目设置 / Project Setup + +将库添加到 Gradle 依赖: +Add the library to your Gradle dependencies: + +```groovy +dependencies { + implementation "com.modularmc.registrate:registratelib:${registratelib_version}" +} +``` + +然后在 `neoforge.mods.toml` 中将 `registratelib` 声明为必需依赖: +Then declare `registratelib` as a required dependency in your `neoforge.mods.toml`: + +```toml +[[dependencies.yourmodid]] +modId="registratelib" +type="required" +versionRange="[2.0.0,)" +ordering="AFTER" +side="BOTH" +``` + +--- + +## 开发指南 / Development + +- 使用 `Java 25` 进行本地构建和 IDE 同步 / Use `Java 25` for local builds and IDE sync +- 优先使用捆绑的 IDEA 运行配置:`Client`、`Server`、`Data Generation`、`Game Tests`、`Game Tests (Client)` + Prefer the bundled IDEA run configurations +- 流式注册 API 放在 `builders`,数据生成编排放在 `providers`,公开辅助工具放在 `util`,实现细节放在 `internal` + Keep fluent registration APIs in `builders`, data generation orchestration in `providers`, public reusable helpers in `util`, and implementation plumbing in `internal` +- 查看 [`docs/architecture.md`](docs/architecture.md) 了解包职责和扩展点 + See [`docs/architecture.md`](docs/architecture.md) for package responsibilities and extension points + +--- + +## 贡献 / Contributing + +请阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md) 了解如何为此项目做出贡献。 +Please read [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on how to contribute to this project. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..80cd051 --- /dev/null +++ b/build.gradle @@ -0,0 +1,129 @@ +plugins { + id 'java-library' + id 'org.jetbrains.kotlin.jvm' + id 'eclipse' + id 'idea' + id 'maven-publish' + id 'jacoco' + alias libs.plugins.modDevGradle + //alias libs.plugins.shadow + alias libs.plugins.spotless + alias libs.plugins.lombok +} + +group = maven_group +// Formats the mod version to include the loader, Minecraft version, and '-SNAPSHOT-' if enabled. +boolean isSnapshot = System.getenv("SNAPSHOT") +version = "${mod_version}" + (isSnapshot ? "-SNAPSHOT" : "") +boolean isCI = System.getenv("CI") != null + +java { + toolchain.languageVersion = JavaLanguageVersion.of(25) +} + +sourceSets { + // Include resources generated by data generators. + main.resources { + srcDir 'src/generated/resources' + } + + client { + compileClasspath += main.output + runtimeClasspath += main.output + main.runtimeClasspath + } + + test { + compileClasspath += main.output + main.compileClasspath + runtimeClasspath += main.output + main.runtimeClasspath + resources { + srcDir 'src/test/generated/resources' + } + } + + extra { + compileClasspath += main.output + runtimeClasspath += main.output + main.runtimeClasspath + } + + clientExtra { + compileClasspath += client.output + extra.compileClasspath + // The normal client run also mounts the test mod, so include the test source set + // here to keep generated test resources synchronized into build/resources/test. + runtimeClasspath += client.output + client.runtimeClasspath + extra.runtimeClasspath + test.output + test.runtimeClasspath + } +} + +configurations { + // set these as unresolvable so we don't accidentally force all dependents to use them with us + clientRuntimeOnly.canBeResolved = false + extraRuntimeOnly.canBeResolved = false + clientExtraRuntimeOnly.canBeResolved = false + testImplementation.canBeResolved = false + testRuntimeOnly.canBeResolved = false + + runtimeClasspath.extendsFrom localRuntime + extraRuntimeClasspath.extendsFrom extraLocalRuntime + clientRuntimeClasspath.extendsFrom clientLocalRuntime + extraClientRuntimeClasspath.extendsFrom clientExtraLocalRuntime + + renderNurseCfg { + canBeConsumed = false + } +} + +apply from: "$rootDir/gradle/scripts/jars.gradle" +apply from: "$rootDir/gradle/scripts/moddevgradle.gradle" +apply from: "$rootDir/gradle/scripts/repositories.gradle" +apply from: "$rootDir/dependencies.gradle" +apply from: "$rootDir/gradle/scripts/resources.gradle" +apply from: "$rootDir/gradle/scripts/publishing.gradle" +apply from: "$rootDir/gradle/scripts/spotless.gradle" + + +tasks.withType(JavaCompile).configureEach { + options.encoding = "UTF-8" + options.compilerArgs << "-Xlint:-removal" +} + +tasks.named('test') { + failOnNoDiscoveredTests = false +} + +lombok { + version = "1.18.38" +} + +jacoco { + applyTo runGameTestServer +} + +tasks.named('runGameTestServer') { + jacoco.excludes = ['com.mojang.*', 'net.minecraft.*', 'net.neoforged.*'] +} + +jacocoTestReport { + doFirst { + try { + runGameTestServer.exec() + } catch (RuntimeException ignored) {} + } + doLast { + println "Coverage report location:" + println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('index.html')).get()}" + println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml')).get()}" + } + executionData runGameTestServer + sourceSets sourceSets.test + reports { + csv.required = false + xml.required = true + html.outputLocation = layout.buildDirectory.dir('coverage') + xml.outputLocation = layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml')) + } + afterEvaluate { + classDirectories.setFrom(files(classDirectories.files.collect { + fileTree(dir: it, exclude: '**/client/**') + fileTree(dir: it, exclude: '**/mixins/**') + })) + } +} diff --git a/dependencies.gradle b/dependencies.gradle new file mode 100644 index 0000000..a44c5cb --- /dev/null +++ b/dependencies.gradle @@ -0,0 +1,17 @@ +dependencies { + compileOnly(libs.jetbrains.annotations) + + testImplementation(libs.testframework.get()) + + // Standard runtime mods // + localRuntime(libs.testframework) + + renderNurseCfg(libs.renderNurse) + + ////////////////////////////////////////////////////// + // Runtime mods for dev testing with unclean client // + ////////////////////////////////////////////////////// + + ////////////////////////// + +} diff --git a/docs/advanced.md b/docs/advanced.md new file mode 100644 index 0000000..2aaeab5 --- /dev/null +++ b/docs/advanced.md @@ -0,0 +1,339 @@ +# 高级用法 / Advanced Usage + +--- + +## 自定义注册表 / Custom Registries + +RegistrateLib 支持创建内置注册表和数据包注册表。 +RegistrateLib supports creating both built-in and datapack registries. + +### 内置注册表 / Built-in Registry + +```java +// 创建内置注册表 / Create a built-in registry +public static final ResourceKey> CUSTOM_REGISTRY = + REGISTRATE.makeRegistry("custom", RegistryBuilder::new); + +// 使用该注册表注册对象 / Register objects with this registry +public static final RegistryEntry MY_CUSTOM = + REGISTRATE.object("testcustom") + .simple(CUSTOM_REGISTRY, MyCustomEntry::new); +``` + +### 数据包注册表 / Datapack Registry + +```java +// 创建数据包注册表(仅服务端同步)/ Datapack registry (server-side sync only) +public static final ResourceKey> MY_REGISTRY = + REGISTRATE.makeDatapackRegistry("my_registry", MyEntry.CODEC); + +// 创建数据包注册表(带网络同步)/ Datapack registry (with network sync) +public static final ResourceKey> MY_REGISTRY = + REGISTRATE.makeDatapackRegistry("my_registry", MyEntry.CODEC, MyEntry.NETWORK_CODEC); +``` + +--- + +## 生命周期钩子 / Lifecycle Hooks + +### onRegister —— 注册回调 + +在对象被注册到游戏注册表时触发。 +Fires when the object is registered into the game registry. + +```java +REGISTRATE.item("my_item", Item::new) + .onRegister(item -> { + // 注册时执行操作 / Do something on registration + LOGGER.info("Item registered: {}", item); + }) + .register(); +``` + +### onRegisterAfter —— 依赖注册回调 + +在指定注册表完成注册后触发。 +Fires after a specified registry finishes registration. + +```java +REGISTRATE.block("my_block", MyBlock::new) + .onRegisterAfter(Registries.BLOCK_ENTITY_TYPE, block -> { + // 方块实体注册后执行操作 / Do after block entities are registered + }) + .register(); +``` + +### 全局注册回调 / Global Registration Callbacks + +```java +// 特定条目的注册回调 / Per-entry registration callback +REGISTRATE.addRegisterCallback("my_block", Registries.BLOCK, block -> { + // ... +}); + +// 整个注册表的注册后回调 / Per-registry after-register callback +REGISTRATE.addRegisterCallback(Registries.BLOCK, () -> { + // 所有方块注册完成后执行 / All blocks registered +}); +``` + +--- + +## 数据生成器管理 / Data Generator Management + +### 设置/移除对象数据生成器 / Set/Remove Per-Object Data Generators + +```java +// 通过构建器设置数据生成器 / Via builder +builder.setData(ProviderType.RECIPE, (ctx, recipeProv) -> { ... }); +builder.removeData(ProviderType.RECIPE); + +// 通过 Registrate 实例 / Via Registrate instance +REGISTRATE.setDataGenerator(builder, ProviderType.RECIPE, consumer); +REGISTRATE.setDataGenerator("my_block", Registries.BLOCK, ProviderType.RECIPE, consumer); +REGISTRATE.removeDataGenerator(builder, ProviderType.RECIPE); +``` + +### 添加全局数据生成器 / Add Global Data Generators + +```java +REGISTRATE.addDataGenerator(ProviderType.LANG, langProvider -> { + langProvider.addBlock(MY_BLOCK); +}); +``` + +--- + +## 创造模式标签页 / Creative Mode Tabs + +### 设置默认创造模式标签页 / Set Default Creative Tab + +```java +// 方法 1:引用现有标签页 / Reference an existing tab +REGISTRATE.defaultCreativeTab(CreativeModeTabs.BUILDING_BLOCKS); + +// 方法 2:创建自定义标签页 / Create a custom tab +public static final RegistryEntry MY_TAB = + REGISTRATE.object("my_tab") + .defaultCreativeTab(tab -> tab.withLabelColor(0xFF00AA00)) + .register(); +``` + +### 将物品添加到标签页 / Add Items to Tabs + +```java +REGISTRATE.item("my_item", Item::new) + .tab(MY_TAB.getKey()) // 简单添加 / Simple add + .tab(MY_TAB.getKey(), (ctx, modifier) -> // 上下文感知添加 / Context-aware + modifier.accept(ctx)) + .removeTab(CreativeModeTabs.BUILDING_BLOCKS) // 从标签页移除 / Remove from tab + .register(); +``` + +### 修改现有标签页 / Modify Existing Tabs + +```java +REGISTRATE.modifyCreativeModeTab(CreativeModeTabs.INGREDIENTS, modifier -> { + modifier.accept(MY_ITEM); +}); +``` + +--- + +## 数据映射 / Data Maps + +```java +REGISTRATE.block("my_block", MyBlock::new) + .dataMap(DataMapTypes.FUEL, 300) // 设置燃料值 / Set fuel value + .register(); + +// 带上下文的工厂 / Context-aware factory +REGISTRATE.block("my_block", MyBlock::new) + .dataMap(DataMapTypes.FUEL, ctx -> { + // 根据上下文计算值 / Compute value from context + return ctx.getEntry().is(Blocks.DIAMOND) ? 3200 : 0; + }) + .register(); +``` + +--- + +## 转换器 / Transform + +可以使用 `.transform()` 方法将构建器传递给辅助函数。 +Use `.transform()` to pass the builder to helper functions. + +```java +// 定义可复用的变换函数 / Define reusable transform function +private static BlockBuilder applyDiamondDrop( + BlockBuilder builder) { + return builder.loot((prov, block) -> prov.dropOther(block, Items.DIAMOND)); +} + +// 在构建器中应用 / Apply in builder +REGISTRATE.block("my_block", MyBlock::new) + .transform(MyMod::applyDiamondDrop) + .register(); +``` + +--- + +## DataIngredient —— 数据驱动的配方便利工具 / Data-Driven Recipe Ingredient + +```java +// 从物品条目创建 / From item entries +DataIngredient.items(MY_ITEM); +DataIngredient.items(MY_BLOCK, MY_OTHER_ITEM); + +// 从标签创建 / From tags +DataIngredient.tag(ItemTags.PLANKS); + +// 结合 Ingredient / Combine with Ingredient +DataIngredient.ingredient(Ingredient.of(...), Items.DIAMOND); + +// 获取进度条件 / Get criterion for advancement unlock +DataIngredient.items(MY_ITEM).getCriterion(recipeProvider); +``` + +--- + +## CreativeModeTabModifier —— 标签页修改器 / Tab Modifier + +```java +// 在标签页修改回调中使用的输出接口 +// Output interface used in tab modification callbacks +public interface CreativeModeTab.Output { + void accept(ItemStack stack, CreativeModeTab.TabVisibility visibility); +} + +// CreativeModeTabModifier 额外方法 / CreativeModeTabModifier extras +modifier.getFlags(); // 获取功能标志 / Get feature flags +modifier.getParameters(); // 获取显示参数 / Get display parameters +modifier.hasPermissions(); // 是否有权限 / Has permissions +modifier.accept(itemLike); // 添加物品 / Add item (default visibility) +modifier.accept(itemLike, TabVisibility); // 添加物品(指定可见性)/ Add item with visibility +``` + +--- + +## 注册监听器管理 / Registration Listener Management + +`OneTimeEventReceiver` 提供了一次性事件监听器机制。 +Provides one-shot event listener mechanism. + +```java +// 添加一次性 mod 总线监听器 / Add one-shot mod bus listener +OneTimeEventReceiver.addModListener(registrate, RegisterEvent.class, event -> { + // 此监听器在第一次触发后自动取消注册 + // This listener auto-unregisters after first fire +}); +``` + +--- + +## 客户端扩展 / Client Extensions + +### 方块客户端扩展 / Block Client Extensions + +```java +REGISTRATE.block("my_block", MyBlock::new) + .clientExtension(() -> () -> new IClientBlockExtensions() { + // 自定义方块客户端行为 / Custom block client behavior + }) + .register(); +``` + +### 物品客户端扩展 / Item Client Extensions + +```java +REGISTRATE.item("my_item", Item::new) + .clientExtension(() -> () -> new IClientItemExtensions() { + // 自定义物品客户端行为 / Custom item client behavior + }) + .register(); +``` + +### 流体客户端扩展 / Fluid Client Extensions + +```java +REGISTRATE.fluid("my_fluid", still, flow, FluidType::new) + .clientExtension(() -> () -> new IClientFluidTypeExtensions() { + // 自定义流体客户端行为 / Custom fluid client behavior + }) + .register(); +``` + +--- + +## 颜色着色 / Color Tinting + +```java +// 方块着色 / Block tinting +REGISTRATE.block("my_block", MyBlock::new) + .color(() -> () -> List.of( + BlockTintSources.constant(0xFFFF0000) // 红色着色 / Red tint + )) + .register(); + +// 物品模型着色(通过 ItemBuilder)/ Item model tinting (via ItemBuilder) +REGISTRATE.item("my_item", Item::new) + .defaultModel(new ItemTintSource("layer0", Constant.create(0xFFFF0000))) + .register(); +``` + +--- + +## 延迟注册 / Deferred Registration + +对于在模组初始化后可能需要延迟解析的对象,可以使用 `NonNullSupplier.lazy()` 创建延迟初始化。 +For objects that need deferred resolution after mod initialisation, use `NonNullSupplier.lazy()`. + +```java +public static final NonNullSupplier REGISTRATE = + NonNullSupplier.lazy(() -> Registrate.create(MOD_ID)); +``` + +--- + +## 跳过错误 / Skipping Errors + +```java +// 在开发环境下跳过注册错误 / Skip registration errors in dev +REGISTRATE.skipErrors(true); +``` + +--- + +## 从现有对象获取条目 / Getting Entries from Existing Objects + +```java +// 从已注册的 Block 获取 BlockEntry +// Get BlockEntry from a registered block +BlockEntry entry = BlockEntry.cast( + registrate.get("existing_block", Registries.BLOCK)); + +// 检查对象是否已注册 +// Check if an object is registered +boolean registered = REGISTRATE.isRegistered(Registries.BLOCK); + +// 获取某注册表中的所有条目 +// Get all entries in a registry +Collection> allBlocks = + REGISTRATE.getAll(Registries.BLOCK); +``` + +--- + +## 注册多个名称相同的条目 / Registering Entries with the Same Name + +```java +// 使用相同的名称在不同注册表中注册不同对象 +// Register different objects with the same name in different registries +REGISTRATE.object("testitem") + .item(Item::new) + .register(); + +REGISTRATE.object("testitem") + .entity(TestEntity::new, MobCategory.CREATURE) + .register(); +``` diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..a7db278 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,90 @@ +# 架构 / Architecture + +## 概述 / Overview + +RegistrateLib 是 Registrate 在 `com.modularmc.registrate` 命名空间下的维护分支,为 ModularMCLib 生态提供流式注册 API,将实现代码分离为注册、生成、运行时支持和测试维护等多个层次。 +RegistrateLib is a maintained fork of Registrate for the `com.modularmc.registrate` namespace. It exposes a fluent registration API while keeping the implementation separated into registration, generation, runtime support, and test-maintenance layers. + +## 包映射 / Package Map + +- `com.modularmc.registrate` + - 公开入口点 / Public entrypoints + - `AbstractRegistrate` 是编排核心 / is the orchestration core + - `Registrate` 是默认的公开实现 / is the default public implementation + - `RegistrateLib` 是 NeoForge 库模组入口点 / is the NeoForge library entrypoint + +- `com.modularmc.registrate.builders` + - 面向用户的流式注册 DSL / Public-facing fluent registration DSL + - 拥有对象构造规则和链式调用行为 / Owns object construction rules and builder chaining behavior + +- `com.modularmc.registrate.providers` + - 数据生成生命周期、提供者注册和分发 / Data generation lifecycle, provider registration, and provider dispatch + +- `com.modularmc.registrate.providers.generators` + - 配方、模型和方块状态的专用适配器 / Specialized adapters for recipes, models, and blockstates + +- `com.modularmc.registrate.providers.loot` + - 战利品表提供者封装与兼容辅助 / Loot-specific provider wrappers and compatibility helpers + +- `com.modularmc.registrate.util` + - 面向下游的共享运行时和数据辅助工具 / Shared downstream-facing runtime and data helpers + +- `com.modularmc.registrate.util.entry` + - 注册返回的强类型句柄 / Strongly-typed handles returned from registrations + +- `com.modularmc.registrate.util.nullness` + - 函数式接口与包级空值约定 / Functional interfaces and package-level nullness conventions + +- `com.modularmc.registrate.internal` + - 从核心提取的非公开状态跟踪器和实现辅助类型 / Non-public state trackers and implementation support types + +- `com.modularmc.registrate.internal.event` + - 用于将构建器回调桥接到 NeoForge mod 总线的一次性事件连接 / One-shot mod event wiring used to bridge builder callbacks onto the NeoForge mod bus + +- `com.modularmc.registrate.internal.lifecycle` + - 实例级生命周期桥接,集中处理 `RegisterEvent`、创造模式标签页和数据生成总线连接 / Per-instance lifecycle bridges that centralize event wiring + +- `com.modularmc.registrate.internal.util` + - 分发限制执行与内部调试日志辅助 / Dist-gated execution and internal debug logging helpers + +- `com.modularmc.registrate.test.mod` + - 用作集成测试的示例模组 / Sample mod used as an integration harness + +- `com.modularmc.registrate.test.gametests` + - 可执行的运行时检查 / Executable runtime checks + +- `com.modularmc.registrate.test.meta` + - 用于生成的桥接方法和受保护 API 快照的维护工具 / Maintenance tooling for generated bridge methods and protected API snapshots + +## 公开 API 边界 / Public API Boundary + +将根包、`builders` 和 `util.entry` 视为面向下游的主要 API 表面。提供者和工具包也是可复用的,但它们主要用于支持 API,而非主要扩展点。 +Treat the root package plus `builders` and `util.entry` as the main downstream-facing API surface. Provider and utility packages are reusable, but most of them exist to support the API rather than to be primary extension points. + +## 放置指南 / Placement Guide + +- 新的注册 DSL 行为放在 `builders` + New registration DSL behavior belongs in `builders` +- 新的数据生成编排放在 `providers` + New datagen orchestration belongs in `providers` +- 生成器专属辅助放在 `providers.generators` 或 `providers.loot` + Generator-specific helpers belong in `providers.generators` or `providers.loot` +- 跨切面的运行时支持,仅当不特定于 builder 或 provider 时才放在 `util` + Cross-cutting runtime support belongs in `util` only when it is not builder- or provider-specific +- 事件总线连接和其他仅实现辅助放在 `internal` + Event-bus plumbing and other implementation-only helpers belong under `internal` +- 实例级 NeoForge 生命周期编排放在 `internal.lifecycle` + Instance-scoped NeoForge lifecycle orchestration belongs in `internal.lifecycle` +- 仅测试用的框架放在 `src/test/java` + Test-only scaffolding belongs under `src/test/java` + +## 现代化原则 / Modernization Principles + +- 偏好明确的包所有权而非便利放置 + Prefer explicit package ownership over convenience placement +- 保持公开入口点小巧,将复杂性推入专注的层次 + Keep public entrypoints small and push complexity into focused layers +- 对下游模组预期集成的扩展点进行文档化 + Document extension points where downstream mods are expected to integrate +- 在此开发分支上,优先采用 26.1 原生结构而非保持遗留兼容性 + Favor 26.1-native structure over preserving legacy compatibility on this dev branch diff --git a/docs/builders.md b/docs/builders.md new file mode 100644 index 0000000..1f350fa --- /dev/null +++ b/docs/builders.md @@ -0,0 +1,331 @@ +# 构建器 API / Builder API + +RegistrateLib 使用**流式构建器模式**(Fluent Builder Pattern)来声明和管理对象注册。每个构建器都提供链式方法调用来配置对象的不同方面,最后通过 `register()` 完成注册。 + +RegistrateLib uses the **Fluent Builder Pattern** to declare and manage object registration. Each builder provides chainable methods to configure different aspects of the object, finalised with `register()`. + +--- + +## 目录 / Table of Contents + +1. [AbstractBuilder —— 所有构建器的基类](#abstractbuilder) +2. [BlockBuilder —— 方块构建器](#blockbuilder) +3. [ItemBuilder —— 物品构建器](#itembuilder) +4. [BlockEntityBuilder —— 方块实体构建器](#blockentitybuilder) +5. [EntityBuilder —— 实体构建器](#entitybuilder) +6. [FluidBuilder —— 流体构建器](#fluidbuilder) +7. [MenuBuilder —— 菜单构建器](#menubuilder) + +--- + +## AbstractBuilder + +所有构建器的抽象基类,提供通用的构建器方法。 +Abstract base class for all builders, providing common builder methods. + +```java +public abstract class AbstractBuilder> +``` + +### 通用方法 / Common Methods + +| 方法 / Method | 描述 / Description | +|--------------------------------------------|-----------------------------------------------------------------------------------------------| +| `register()` | 完成注册,返回对应的 `RegistryEntry` / Finalise registration, returns the corresponding `RegistryEntry` | +| `tag(ProviderType, TagKey...)` | 为对象添加标签(通用版)/ Add tags to the object (generic) | +| `removeTag(ProviderType, TagKey...)` | 移除对象的标签 / Remove tags from the object | +| `lang(NonNullFunction, String)` | 设置自定义语言键 / Set a custom lang key | +| `asOptional()` | 将此构建器标记为可选的 / Mark this builder as optional | +| `getResourceKey()` | 获取此构建器创建的资源的 `ResourceKey` / Get the `ResourceKey` for the resource | + +### Builder 接口方法 / Builder Interface Methods + +以下方法在 `Builder` 接口中定义,对所有构建器可用: +These methods are defined in the `Builder` interface and available on all builders: + +| 方法 / Method | 描述 / Description | +|-------------------------------------------------|------------------------------------------------------------------------| +| `setData(GeneratorType, NonNullBiConsumer)` | 为此对象设置数据生成器 / Set a data generator for this object | +| `removeData(GeneratorType)` | 移除数据生成器 / Remove a data generator | +| `addMiscData(GeneratorType, NonNullConsumer)` | 添加全局数据生成器 / Add a global data generator | +| `dataMap(DataMapType, ...)` | 为此对象添加数据映射 / Add a data map value | +| `onRegister(NonNullConsumer)` | 注册完成时的回调 / Callback when registration completes | +| `onRegisterAfter(ResourceKey, NonNullConsumer)` | 在指定注册表注册完成后的回调 / Callback after another registry finishes registration | +| `transform(NonNullFunction)` | 对构建器应用变换函数 / Apply a transform function to the builder | +| `build()` | 返回父构建器(用于嵌套构建器链)/ Return to parent builder | + +--- + +## BlockBuilder + +用于注册方块。 +Used for registering blocks. + +```java +public class BlockBuilder + extends AbstractBuilder> +``` + +### 创建 / Creation + +```java +// 由 Registrate 的 block() 方法创建 / Created via Registrate's block() method +registrate.block("my_block", MyBlock::new) +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| +| `properties(NonNullUnaryOperator)` | 修改方块属性 / Modify block properties | +| `initialProperties(NonNullSupplier)` | 从现有方块复制初始属性 / Copy initial properties from an existing block | +| `simpleItem()` | 自动创建一个默认的 BlockItem / Automatically create a default BlockItem | +| `item()` | 返回 `ItemBuilder>`,用于自定义 BlockItem / Return ItemBuilder for custom BlockItem | +| `item(NonNullBiFunction)` | 使用自定义工厂创建 BlockItem / Create BlockItem with a custom factory | +| `simpleBlockEntity(BlockEntityFactory)` | 快速创建没有额外配置的方块实体 / Quickly create a block entity without extra configuration | +| `blockEntity(BlockEntityFactory)` | 返回 `BlockEntityBuilder` 用于完全配置方块实体 / Return BlockEntityBuilder for full BE configuration | +| `color(NonNullSupplier>>)` | 设置方块着色器 / Set block tint sources | +| `defaultBlockstate()` | 使用默认方块状态生成 / Use default blockstate generation | +| `blockstate(NonNullSupplier)` | 自定义方块状态生成 / Custom blockstate generation | +| `defaultLang()` | 自动生成语言条目 / Auto-generate lang entry | +| `lang(String)` | 自定义语言名称 / Custom lang name | +| `defaultLoot()` | 使用默认战利品表生成 / Use default loot table generation | +| `loot(NonNullBiConsumer)` | 自定义战利品表生成 / Custom loot table generation | +| `recipe(NonNullBiConsumer)` | 添加配方生成 / Add recipe generation | +| `clientExtension(NonNullSupplier>)` | 添加客户端扩展 / Add client block extensions | +| `tag(TagKey...)` | 添加方块标签 / Add block tags | +| `register()` | 返回 `BlockEntry` / Returns `BlockEntry` | + +### 示例 / Example + +```java +public static final BlockEntry MY_STAIRS = REGISTRATE + .block("my_stairs", MyStairsBlock::new) + .defaultItem() // 或 .item() 进行自定义 / or .item() for custom + .tag(BlockTags.STAIRS) + .blockstate(ctx -> ctx.getProvider() + .stairsBlock(ctx.getEntry(), ctx.getProvider().modLoc(ctx.getName()))) + .lang("Special Stairs") + .register(); +``` + +--- + +## ItemBuilder + +用于注册物品。 +Used for registering items. + +```java +public class ItemBuilder + extends AbstractBuilder> +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|---------------------------------------------------------------------|--------------------------------------------| +| `properties(NonNullUnaryOperator)` | 修改物品属性 / Modify item properties | +| `initialProperties(NonNullSupplier)` | 使用初始属性 / Use initial properties | +| `tab(ResourceKey, ...)` | 添加到创造模式标签页 / Add to creative mode tab | +| `removeTab(ResourceKey)` | 从标签页移除 / Remove from tab | +| `defaultModel()` | 使用默认物品模型 / Use default item model | +| `model(NonNullSupplier)` | 自定义物品模型 / Custom item model | +| `defaultLang()` | 自动生成语言条目 / Auto-generate lang entry | +| `lang(String)` | 自定义语言名称 / Custom lang name | +| `recipe(NonNullBiConsumer)` | 添加配方生成 / Add recipe | +| `burnTime(int)` | 设置燃料燃烧时间(tick)/ Set fuel burn time (ticks) | +| `compostable(float)` | 设置堆肥机概率 / Set composter chance | +| `clientExtension(NonNullSupplier>)` | 添加客户端扩展 / Add client item extensions | +| `tag(TagKey...)` | 添加物品标签 / Add item tags | +| `register()` | 返回 `ItemEntry` / Returns `ItemEntry` | + +### 示例 / Example + +```java +public static final ItemEntry MY_ITEM = REGISTRATE + .item("my_item", Item::new) + .properties(p -> p.food(new FoodProperties.Builder() + .nutrition(4).saturationModifier(0.5f).build())) + .tag(ItemTags.FOOD) + .tab(MyMod.CREATIVE_TAB) + .register(); +``` + +--- + +## BlockEntityBuilder + +用于注册方块实体。 +Used for registering block entities. + +```java +public class BlockEntityBuilder + extends AbstractBuilder, BlockEntityType, P, BlockEntityBuilder> +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|-----------------------------------------------------------|----------------------------------------------------------| +| `validBlock(NonNullSupplier)` | 为此方块实体关联一个有效方块 / Associate a valid block with this BE | +| `validBlocks(NonNullSupplier...)` | 关联多个有效方块 / Associate multiple valid blocks | +| `renderer(NonNullSupplier)` | 设置方块实体渲染器 / Set block entity renderer | +| `registerCapability(Consumer)` | 注册能力(Capability)/ Register capabilities | +| `register()` | 返回 `BlockEntityEntry` / Returns `BlockEntityEntry` | + +### 示例 / Example + +```java +public static final BlockEntityEntry MY_BE = REGISTRATE + .blockEntity("my_be", MyBlockEntity::new) + .validBlock(() -> MyMod.MY_BLOCK) + .renderer(() -> MyBERenderer::new) + .register(); +``` + +--- + +## EntityBuilder + +用于注册实体。 +Used for registering entities. + +```java +public class EntityBuilder + extends AbstractBuilder, EntityType, P, EntityBuilder> +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|----------------------------------------------------------------------------------|------------------------------------------------| +| `properties(NonNullConsumer>)` | 修改实体类型属性 / Modify entity type properties | +| `renderer(NonNullSupplier)` | 设置实体渲染器 / Set entity renderer | +| `attributes(Supplier)` | 设置实体属性 / Set entity attributes | +| `spawnPlacement(SpawnPlacementType, Heightmap.Types, SpawnPredicate, Operation)` | 设置生成放置规则 / Set spawn placement rules | +| `spawnEgg()` | 自动生成刷怪蛋 / Auto-generate spawn egg | +| `spawnEgg(NonNullConsumer)` | 自定义刷怪蛋 / Custom spawn egg | +| `defaultLang()` | 自动生成语言条目 / Auto-generate lang entry | +| `lang(String)` | 自定义语言名称 / Custom lang name | +| `loot(NonNullBiConsumer)` | 自定义战利品表 / Custom loot table | +| `tag(TagKey>...)` | 添加实体标签 / Add entity type tags | +| `register()` | 返回 `EntityEntry` / Returns `EntityEntry` | + +### 示例 / Example + +```java +public static final EntityEntry MY_ENTITY = REGISTRATE + .entity("my_entity", MyEntity::new, MobCategory.CREATURE) + .attributes(MyEntity::createAttributes) + .renderer(() -> MyEntityRenderer::new) + .spawnEgg() + .spawnPlacement(SpawnPlacementTypes.ON_GROUND, + Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, + Animal::checkAnimalSpawnRules, + RegisterSpawnPlacementsEvent.Operation.OR) + .loot((prov, type) -> prov.add(type, LootTable.lootTable() + .withPool(LootPool.lootPool() + .add(LootItem.lootTableItem(Items.DIAMOND))))) + .register(); +``` + +--- + +## FluidBuilder + +用于注册流体。 +Used for registering fluids. + +```java +public class FluidBuilder + extends AbstractBuilder> +``` + +### 创建 / Creation + +```java +// 基本创建(默认 FluidType)/ Basic creation (default FluidType) +registrate.fluid("my_fluid", + Identifier.of("minecraft:block/water_still"), + Identifier.of("minecraft:block/water_flow"), + FluidType::new) +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|-----------------------------------------------------------------|----------------------------------------------------------------| +| `properties(NonNullConsumer)` | 修改流体类型属性 / Modify fluid type properties | +| `fluidProperties(NonNullConsumer)` | 修改流体属性 / Modify fluid properties | +| `defaultLang()` | 自动生成语言条目 / Auto-generate lang entry | +| `lang(String)` | 自定义语言名称 / Custom lang name | +| `defaultSource()` | 使用默认流体源 / Use default fluid source | +| `source(NonNullFunction)` | 自定义流体源 / Custom fluid source | +| `defaultBlock()` | 自动生成流体方块 / Auto-generate fluid block | +| `block()` | 返回 `BlockBuilder` 配置流体方块 / Return BlockBuilder for fluid block | +| `block(NonNullBiFunction)` | 使用自定义工厂创建流体方块 / Custom fluid block factory | +| `noBlock()` | 不生成流体方块 / Skip fluid block generation | +| `defaultBucket()` | 自动生成流体桶 / Auto-generate fluid bucket | +| `bucket()` | 返回 `ItemBuilder` 配置流体桶 / Return ItemBuilder for bucket | +| `bucket(NonNullBiFunction)` | 自定义桶 / Custom bucket | +| `noBucket()` | 不生成桶 / Skip bucket generation | +| `model(Identifier, Identifier)` | 设置静态和流动纹理 / Set still and flowing textures | +| `model(NonNullSupplier)` | 自定义模型 / Custom model | +| `clientExtension(NonNullSupplier)` | 添加客户端流体类型扩展 / Add client fluid type extensions | +| `tag(TagKey...)` | 添加流体标签 / Add fluid tags | +| `removeTag(TagKey...)` | 移除流体标签 / Remove fluid tags | +| `register()` | 返回 `FluidEntry` / Returns `FluidEntry` | + +### 示例 / Example + +```java +public static final FluidEntry MY_FLUID = REGISTRATE + .fluid("my_fluid", + Identifier.of("minecraft:block/water_still"), + Identifier.of("minecraft:block/water_flow"), + FluidType::new) + .properties(p -> p.lightLevel(15).canConvertToSource(true)) + .register(); +``` + +--- + +## MenuBuilder + +用于注册菜单(容器界面)。 +Used for registering menus (container screens). + +```java +public class MenuBuilder, P> + extends AbstractBuilder, MenuType, P, MenuBuilder> +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|--------------|--------------------------------------------| +| `register()` | 返回 `MenuEntry` / Returns `MenuEntry` | + +### 工厂接口 / Factory Interfaces + +```java +// 标准菜单工厂 / Standard menu factory +MenuFactory // (type, windowId, inv) -> T + +// Forge 扩展菜单工厂(支持缓冲区)/ Forge extended menu factory (with buffer) +ForgeMenuFactory // (type, windowId, inv, buffer) -> T + +// 屏幕工厂 / Screen factory +ScreenFactory // (menu, inv, displayName) -> S +``` + +### 示例 / Example + +```java +public static final MenuEntry MY_MENU = REGISTRATE + .menu("my_menu", + (type, windowId, inv) -> new ChestMenu(type, windowId, inv, new SimpleContainer(9), 9), + () -> ContainerScreen::new) + .register(); +``` diff --git a/docs/entries.md b/docs/entries.md new file mode 100644 index 0000000..9fbb5c8 --- /dev/null +++ b/docs/entries.md @@ -0,0 +1,262 @@ +# 注册条目 / Registry Entries + +当构建器调用 `register()` 后,会返回一个强类型的 `RegistryEntry` 句柄。这些条目提供了类型安全的方式来引用和使用已注册的对象。 + +When a builder's `register()` is called, it returns a strongly-typed `RegistryEntry` handle. These entries provide a type-safe way to reference and use registered objects. + +--- + +## RegistryEntry —— 基础条目 / Base Entry + +所有注册条目的基类。 +Base class for all registry entries. + +```java +public class RegistryEntry extends DeferredHolder + implements NonNullSupplier +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|---------------------------|------------------------------------------------------------------| +| `get()` | 获取注册对象(继承自 `NonNullSupplier`)/ Get the registered object | +| `getSibling(ResourceKey)` | 按注册表键获取兄弟条目(如方块获取其 BlockItem)/ Get sibling entry by registry key | +| `getSibling(Registry)` | 按注册表实例获取兄弟条目 / Get sibling entry by registry instance | +| `getSiblingOptional(...)` | 获取可选的兄弟条目 / Get optional sibling entry | +| `filter(Predicate)` | 按谓词过滤条目 / Filter entry by predicate | +| `is(Object)` | 检查条目是否等于给定对象 / Check if entry equals given object | + +### 兄弟条目示例 / Sibling Example + +```java +// 从方块获取其 BlockItem 条目 +// Get BlockItem entry from a block +ItemEntry blockItem = ItemEntry.cast( + MY_BLOCK.getSibling(Registries.ITEM)); + +// 从方块获取其方块实体条目 +// Get BE entry from a block +BlockEntityEntry be = BlockEntityEntry.cast( + MY_BLOCK.getSibling(Registries.BLOCK_ENTITY_TYPE)); +``` + +--- + +## ItemProviderEntry —— 可提供物品的条目 / Item-able Entry + +`BlockEntry` 和 `ItemEntry` 的基类,实现了 `ItemLike`。 +Base class for `BlockEntry` and `ItemEntry`, implements `ItemLike`. + +```java +public class ItemProviderEntry + extends RegistryEntry implements ItemLike +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|---------------------|-------------------------------------------------------------------------| +| `asStack()` | 创建包含此物品的 `ItemStack`(数量 1)/ Create an ItemStack (count 1) | +| `asStack(int)` | 创建指定数量的 `ItemStack` / Create an ItemStack with specified count | +| `asStackTemplate()` | 创建 `ItemStackTemplate`(用于配方)/ Create an ItemStackTemplate (for recipes) | +| `isIn(ItemStack)` | 检查物品栈是否包含此物品 / Check if a stack contains this item | +| `is(Item)` | 检查是否特定物品 / Check if specific item | +| `asItem()` | 获取 `Item` 对象 / Get the Item object | + +--- + +## BlockEntry —— 方块条目 / Block Entry + +```java +public class BlockEntry extends ItemProviderEntry +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|-----------------------|------------------------------------------------------| +| `getDefaultState()` | 获取默认方块状态 / Get default block state | +| `has(BlockState)` | 检查方块状态是否属于此方块 / Check if state belongs to this block | +| `cast(RegistryEntry)` | 静态转换方法 / Static cast method | + +### 示例 / Example + +```java +public static final BlockEntry MY_BLOCK = REGISTRATE + .block("my_block", MyBlock::new).simpleItem().register(); + +// 使用 / Usage +BlockState state = MY_BLOCK.getDefaultState(); +ItemStack stack = MY_BLOCK.asStack(); +boolean isMyBlock = MY_BLOCK.has(someState); +``` + +--- + +## ItemEntry —— 物品条目 / Item Entry + +```java +public class ItemEntry extends ItemProviderEntry +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|-----------------------|-----------------------------| +| `cast(RegistryEntry)` | 静态转换方法 / Static cast method | + +### 示例 / Example + +```java +public static final ItemEntry MY_ITEM = REGISTRATE + .item("my_item", Item::new).register(); + +// 使用 / Usage +ItemStack stack = MY_ITEM.asStack(64); +boolean isFood = MY_ITEM.is(Items.APPLE); +``` + +--- + +## BlockEntityEntry —— 方块实体条目 / Block Entity Entry + +```java +public class BlockEntityEntry + extends RegistryEntry, BlockEntityType> +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|--------------------------------------|-----------------------------------------------------| +| `create(BlockPos, BlockState)` | 在指定位置创建方块实体实例 / Create a BE instance at a position | +| `is(BlockEntity)` | 检查方块实体是否属于此类型 / Check if BE is of this type | +| `get(BlockGetter, BlockPos)` | 从世界中获取可选的方块实体实例 / Get optional BE from world | +| `getNullable(BlockGetter, BlockPos)` | 从世界中获取可能为 null 的方块实体实例 / Get nullable BE from world | +| `cast(RegistryEntry)` | 静态转换方法 / Static cast method | + +### 示例 / Example + +```java +// 获取世界中的方块实体 +// Get BE in world +Optional be = MY_BE.get(level, pos); + +// 创建新实例 +// Create new instance +MyBE newBe = MY_BE.create(pos, state); +``` + +--- + +## EntityEntry —— 实体条目 / Entity Entry + +```java +public class EntityEntry + extends RegistryEntry, EntityType> +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|------------------------------------|-----------------------------------------------| +| `create(Level, EntitySpawnReason)` | 创建实体实例 / Create an entity instance | +| `is(Entity)` | 检查实体是否属于此类型 / Check if entity is of this type | +| `cast(RegistryEntry)` | 静态转换方法 / Static cast method | + +### 示例 / Example + +```java +// 生成实体 +// Spawn entity +MyEntity entity = MY_ENTITY.create(level, EntitySpawnReason.SPAWN_EGG); +entity.setPos(x, y, z); +level.addFreshEntity(entity); +``` + +--- + +## FluidEntry —— 流体条目 / Fluid Entry + +```java +public class FluidEntry + extends RegistryEntry +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|---------------|----------------------------------------------------------------------------| +| `is(Object)` | 使用 `Fluid.isSame()` 检查流体是否相同 / Check fluid equality using `Fluid.isSame()` | +| `getSource()` | 获取此流体的源变体 / Get the source variant of this fluid | +| `getType()` | 获取 `FluidType` / Get the `FluidType` | +| `getBlock()` | 获取流体方块(如存在) / Get the fluid block (if present) | +| `getBucket()` | 获取流体桶物品(如存在) / Get the bucket item (if present) | + +### 示例 / Example + +```java +public static final FluidEntry MY_FLUID = REGISTRATE + .fluid("my_fluid", still, flow, FluidType::new).register(); + +// 使用 / Usage +Fluid source = MY_FLUID.getSource(); +Optional block = MY_FLUID.getBlock(); +Optional bucket = MY_FLUID.getBucket(); +boolean isSame = MY_FLUID.is(otherFluid); +``` + +--- + +## MenuEntry —— 菜单条目 / Menu Entry + +```java +public class MenuEntry + extends RegistryEntry, MenuType> +``` + +### 方法 / Methods + +| 方法 / Method | 描述 / Description | +|--------------------------------------------------------------------|------------------------------------------------------| +| `create(int, Inventory)` | 创建菜单实例 / Create a menu instance | +| `asProvider()` | 获取 `MenuConstructor` / Get a `MenuConstructor` | +| `open(ServerPlayer, Component)` | 为玩家打开菜单 / Open the menu for a player | +| `open(ServerPlayer, Component, Consumer)` | 打开菜单并传递额外数据 / Open menu with extra data | +| `open(ServerPlayer, Component, MenuConstructor)` | 使用自定义提供者打开菜单 / Open with custom provider | +| `open(ServerPlayer, Component, MenuConstructor, Consumer)` | 使用自定义提供者和数据打开菜单 / Open with custom provider and data | + +### 示例 / Example + +```java +// 在服务器端为玩家打开菜单 +// Open menu for a player on the server side +MY_MENU.open(player, Component.literal("My Menu")); + +// 带额外数据 +// With extra data +MY_MENU.open(player, Component.literal("My Menu"), buf -> { + buf.writeUtf("extra data"); +}); +``` + +--- + +## LazyRegistryEntry —— 延迟解析条目 / Lazy Entry + +用于需要延迟解析注册条目的场景,避免在类加载阶段提前触发注册。 +Used when registry entry resolution needs to be deferred to avoid triggering registration early during class loading. + +```java +public class LazyRegistryEntry implements NonNullSupplier +``` + +### 构造 / Construction + +```java +LazyRegistryEntry<>(NonNullSupplier> supplier) +``` + +解析一次后缓存结果,并释放 supplier 引用以允许 GC。 +Resolves once, caches the result, and releases the supplier reference for GC. diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..13405d3 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,101 @@ +# 快速入门 / Getting Started + +## 安装 / Installation + +### 1. 添加依赖 / Add Dependency + +在 `build.gradle` 中添加: +Add to your `build.gradle`: + +```groovy +dependencies { + implementation "com.modularmc.registrate:registratelib:${registratelib_version}" +} +``` + +### 2. 声明依赖 / Declare Dependency + +在 `neoforge.mods.toml` 中添加: +Add to your `neoforge.mods.toml`: + +```toml +[[dependencies.yourmodid]] +modId="registratelib" +type="required" +versionRange="[2.0.0,)" +ordering="AFTER" +side="BOTH" +``` + +## 创建 Registrate 实例 / Creating a Registrate Instance + +在你的主模组类中创建一个 `Registrate` 对象: +Create a `Registrate` object in your main mod class: + +```java +@Mod(MyMod.MOD_ID) +public class MyMod { + public static final String MOD_ID = "mymod"; + + // 简单方式(注意:需确保不在构造之前访问) + // Simple approach (ensure it's not accessed before construction) + public static final Registrate REGISTRATE = Registrate.create(MOD_ID); + + public MyMod(IEventBus modEventBus) { + // 在此处注册事件监听器 + // Register event listeners here + } +} +``` + +### 延迟初始化 / Lazy Initialization + +如果需要延迟初始化(避免在类加载阶段过早创建): +If you need lazy initialization to avoid creating too early during class loading: + +```java +public static final NonNullSupplier REGISTRATE = + NonNullSupplier.lazy(() -> Registrate.create(MOD_ID)); +``` + +## 注册你的第一个对象 / Registering Your First Object + +### 方块 / Block + +```java +public static final BlockEntry MY_BLOCK = REGISTRATE + .block("my_block", Block::new) + .simpleItem() // 自动创建 BlockItem / Automatically create a BlockItem + .defaultBlockstate() // 使用默认方块状态 / Use default blockstate + .defaultLang() // 自动生成语言条目 / Auto-generate lang entry + .defaultLoot() // 自动生成战利品表 / Auto-generate loot table + .register(); // 完成注册 / Finalize registration +``` + +### 物品 / Item + +```java +public static final ItemEntry MY_ITEM = REGISTRATE + .item("my_item", Item::new) + .defaultModel() // 使用默认模型 / Use default model + .defaultLang() // 自动生成语言条目 / Auto-generate lang entry + .register(); +``` + +### 方块实体 / Block Entity + +```java +public static final BlockEntityEntry MY_BE = REGISTRATE + .blockEntity("my_block_entity", MyBlockEntity::new) + .validBlock(() -> MyMod.MY_BLOCK) // 关联有效方块 / Associate valid block + .register(); +``` + +## 下一步 / Next Steps + +- 探索[构建器 API](builders.md) 了解所有可用的构建器和方法 + Explore the [builder API](builders.md) for all available builders and methods +- 查看[注册条目](entries.md)了解如何使用注册后的句柄 + Check [registry entries](entries.md) for how to use the registered handles +- 阅读[数据提供者](providers.md)了解自动数据生成系统 + Read about [data providers](providers.md) for the automatic data generation system diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..e46d845 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,45 @@ +# RegistrateLib 维基 / Wiki + +## 什么是 RegistrateLib? / What is RegistrateLib? + +RegistrateLib 是一个强大的流式注册 API 封装,用于在 NeoForge 模组中创建和注册对象。它提供了一套流畅的链式调用 API,让你能够以声明式的方式组织模组内容,并自动处理数据生成、本地化和标签管理。 + +RegistrateLib is a powerful fluent registration API wrapper for creating and registering objects in NeoForge mods. It provides a smooth chain-call API that lets you organize mod content declaratively, with automatic data generation, localization, and tag management. + +## 功能特性 / Features + +- **流畅的流式 API** — 链式调用构建器,以声明式方式定义对象及其行为 / Chain-call builders for declarative object definition +- **自动数据生成** — 自动为方块、物品、流体等生成模型、方块状态、战利品表和配方 / Automatic model, blockstate, loot table, and recipe generation +- **智能本地化** — 自动为注册对象生成语言条目 / Automatic lang entry generation for registered objects +- **标签管理** — 链式 API 中直接支持方块、物品、流体和实体标签 / Built-in tag support for blocks, items, fluids, and entities +- **自定义注册表** — 支持创建自定义注册表和数据包注册表 / Custom registry and datapack registry creation +- **创造模式标签页** — 轻松将物品分配到创造模式标签页 / Easy creative mode tab assignment + +## 快速开始 / Quick Start + +```java +// 创建 Registrate 实例 / Create a Registrate instance +public static final Registrate REGISTRATE = Registrate.create(MOD_ID); + +// 注册一个简单的方块 / Register a simple block +public static final BlockEntry MY_BLOCK = REGISTRATE.block("my_block", Block::new) + .simpleItem() + .register(); + +// 注册一个物品 / Register an item +public static final ItemEntry MY_ITEM = REGISTRATE.item("my_item", Item::new) + .register(); +``` + +## 文档目录 / Table of Contents + +1. [快速入门](getting-started.md) — 安装、设置和你的第一个注册 / Installation, setup, and your first registration +2. [构建器 API](builders.md) — 所有构建器的详细 API 参考 / Detailed builder API reference +3. [注册条目](entries.md) — 注册返回的强类型句柄 / Strongly-typed registry entry handles +4. [数据提供者](providers.md) — 数据生成系统详解 / Data generation system in detail +5. [高级用法](advanced.md) — 自定义注册表、生命周期钩子等 / Custom registries, lifecycle hooks, and more + +## 架构概述 / Architecture Overview + +详细信息请查阅 [architecture.md](architecture.md)。 +See [architecture.md](architecture.md) for package responsibilities and extension points. diff --git a/docs/providers.md b/docs/providers.md new file mode 100644 index 0000000..e7a8970 --- /dev/null +++ b/docs/providers.md @@ -0,0 +1,272 @@ +# 数据提供者 / Data Providers + +RegistrateLib 内置了自动数据生成系统。当你通过构建器注册对象时,它会自动收集数据生成任务,并在数据生成运行时统一输出。 + +RegistrateLib has a built-in automatic data generation system. When you register objects through builders, it automatically collects data generation tasks and outputs them uniformly during datagen runs. + +--- + +## 提供者类型 / Provider Types + +### 服务端提供者 / Server Providers + +| 类型 / Type | 类 / Class | 描述 / Description | +|--------------------|-------------------------------------------------------|----------------------------------------| +| `DYNAMIC` | `RegistrateDatapackProvider` | 动态数据包注册表 / Dynamic datapack registries | +| `DATA_MAP` | `RegistrateDataMapProvider` | 数据映射 / Data maps | +| `RECIPE_RUNNER` | `RegistrateRecipeRunner` | 配方(入口点)/ Recipes (entry point) | +| `ADVANCEMENT` | `RegistrateAdvancementProvider` | 进度 / Advancements | +| `LOOT` | `RegistrateLootTableProvider` | 战利品表 / Loot tables | +| `BLOCK_TAGS` | `RegistrateTagsProvider.IntrinsicImpl` | 方块标签 / Block tags | +| `ITEM_TAGS` | `RegistrateItemTagsProvider` | 物品标签 / Item tags | +| `FLUID_TAGS` | `RegistrateTagsProvider.IntrinsicImpl` | 流体标签 / Fluid tags | +| `ENTITY_TAGS` | `RegistrateTagsProvider.IntrinsicImpl>` | 实体标签 / Entity type tags | +| `ENCHANTMENT_TAGS` | `RegistrateTagsProvider.Impl` | 附魔标签 / Enchantment tags | +| `GENERIC_SERVER` | `RegistrateGenericProvider` | 通用服务端提供者 / Generic server provider | + +### 客户端提供者 / Client Providers + +| 类型 / Type | 类 / Class | 描述 / Description | +|------------------|-----------------------------|------------------------------------| +| `MODEL` | `RegistrateModelProvider` | 模型和方块状态 / Models & blockstates | +| `LANG` | `RegistrateLangProvider` | 语言文件(en_us + en_ud)/ Lang files | +| `GENERIC_CLIENT` | `RegistrateGenericProvider` | 通用客户端提供者 / Generic client provider | + +--- + +## 子生成器类型 / Sub-generator Types + +这些是更细粒度的生成器键,通常用于构建器的 `setData()` 方法。 +These are finer-grained generator keys, typically used in builder `.setData()`. + +| 生成器 / Generator | 所属提供者 / Parent Provider | 用途 / Purpose | +|-----------------|-------------------------|------------------------------------------------| +| `RECIPE` | `RECIPE_RUNNER` | 单个对象的配方生成 / Per-object recipe generation | +| `BLOCKSTATE` | `MODEL` | 单个对象的方块状态生成 / Per-object blockstate generation | +| `ITEM_MODEL` | `MODEL` | 单个对象的物品模型生成 / Per-object item model generation | + +--- + +## 构建器中集成数据生成 / Data Generation in Builders + +大多数构建器提供了直接的方法来配置数据生成: +Most builders provide direct methods to configure data generation: + +```java +// 方块 — 方块状态、模型、战利品、配方、语言 +// Block — blockstate, model, loot, recipe, lang +REGISTRATE.block("my_block", MyBlock::new) + .blockstate(ctx -> { /* ... */ }) // 方块状态 / blockstate + .loot((prov, block) -> { /* ... */ }) // 战利品表 / loot + .recipe((ctx, prov) -> { /* ... */ }) // 配方 / recipe + .lang("My Block") // 语言 / lang + .defaultBlockstate() // 使用默认值 / use defaults + .defaultLoot() + .register(); +``` + +--- + +## RegistrateLangProvider —— 语言提供者 / Lang Provider + +自动生成 `en_us` 和 `en_ud`(上下颠倒)语言文件。 +Automatically generates `en_us` and `en_ud` (upside-down) lang files. + +```java +// 通过 Registrate 添加语言条目 / Add lang entries via Registrate +REGISTRATE.addRawLang("key", "value"); // 原始语言键 / raw lang key +REGISTRATE.addLang("tooltip", blockId, "My Tooltip"); // 工具提示 / tooltip +REGISTRATE.addLang("item", itemId, "suffix", "Name"); // 带后缀的物品名称 / item name with suffix + +// 从构建器自动生成 / Auto-generated from builders +// 调用 .defaultLang() 或 .lang("name") 即可 / call .defaultLang() or .lang("name") +``` + +### 手动使用 / Manual Usage + +```java +// 直接访问语言提供者 / Access the lang provider directly +REGISTRATE.addDataGenerator(ProviderType.LANG, provider -> { + provider.addBlock(MY_BLOCK); + provider.addItem(MY_ITEM); + provider.addBlockWithTooltip(MY_BLOCK, "block.mymod.my_block", "A wonderful block"); +}); +``` + +--- + +## RegistrateTagsProvider —— 标签提供者 / Tag Provider + +标签管理可以通过构建器链式调用或在数据生成器中手动完成。 +Tag management can be done via builder chaining or manually in data generators. + +### 通过构建器 / Via Builders + +```java +REGISTRATE.block("my_block", Block::new) + .tag(BlockTags.STAIRS, BlockTags.DRAGON_IMMUNE) + .tag(BlockTags.WITHER_IMMUNE) + .register(); + +REGISTRATE.item("my_item", Item::new) + .tag(ItemTags.BEDS) + .register(); +``` + +### 手动使用 / Manual Usage + +```java +REGISTRATE.addDataGenerator(ProviderType.ITEM_TAGS, provider -> { + provider.tag(ItemTags.STAIRS) + .add(MY_BLOCK.getKey()); +}); +``` + +### 复制方块标签到物品标签 / Copy Block Tags to Item Tags + +```java +// ItemTagsProvider 支持从方块标签复制到物品标签 +// ItemTagsProvider supports copying block tags to item tags +REGISTRATE.addDataGenerator(ProviderType.ITEM_TAGS, provider -> { + provider.copy(BlockTags.STAIRS, ItemTags.STAIRS); +}); +``` + +--- + +## RegistrateRecipeProvider —— 配方提供者 / Recipe Provider + +在构建器中通过 `.recipe()` 添加配方: +Add recipes in builders via `.recipe()`: + +```java +REGISTRATE.block("my_block", MyBlock::new) + .recipe((ctx, prov) -> { + prov.shaped(RecipeCategory.MISC, ctx.getEntry()) + .pattern("DDD").pattern("DED").pattern("DDD") + .define('D', Items.DIAMOND) + .define('E', Items.EGG) + .unlockedBy("has_egg", prov.has(Items.EGG)) + .save(prov); + + prov.food(DataIngredient.items(ctx), RecipeCategory.MISC, + CookingBookCategory.MISC, () -> Blocks.DIAMOND_BLOCK, 1f); + }) + .register(); +``` + +### 便捷方法 / Convenience Methods + +| 方法 / Method | 描述 / Description | +|--------------------------------------------------------------------|-----------------------------------------------| +| `smelting(DataIngredient, RecipeCategory, NonNullSupplier, float)` | 烧炼配方 / Smelting recipe | +| `blasting(...)` | 高炉配方 / Blasting recipe | +| `smoking(...)` | 烟熏配方 / Smoking recipe | +| `campfire(...)` | 营火配方 / Campfire recipe | +| `stonecutting(...)` | 切石机配方 / Stonecutting recipe | +| `smeltingAndBlasting(...)` | 同时生成烧炼和高炉配方 / Both smelting & blasting | +| `food(...)` | 食物配方(烧炼)/ Food cooking recipe | +| `storage(...)` | 存储压缩配方(3x3 或 2x2)/ Storage compression recipe | +| `singleItem(...)` | 单物品配方 / Single item recipe | +| `planks(...)` | 木板配方 / Planks recipe | +| `stairs(...)` | 楼梯配方 / Stairs recipe | +| `slab(...)` | 台阶配方 / Slab recipe | +| `fence(...)` | 栅栏配方 / Fence recipe | +| `fenceGate(...)` | 栅栏门配方 / Fence gate recipe | +| `wall(...)` | 墙配方 / Wall recipe | +| `door(...)` | 门配方 / Door recipe | +| `trapDoor(...)` | 活板门配方 / Trapdoor recipe | + +--- + +## RegistrateLootTableProvider —— 战利品表提供者 / Loot Table Provider + +### 通过构建器 / Via Builders + +```java +REGISTRATE.block("my_block", MyBlock::new) + .loot((prov, block) -> { + prov.dropOther(block, Items.DIAMOND); + }) + .register(); + +REGISTRATE.entity("my_entity", MyEntity::new, MobCategory.CREATURE) + .loot((prov, type) -> { + prov.add(type, LootTable.lootTable() + .withPool(LootPool.lootPool() + .add(LootItem.lootTableItem(Items.DIAMOND) + .apply(SetItemCountFunction.setCount( + UniformGenerator.between(1, 3)))))); + }) + .register(); +``` + +### 可用方法 / Available Methods + +从 `RegistrateBlockLootTables`(继承自 `BlockLootSubProvider`): +From `RegistrateBlockLootTables` (extends `BlockLootSubProvider`): + +| 方法 / Method | 描述 / Description | +|---------------------------------------|----------------------------------------| +| `dropSelf(Block)` | 掉落自身 / Drop itself | +| `dropOther(Block, ItemLike)` | 掉落其他物品 / Drop other item | +| `createSingleItemTable(ItemLike)` | 单物品掉落表 / Single item drop table | +| `createSilkTouchDispatchTable(Block)` | 精准采集掉落表 / Silk touch drop table | +| `createSlabItemTable(Block)` | 台阶掉落表(保证掉落 2 个)/ Slab drop table | +| `createDoorTable(Block)` | 门掉落表 / Door drop table | +| `createOreDrop(Block, ItemLike)` | 矿石掉落 + 精准采集 / Ore drop with silk touch | + +--- + +## RegistrateAdvancementProvider —— 进度提供者 / Advancement Provider + +```java +REGISTRATE.addDataGenerator(ProviderType.ADVANCEMENT, adv -> { + Advancement.Builder.advancement() + .addCriterion("has_egg", + InventoryChangeTrigger.TriggerInstance.hasItems(Items.EGG)) + .display(Items.EGG, + adv.title(MOD_ID, "root", "Test Advancement"), + adv.desc(MOD_ID, "root", "Get an egg."), + Identifier.withDefaultNamespace( + "textures/gui/advancements/backgrounds/stone.png"), + AdvancementType.TASK, true, true, false) + .save(adv, MOD_ID + ":root"); +}); +``` + +--- + +## RegistrateGenericProvider —— 通用提供者 / Generic Provider + +用于自定义数据生成任务(服务端和客户端)。 +For custom data generation tasks (server and client). + +### 服务端示例:自定义维度 / Server Example: Custom Dimension + +```java +REGISTRATE.addDataGenerator(ProviderType.GENERIC_SERVER, + provider -> provider.add(data -> { + return new DatapackBuiltinEntriesProvider( + data.output(), data.registries(), + new RegistrySetBuilder() + .add(Registries.DIMENSION_TYPE, context -> { /* ... */ }) + .add(Registries.LEVEL_STEM, context -> { /* ... */ }), + Set.of(MOD_ID)); + })); +``` + +--- + +## 注册自定义提供者 / Registering Custom Providers + +你可以通过 `ProviderType.registerServerData()` 和 `ProviderType.registerClientProvider()` 注册自己的提供者类型。 + +You can register your own provider types via `ProviderType.registerServerData()` and `ProviderType.registerClientProvider()`. + +```java +// 注册自定义服务端数据提供者 +// Register a custom server data provider +public static final ProviderType MY_PROVIDER = + ProviderType.registerServerData("my_provider", MyCustomProvider::new); +``` diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..890e56c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,15 @@ +org.gradle.jvmargs = -Xmx6G +org.gradle.java.installations.auto-download=false +org.gradle.parallel = true +org.gradle.caching = true + + +# Mod Info +mod_id = registratelib +mod_name = RegistrateLib +mod_version = 2.0.1 +mod_description = +mod_license = Mozilla Public License Version 2.0 +mod_url = https://github.com/ModularMCLib/Registrate-Lib/ +mod_issue_tracker = https://github.com/ModularMCLib/Registrate-Lib/issues/ +maven_group = com.modularmc.registrate diff --git a/gradle/forge.versions.toml b/gradle/forge.versions.toml new file mode 100644 index 0000000..eb179be --- /dev/null +++ b/gradle/forge.versions.toml @@ -0,0 +1,13 @@ +[versions] + + +## modrinth maven ## + +## curseforge maven ## + +## libs ## + + +[libraries] + +[bundles] \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..13e9fb3 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,25 @@ +[versions] +minecraft = "26.1.2" +neoForge = "26.1.2.126" +loader = "4" +shadow = "9.6.1" +spotless = "8.10.4" +modDevGradle = "2.0.147" +lombok = "9.8.2" +jetbrains-annotations = "26.1.0" +renderNurse = "0.0.26" +mixin = "0.8.7" + +[libraries] +minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" } +neoForge = { module = "net.neoforged:neoforge", version.ref = "neoForge" } +testframework = { module = "net.neoforged:testframework", version.ref = "neoForge" } +jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } +renderNurse = { module = "net.neoforged:render-nurse", version.ref = "renderNurse" } +mixin = { module = "org.spongepowered:mixin", version.ref = "mixin" } + +[plugins] +modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGradle" } +shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } +spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } +lombok = { id = "io.freefair.lombok", version.ref = "lombok" } \ No newline at end of file diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle new file mode 100644 index 0000000..d95fbea --- /dev/null +++ b/gradle/scripts/jars.gradle @@ -0,0 +1,40 @@ +jar { + exclude "**/.cache" + exclude "**/SimplifiedToTraditional.properties" +} + +tasks.register('slimJar', Jar) { + dependsOn("classes") + archiveClassifier = "slim" + from sourceSets.main.output +} + +java { + withSourcesJar() +} + +// Use delombok'd files for sources +sourcesJar { + exclude { + sourceSets.main.allSource.contains it.file + } + from delombok +} + +base { + archivesName = "${project.name}-${libs.versions.minecraft.get()}" +} + +afterEvaluate { + tasks.withType(org.gradle.jvm.tasks.Jar).configureEach { + destinationDirectory = file('build/libs/') + manifest.attributes([ + 'Specification-Title': project.name, + 'Specification-Version': mod_version, + 'Specification-Vendor': 'ModularMCLib Team', + 'Implementation-Title': base.archivesName, + 'Implementation-Version': version, + 'Implementation-Vendor': 'ModularMCLib Team', + ]) + } +} diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle new file mode 100644 index 0000000..43a47c4 --- /dev/null +++ b/gradle/scripts/moddevgradle.gradle @@ -0,0 +1,138 @@ +import org.gradle.internal.os.OperatingSystem + +static def isJetBrainsRuntime() { + return System.getProperty('java.vm.vendor').contains('JetBrains') +} + +def devTestModId = 'testmod' + +neoForge { + version = libs.versions.neoForge.get() + + accessTransformers { + var file = project.file('src/main/resources/META-INF/accesstransformer.cfg') + from(file) + publish(file) + } + validateAccessTransformers = true + +// interfaceInjectionData { +// var file = project.file('injected_interfaces/interfaces.json') +// from(file) +// publish file +// } +// +// interfaceInjectionData = project.files('injected_interfaces/interfaces.json') + + addModdingDependenciesTo(sourceSets.test) + addModdingDependenciesTo(sourceSets.extra) + + mods { + // define mod <-> source bindings + "${mod_id}" { + sourceSet(sourceSets.main) + sourceSet(sourceSets.client) + sourceSet(sourceSets.extra) + sourceSet(sourceSets.clientExtra) + } + "${devTestModId}" { + sourceSet(sourceSets.test) + } + } + + runs { + client { + client() + sourceSet = sourceSets.clientExtra + ideName = "Client" + + + gameDirectory.set(file('run/client')) + systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) + } + + server { + server() + sourceSet = sourceSets.extra + ideName = "Server" + + gameDirectory.set(file('run/server')) + programArguments.addAll('--nogui', '--world', 'world-extra') + systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) + } + + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + type = "gameTestServer" + sourceSet = sourceSets.test + ideName = "Game Tests" + + gameDirectory.set(file('run/gametest/server')) + systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) + environment('TEST', 'true') + } + + gameTestClient { + client() + sourceSet = sourceSets.test + ideName = "Game Tests (Client)" + + gameDirectory.set(file('run/gametest/client')) + systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) + environment('TEST', 'true') + } + + data { + type = 'clientData' + sourceSet = sourceSets.main + ideName = "Data Generation" + + gameDirectory.set(file('run/data')) + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + programArguments.addAll('--mod', project.mod_id) + programArguments.addAll('--all') + programArguments.addAll('--output', file('src/generated/resources/').getAbsolutePath()) + programArguments.addAll('--existing', file('src/main/resources/').getAbsolutePath()) + } + + Testdata { + type = 'clientData' + sourceSet = sourceSets.test + ideName = "Test Data Generation" + + gameDirectory.set(file('run/data')) + // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. + programArguments.addAll('--mod', "${devTestModId}") + programArguments.addAll('--all') + programArguments.addAll('--output', file('src/test/generated/resources/').getAbsolutePath()) + programArguments.addAll('--existing', file('src/test/resources/').getAbsolutePath()) + } + + // applies to all the run configs above + configureEach { + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + systemProperty 'forge.logging.markers', 'REGISTRIES' + + // Enable assertions for our classes in dev environment + jvmArgument('-ea:com.modularmc.registrate...') + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + logLevel = org.slf4j.event.Level.INFO + } + } +} + +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} diff --git a/gradle/scripts/publishing.gradle b/gradle/scripts/publishing.gradle new file mode 100644 index 0000000..149eb38 --- /dev/null +++ b/gradle/scripts/publishing.gradle @@ -0,0 +1,21 @@ +publishing { +// publications { +// mavenJava(MavenPublication) { +// artifactId = base.archivesName.get() +// artifact(reobfSlimJar) +// from components.java +// } +// } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { +// Add repositories to publish to here. +// maven { +// url = "https://maven.gtceu.com" +// credentials { +// username = System.getenv("MAVEN_USER") +// password = System.getenv("MAVEN_PASSWORD") +// } +// } + } +} \ No newline at end of file diff --git a/gradle/scripts/repositories.gradle b/gradle/scripts/repositories.gradle new file mode 100644 index 0000000..7518783 --- /dev/null +++ b/gradle/scripts/repositories.gradle @@ -0,0 +1,35 @@ +repositories { + mavenLocal() + mavenCentral() + // force gradle to download FastUtil & LWJGL from the central maven so we can get source artifacts + exclusiveContent { // Force + forRepository { mavenCentral() } + filter { + includeGroup("it.unimi.dsi") + includeGroup("org.lwjgl") + } + } + maven { + url = "https://maven.quiltmc.org/repository/release/" + } + maven { // JEI + name = "Jared's Maven" + url = "https://maven.blamejared.com/" + } + maven { // JEI mirror, AE2 + name = "ModMaven" + url = "https://modmaven.dev" + } + exclusiveContent { // terraformers - EMI + forRepository { maven { url = "https://maven.terraformersmc.com/releases/" } } + filter { includeGroup("dev.emi") } + } + exclusiveContent { // Modrinth Maven + forRepository { maven { url = "https://api.modrinth.com/maven" } } + filter { includeGroup("maven.modrinth") } + } + exclusiveContent { // Curseforge Maven + forRepository { maven { url = "https://cursemaven.com" } } + filter { includeGroup("curse.maven") } + } +} diff --git a/gradle/scripts/resources.gradle b/gradle/scripts/resources.gradle new file mode 100644 index 0000000..52ba62c --- /dev/null +++ b/gradle/scripts/resources.gradle @@ -0,0 +1,53 @@ +String getConfig(String key) { + return project.properties.get(key) +} + +def mod_id = getConfig("mod_id") +def version = getConfig("version") +def mod_license = getConfig("mod_license") +def mod_name = getConfig("mod_name") +def mod_description = getConfig("mod_description") +def mod_url = getConfig("mod_url") +def mod_issue_tracker = getConfig("mod_issue_tracker") + +String suffix = System.getenv("VERSION_SUFFIX") +String version_toml = "$version" + (suffix ? "+$suffix" : "") + +tasks.register('printVersion') { + doLast { + println mod_version + } +} + +// Create run-folders for non-client configs to avoid pollution of dev envs +tasks.matching { it.name.startsWith('prepare') }.configureEach { + doFirst { + mkdir('run/client') + mkdir('run/server') + mkdir('run/gametest') + mkdir('run/data') + } +} + +var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) { + var neoVersion = libs.versions.neoForge.get() + neoVersion = neoVersion.substring(0, neoVersion.lastIndexOf('.')) + var replaceProperties = [ + version : version_toml, + mod_id : mod_id, + minecraft_version : "[26.1,)", + loader_version : libs.versions.loader.get(), + neo_version : neoVersion, + mod_license : mod_license, + mod_name : mod_name, + mod_description : mod_description, + mod_url : mod_url, + mod_issue_tracker : mod_issue_tracker + ] + inputs.properties replaceProperties + expand replaceProperties + from "src/main/templates" + into "build/generated/sources/modMetadata" +} +sourceSets.main.resources.srcDir generateModMetadata +neoForge.ideSyncTask generateModMetadata \ No newline at end of file diff --git a/gradle/scripts/spotless.gradle b/gradle/scripts/spotless.gradle new file mode 100644 index 0000000..5ecb0f9 --- /dev/null +++ b/gradle/scripts/spotless.gradle @@ -0,0 +1,44 @@ +spotless { + encoding 'UTF-8' + + format 'misc', { + target '.gitignore' + + trimTrailingWhitespace() + leadingTabsToSpaces() + endWithNewline() + } + java { + target 'src/main/java/**/*.java', 'src/test/java/**/*.java' + + def orderFile = file("$rootDir/gradle/spotless/spotless.importorder") + def formatFile = file("$rootDir/gradle/spotless/spotless.eclipseformat.xml") + + toggleOffOn() + importOrderFile(orderFile) + removeUnusedImports('cleanthat-javaparser-unnecessaryimport') + trimTrailingWhitespace() + leadingSpacesToTabs() + endWithNewline() + eclipse('4.31').configFile(formatFile) + } + kotlin { + target'src/main/java/**/*.kt', 'src/test/java/**/*.kt' + + def orderFile = file("$rootDir/gradle/spotless/spotless.ktlint") + ktlint().setEditorConfigPath(orderFile) + + toggleOffOn() + trimTrailingWhitespace() + leadingSpacesToTabs() + endWithNewline() + } + json { + target('src/*/resources/**/*.json', 'src/*/resources/**/*.mcmeta') + targetExclude 'src/generated/resources/**' + biome() + trimTrailingWhitespace() + leadingSpacesToTabs() + endWithNewline() + } +} diff --git a/gradle/spotless/spotless.eclipseformat.xml b/gradle/spotless/spotless.eclipseformat.xml new file mode 100644 index 0000000..1c57b3b --- /dev/null +++ b/gradle/spotless/spotless.eclipseformat.xml @@ -0,0 +1,400 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/gradle/spotless/spotless.importorder b/gradle/spotless/spotless.importorder new file mode 100644 index 0000000..dc928c6 --- /dev/null +++ b/gradle/spotless/spotless.importorder @@ -0,0 +1,8 @@ +#Organize Import Order +#Sat May 27 02:13:47 CDT 2023 +0=com.modularmc +1=net +2= +3=java +4=javax +5=\# \ No newline at end of file diff --git a/gradle/spotless/spotless.ktlint b/gradle/spotless/spotless.ktlint new file mode 100644 index 0000000..6bab578 --- /dev/null +++ b/gradle/spotless/spotless.ktlint @@ -0,0 +1,10 @@ +[*.{kt,kts}] +ktlint_code_style = intellij_idea +insert_final_newline = true +max_line_length = 200 + +ij_kotlin_imports_layout = com.modularmc.**,|,net.**,|,*,|,java.**,javax.**,kotlin.**,|,^ +ij_kotlin_packages_to_use_import_on_demand = java.util.*,com.modularmc.** +ktlint_standard_class-naming = disabled +ktlint_standard_function-naming = disabled +ktlint_standard_no-wildcard-imports = disabled \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..51cbd2a6f8121b2ce12daf979b128058fb9672ee GIT binary patch literal 49154 zcma&OV|1nKwk@2bVmq0!ZQHhO+h)bKZB(38Y}=`zV%v6Zt-Wr$-@W^sv%dYdHs4?K z&oiDrdLMm^F{gs`H&9d{NJvN^ARxj&pa1Vc1cCyR6;%hzs2^rks%InQpN&4@i?cFB(v z-M(*+9p)GpVFh0|Q&|H$3~7y1>nj^sp)F4KdOQ7ZYY$i0^%@)D?(UUY2Oqa~O-NT) zOS^{7+TjluBM%!>1Kd73v)b$vQy*S0ci;F3fwv}yVk%tAAQYyj^gV6OK1G;!9vdu0 zDox12IZpCz&VtXW6fgH&Xl@*LM0Yw;+=3R@kn&(oL_)MHq-^4h ziloqQ;YM4`)-Q$-`hQ&u4tSU1XfMK*c>%mjH7s9?7CSx&CJU6+zDw09Aczx=7}{5T zB3v9D=x8yX9}pNU69oA*hV2VXuv3BigbBWK56c~ZWUH+)B{KHrxsxO32F zPxY?VAcXf89f7!7=uR{_O69bOCX06}5kzr{TRX!eU2F%pejHDwcs+e<@oy`=fK3mB z!v~EC!tOmi{^pRRN+$uDpuHG?Bn4NKEirR1L-#ch&FlzfeZ$V(G2I3KHA@!Pj-{B2 z=IP@Bd@ODoJsQuXt9tj z*|A7$pyJSQH)T$wB!Ch%2cJ7u+q>KrH$UC^zH?w9>>vfUgwQ4)*oo;^0QsVSwqbE{ zwVf(vdhOWq!5-Y-cG|#w%j__+qTu&ysquQmiJp6wiv&_c^ypd^01}zY@@Y(4Y;YIf zYUCwAzqg+r&(<{@%v7Ase+W+mJPi~_4lz9kBlkLbe4zk;WLHT=JLGVFXY9}Pcn6@s z*(S7<;RsGhRT6OD!DIwparxA!t^$(4E3w;ehI+}{Q3|k#1lEwkmtxu#5@2We)`_zd zLkmW4%~Xj4UPWtCkYA1A2nL}b-*91Qt^qjTs1>KaBk<^t2*T8)0yZRMl9;M}sbz0d_ERfsXTIYPt|* z)<8ts6N!-`35%l^znDvAxyFBuon0Z0`^NMf-z?ySQ)XRYz#XH|{hBX_fX;djHfp_< zA(3FR!PWxv_m_Jil8yvc-0EGD{cg){2h7dm0lFzTCz_e$#fN4=+<(KYh14l?a5-d^ zfPyAsx{9~wTiKh=n!f9Kd+WNWH@TZ(riZ@#202kD!5aU42?!J8IHcN!A{HKf*;RyZ zcv@TE0DWIfeN4fktgpm`@U3HaNC~x`dh6RKX$}yQYfuz+elh_qwPpfzTM@R(nG|U&;*q z_f>>=I}|m`2Nq%wV{1}xfPxt^H&lu=C$D9sM`4P>xY0TcVx&H+W)N@bgrid*x7>d6 zcP>0`lWh!2c{_o@kw+8ddI-~I=v^p^A|euqk~?1|WUhxJ$eV@j<`Q6U=QgqatP=ch zb1lv{F!NOFkGed525LskPL2=tUiBGc^EBe7V5&+c;K-1K`ONhkyI=zFJITG*Uaa3u zg`R=$Sr-L~myczhGI_4H2cK_P>+m`ThR1MBnQ`=&)%wWc1~2E5A@|J}*Pr}b4Ud}* z!1gub9DPDvpr+p(VXXTi5zBpv31|0EW;3L#i^y{|_I#=~{>ni>+Y&Zn--!oE=_ z#;>;{v2%~=9ThJo=QM%cL*d5E7d#$B_#f01z_I1rq9JV~U`m=iG@iQ%av-|5cCQA$ z%G{QYztF-TM=G2h8fg}N8Po3r{a`39QU>obM%$O$&4b$a+4D<*R@+}%;&{r04IQDF z3V)B_4>~Hb*zb$+>Mdfk8W9DeK~I*?-Uda}2jQrIs%pKfc1u(yJHi>L59HS}svrpc zvBHA<%@lg7d?tC;q8R6nl)jFt20p#;xC@bb9;{!jZvfF}uAKnxZ7{N6yQ58`(uawq ztXkVsX4EZG=z9>CLlzWXSMTj8sRXv+Pb7iZT}S}j`_^D2k8M_4Fn^GVs8z@)0cE3B z$;w2NWj^`tD_-5%h=O_TK5L#!u*6zHcRAh@_O=?FxXA4I5BqcYo1^pm#M1#w@*9+t zxw<2^wIm4k2q|OykPmJISDH}7MuheOj-AUn(>3D3p?I;3mG-Mq%*X>7cenDI>L{3}EHRWf zxQ@vi1gliTBw|r8zRft7o$cr*5fUZuq*qZUR#}78Sor0;7gm#7eR-L7WoI7mBmeC; z_QLd4Kr;6l`AiKg2%X7zhUu7oM)|Cl)OA5s`G|~Q8C@otpyX~gJIbD5Ond->kT^y6 za7{+~1bVlHIy77S9K}gp&Uo3qpX9h2fmq#1oS-bgMW$H}JyRsbTQMxpi6IYEGk19b zIC<8!A3&4Qp#nT}fUTXatqER}Cfnv?@6adpAX$nS@Etxr2Moma0Sm!1y8Fa|4+4%E z8HTg~s%y&`BlOwT?r?HT1g|wER+#UYQ0Xob*0dsahE}L*&x8$sBD9L?eZ#0HN!)~t zwEU9xo;5?E?g5vBh#%!anPan@YEjh~+v1GG2&B&83uE0g($Zv`VGxK}M}{m@O>kzA zr#H6jW+c?}a&xyZLP=e)F(vdt21pKEKZ9B!oL{_#DR!TwVF_xYt9N_B;;KIdDQfI8 zQpQ&>i>O3ac53$~LyaVFdPs%Hv(=StN*X$QLru2A!DNF&nv5#Okp(a@D0fhdlFqU3 zZRPeZ3-nYG0oLB;ahxB?<&^0a7$X&PK`%K;C$a0Z=P^$7(@>3V*vri&C7timgKN~V zqGhUV=1bc8&=UPe1{iFV!Kqfrnz&vM(>J=v7Iqc==FluAnKj%dcMUNKR(2syhYBSh zq+rYVwn6*B^FWAVgP|4Vi~O>pUjA3uf>;^eA51|WAe$D5m2UI5UGtV#J69l|;0lu=f(ZgBOa_IT5y zSMm??r&VI-b7$Ir&vW29otI?UkxGe?R0f~RRsqlE5=xRTEesva6{f+w^Yi@LX$GpS z)uUIxTAo;>Z|T{pxrDiSyLjEG%|F;ZItV-Xz(*CjN_(nYgY)+_*fI6dsp>OCz(=>f zxiS2>v2&hSOtpu>?$iYO@Lo|_sQ$Jw>7dR5hjE?F+O;S#bJEKyg3&E>lZMEim3G@W z$GI)yu@1DniqycZe7Zu$T>j>*mN|TgQGGN;GqTBlc+HuPis3u!REgcrqi=M8Cg9&5 zaBl#(E-x@7KZeY4W3z%{*F+Q$=3_ekRWsMyE#;~^xOQp8G#-R zwHtC6o!+Yg@8qNTfinqO|y@AtSZlvRVOQ-t;<-Z@nCvF-tjay z^T48yk;B7oj>jx?+y*B6N)F?qAp6VtH8ZN|!V_{?@F_2$yuEym#^Cf(vgKjn7RxZQZPsJ*>Q-@A>t8&x<&9 zD7$J*SkdPhP;y5__KhyGZrI42Ej{Q3gf;%r0+|NM_oSssc8bV_Ws-{M;C^J$yh$~H zJjNZ)tuZ#&M%fZ83v~}LhP~7NW1ZF1c#8Nli=pJ{qNbDPN%>gdqyp*@vy`y%p_g?J z?|Tzs+~aU`3APxM&v;Q|G3+8boZgm7?5fJNZt$nm9tCL#$hwvyyc0Mepl)&?AcgzQ5_8J(v>y2ENiG+cWHyOJ;b8uW zz4)YZqH_R`YraE9{5<ePTBdC<>YrPjp<>p9ec?P00Q%m<0rl!(T0Yi-P>yDVjqTIHWYcQ z1fZaIRkx9LjfB7(lVyshjBKcsMMaWkwCx@hxVkTm4g2F~5TY-KUFa;JIGcOW#6fg1 zW+~K7CH{WO0(U~(x_ZzY9GRb@MG>hM4rBf5`4edfNZKPW5#&EnSO3Szll^1l<^Q{In<{C`qX?pYhNjZl zrb$nTUI(`7SrnKm3Q%L}LsCfs8$*HaO}MzP!k?G?-Y6WF*qyn?c&IXOl=EWd_xbXQ+e?Fvxp{HHOWieBvA%*7`(w&lOqSXr)SA6y=-UaG z=o%~7BCjFTB@CC1LyrYZaQ$A3jeb_G;{*m+wI=;)r)DzJNaJ>srkqBt%e=m|COVp1 z$Po%Pnv}A$GPCpQ8XZHZ%8;#Rs0RscAH$)SYuBaY0&=^dr0-ml?Pa>@NqCbPM^Ye% z@D|(FLHkfnd$-yKx>!CzUw$i6zxgq}_;)n|+7GBFY&4`>%0m>KcfDYS9|d;^1P(Zpefo9hSS0F z$lSeQMy#hsM@~e%S}mb~;aSoF8VBCc0-bK#*#rLvFf?`t=9sfq*M6r%9l_Z3k`{fm z+Q4J28C4krrWhV*mTZ(12)Wj^&5-o6{IJ#&=32M&(m?LPVc8@@2KR1um5d=Bi&tb=JSf{LTDzFP$7LDIiw6JB$$mzH?)mLbD^2S?A1AO z>xhOl2?DXVy|IXD42a{e(7x(#uouS9C^hGMr(f@@gu{UGq%aDm&XG}2(H4N8f!P6b zD2%>?{oTM^ZJfwrz+0o)oMW(~3&pX@DCGMv#o>=!f*lVQ5t{ztPmsUR%rg^Q?Fa${ zl>P0Wc!c>M(X3$Thw3Vo&SwVQj~T7f;R60dMaH>3DI+PYv5y2CZuG^ zFsP)DRd2Y_cvQxv+{FCGZ!MAQ~b8I}4wm6Q>YGV^gv5sr5GLv_&TAxob_hcq_Ry9l4~VwZX)#^cK!pZ>G-L z>A3tZzQ%1sxcbS_b{*%pcE2y3c~Co>MxiPz$Zx7=9Y^b_ljW=S%jsxnd9;}LVgneD zvGvMjZr0sEg?}qwNNGDxAfYYPQ&;AmIaw~+QtCMzz_7N=LkDYJJ>I`yA;Xpw5Y9Cq zT?<%Xnqsnl31UXS0s{HgxkQzXF@24sxjn`i^047&?3o6gU#3u9id`(yB@AK5NW|g| z(_LQll;g3`L`DqKrx)Fy>1sK2nyIk^8caJ_0TUSn81N>#6bP0JuhaSs1hGT-qntHz3%NDqb&CUp-x2--EXfJ&H}OA!%>w-= z!1DYjfE6+|vv)ETvvhKHQFb-@-@^EB$Zb-!RbJ3Q^`j%8tS?91a(A^p*RsH_xFu5X z0Y*iIX^o;+9swM&b=eYI&Pysenww|*&a2;gf~ez$W_B}s$YTC1ca={p6i9eBElVnX zT0hEuTX)WLz8vx2`ut`9%Fp=T-Tis@Tq~7eUD;1VnG~s}#uRC`c-r2lyTP=WsfujU z5<=KYY|$`|t6B+dyJ-0f$FyM*PTVBfOSJl?z2c3L4n_}eC%9>(jfk?Bk_2u zti_t6I@ZuqXE0r;bwT%ptG)Ju^}3y=n$9IO)CTN^ovJ%>8X(z6BORxp%thJVo?#Lp zc;Jc1$Jr8sj{TV<64J}d0dkJQ1Sgen2U57!6j^u;&V!i;ceH1l-g9Z&jI?8SwOw

D4ii5U)8pSQ%EF)}Pk=FpU6G*dMWV z=Tz*G&b=b4GdF4%cKUIfrQ7(}IxE#7w%{j`PN+0@1RaJxIeV8hTrzUUb#jmJzfG-7t}@^-6aQZRI272}=n)<#_!)zZXE zLXawGEbW%d%s>9BQHKP70+ORnL^8DQ#Oum|ZFtUJP@( zNeRWCRFIWIjt5bk2hfK(5aHX5seqNn7ztIOrdO*RMjR0~YOws8Jc3i&iMR~lN)$#~ zUq{(-?!rYiT#aHFKy<9OrNqa#a3?&sUB9VwW(wt9+POIYR2OlM+nKrUZmi5k;JO8R z;vYNgjt1KYw40sOQs_5OKZ zkz$d~O7atAQWbCIv*-NopX=e_Nj=$+-IDWqb%@UG-LsEe5Z$t>i1_SJJaW8c_0r#a zncLZ@CTeOEV{60i#75glbN;kG;(9iyyZ4AmGq+`7A8n8lc zIr+}(mVd|pS61t0B%~Vuk)TJcQ>tmbX`<)F80X%wx^RxmH(eKx!_!5(^50cH&OnB_@5 zDWDAg%J?o?`v9{GUW2?kE2{yattuS@Awrw$t#rEawo5?zHR|%7bWYA%| zI^=w$HHw#YZ{MnCAs(1b<&eg)A216Q#RC$4_HXv`9`$lOo!rOKUMHS6#kQ1=p&eyv zoR+ViI=I#Mf+y*%UBZ;IhC1Zawj$TE>I)lfGL$oB@8Q@z6jmbs8LD`F>2^o2*5OrL@YXt zoJ}oeI4-tu+{pAo!;TY*JC$qIZe_CS)1r-z1!BsVL!u+ZS^ipfnKP=GFKi0oeo|p; zpE?(v%Edz1U$;NG%cm?Y9nJ{)NcMD|JVzD1YhkRxmDL_BO}WX%&NLlPy>ACdGZscn zGbHY+JYgx3Y#Z?v4)YlQz22ZdjAnt6sCNP_g17HNckAeT2XYW!56})Ic~A>I_P?SD zF*w>mePV5o-0A#{cQI=1m8p%)1z6>V3o&<|4pvf90;t=Pnr9emWtOEFE-1bCN1eF@ z?=Du&t3=gk`lS(FkgZM=xEWwTl^r_$A_MF?ORChbm5IUYM{R)Ya)nluE@_dN5l$8_ zei7b72lIt$jnKIMFr7-#9)0v$C$M=7TA|aRzsg)QtteKNm0I0zHcF4(Eickhi~*d4 zAIT=06)vexoE(JVMnVP^|K<)Ew0l%gTaOk@Kx<*J$z+G|Vp$`L)Eh_1-10+EnBhO0 zzPmCbC@cbZL=+Zb9mug(?MP-90!e*nl5+c=hfk*6V1i@p zDdLd&!)2!Hdix>7-+<<#y2&eYFr{Y9z*!W|u_YtrqvD<%^*;i5sBbShtsc-Oko6#U zMf+?|&Xq|zWj+-fI?_M_zM>>gNjN=J)7IpBx`%P$fp&B+=w$7`~QBQ$l=hO$Mp%x>T@iP{KRJsDp_6xO$-)@NrXljrnLj5%h39>gW190b>FNR_#T zaMZfe@5dM#UwF-;Q7bO61riMc-$h+uQR^>$DzD^{R4#6m)e&=Iaw_;gpw>_pdgphS zh4Y#;xI?r1DI2mXG)Sdt&PAv`4<4vIkoTYI_&v~Z_ti(@RFOe}47&0+KkIl~#oF^-lwFaR=yPJf2yb323DD(SqFvY?VnG!hIG7Be0j+ZS*KY$(Lig2@pn zeB8h$l8lBnds~59HUy(1tG9)zs0s%ZZ`WZ@B!rr2Y@$jgifj}s1TKY0@G5VES&VI7 zDPTmwBoK{Zp6pYuphS=s)xX+EiY_QS&Io+intCC>ixO#7!qkD;-3uV0j0L-&=4ivT zX5m%BgHxpWYCSyV_7)~t{0LwEa28$s=G996NQ!5!A{V2G#XEIP```-_7lp&g`SCOC z!v~3;w6NQh2>F3F%PZWZ_WJrE0A!P-2zmV;;ReteD*$}O0v^fXX!Ba;0gNAh69)Q8 z9H8$*RPVTc4N%V==7JKJ6HdH7#&5l531oSOu|Clk`g9*$ zN4y+~j11P6elt!^&9W#>iX@hQ;1ulRlQQ&8thiIHnAtP&3_QKVsF>ELeC|;^{fq!_ zhMri#YPYF%cdXQ{S^WA}LjuOZDQy%S2*@1%pS1Hos)%JRot-W1%>P!;KkcFaPC9dv zbnO=yP($@wv=_`Mtzp21mkDfUujFP0n+OqQ98}pv<`6ram0Mt>v#BJ>2?t3&5in!| zi5&Y7w#5nM8c=P^=lP7r+_H~+%%9H2PSFdQ=oFGh(UwNcK=L3y-mE_3us zwy{#eh@o&b`pa%LsIm!OcUrOR4D^Ov*MB*HsRxmq!7|6{xbHu=zMLRG5lf>*u5osMeRny* zW+GmvQWtCeKl0#Ondo%z1+a`vZ!J5 z;p5v+`l{UNtYN4L>MAr9VktK@XwJc19-C6zrNRX6D`5t%1txc_$69v?t+iB^R@0%j z8AhdRQ4Y!KMVzt5O7=x9WY;-e&Ub6D!Xo29TB1-x9U?PF`~W;8VMO=!Xx2!{cFzCt zYTBtKCX%;-go&92Jyju!N9RZ!RAcY*u}|iez$WvDok^cc25Q9g=r6Hcf@tV^v2QQb2&uyp}1WE z-#-@+pnk{TQ(qXFHNGwC%;zaluEiJ-;OH7b@R;9Lqij2o*r1{n+hnHLLE}c27wKx1 zbz3Hc4uvvu3TwB6UlO(%z*EHo1oUE|{p*x}1#S{_3;}ed-jTD2RiF|{Mo+Z~0 zkf=Py*QvojtsJr%&SAu{3ag+Z46vB}WOg`(J5B4AMQ^q2)2j_)4LdDK?D1NG(BIP` zT+4k^@K}UrRZT0*^hR-Jumf}TAY=({F@l@mRBN4v9@FkG+&xh21E4?eox zqxL!956jJc!ChkX1A)_jM+mQoaU)&jb_w;?KOU`jRV1Yo7L-({CeZ*g!0XqP+`yd!BEbfI@d^uYDIB z`*RyEJxmd$f|LR~(4BBh_F_om-4W|(>`hkB7DwbkIrC_$Qd#m_Y+y0C3`-l7*sRg6 z(vK;8aw$dzLX@9W-!7_`mh2`xDFP4`@PZ?5jy0%|>rk+^9^hh8+j0{x6){1}#d&|6 zz{<*)U9d=1`=Wh|N{x)iQ0VA`YKLyR%7wQd{V7TTNpUVod(r(}$M?etUW!3ElqeZY zMQBRL_|3%}A)4NxqkHqs`M$P5_Yv2slnmICdb@7(&5@x_%&Oj-q9r0Me&>;rysH71BQ_P2Ojb&J#PF1OUvZ)q#bQjCKL zd}8A~7(Z<6W^beckqf^6K@B|hs`jyy`bY;h9BC{)p{6){$y~nfiOh z)i#TJgLeT5Lg!Ve=E|F}NsU0Ztd^j!&SOyCV_;XVr+$kQ`Ol1D4DqO8CVuM;7boqU zfn=i`j5AJV1Qw4udHkp6Pl<#0)l}**Dmvn%&_HS`B@K;UQkn{hxGo-HDu)p?Sm}dt z9&koo`JGe!Uu78WVu8=VX#rp3u;8#0&gH6ll^T69EH!&%!Z%ybNd=a!Au0}U{0Dz@ zptwG=g9PM>2a8{lpWYQblVwY>KJ=k(h!;&-1HKFSTamXaCUOUhN2m=)^U)tM-k08l z8p*N*yI;+9q+cZ#52U=uG2Tx|+&>V)B@RXsPdNv_kP2S_X;^f71Nj}}yl-_x;X@W) zAjT&7#o^l)KT$j?5Xh6S$tz5!kF&D`QROpa)$vNE-}&7wv>)-$Q`{rM{sLSMTCrQsr?K{h1uE$hMc4^Y;f~Ug3}oG%eXToN z@%-W9isy}9Oa?-EFSA8qu@fOa~?)OmKXQ_rnnu|D<}(J zOW%7eriLK8KwmSBU0R7k-S7#0A?JhCFwB}U=(8lH5atR2D>vzejsjSpXcuM=b>=bo z=0dJfrhop+CwxZ=x$*x)G?D*EH2nX`J*(PT|3_UmW!pbvA4I>@X4G*_ngdy|A(SRs z+c*jlP~$+7;X&|dRhfv0-uK7ss`9WN4pXDqJJlRn*TGldBq$z@?xb{as>w9{VAJmOeqrAnpNb3B3Jd|TRZ?TWh;V^;CN zsRZXilpF-$-3RM`KQotjE|^fLxhFXetYH{zWdVp$ar?wsv$@MwV@XV~QnD8383KOY zO(Mn34avuUlBZgO$pb_#{f9R}(@^rZNM73BO9NSIO5;Vu1fhk4BnT=6`ch`Gl^MSG z&1M-$WD$AveW+SCQ6|a)q8w(ZHhs+$&c-9qF7Nt^NN5v|Mn_=O;~LyYfM&L6d`ya&%j#p*xdK`+ z0sQWMb|)z83HTvLw=hNuE#B%nD><|6rrv(#}BqSLA@$D}W-T3LEZ1xA&t^a5({&^_>H+lV=Zu+WftD~r+ ze#Sz{h1W}6&ub*dTcLmus?`yBL?Kb5AyZMr7%dF!$4ASU?M{m1>uK4332arw`QDUR zKNP|>*OpY>(hxs@N`XJOFJ9 zX5m9PFaYtpNsPONHn05p?X8^BLAg<$dbOpYNqWn^m&516aK0r(26n|n@lcZwLTW@@ zD_mjCywX-O2#nL`?S~`A0)(Gw%8)}Mud5S^QjeWgZ@cl$HAM0Wx5AP`hxvTMD8TUQ zH2)Nrks?JRUpz9aIFroB!(VpqR~O}R349~29p_{5Ve*nAs}NDm-gB?~(;;Yt;vu{) zNK}D4E1T}_QfsR&S|}A;f=Q!aI00z6kdhyUDIy0{ z4~eo#ggCMy8+ksBBVjbUs3SHyGraXNmt$8WtwbNOZwaY4_`i>JsCJh4dBh*m=)&Ky z9L?2>UxJGxLRq=WwF5EG`@tB6r!)u%Vj`Dhy)^oMVVi5ZwW;K>Y0X~*B%9uVweRLh z7F-}rxl!!0su$0#Rklm_Q_NYG`#C6BY8jtxEm?EyiQ^R~8?g=ldQD)XBS{L?o(j(1 zV5mNB3S^=zQsiwlo(EgO(8e9VZpe|4QF&)@$RcdL=>l=8nQb8@&%3QH18O2rX)6j-cEU3plH* zQ7Y5Q!%Q^ghlr&K>C4dzIVA#j2s?EqmWayPy_$MVYE&dGGZYe96cA^L2Iw+K#YctYO(y?8HCKF$V`FV1)Aucfx;y>mJtx{f6RN6>0A2 z(93zu=3IHi?T&HBcW#@j!9a|n;0@CYVx51W zKE%Y^6UbI`2Yd?XhxW_4EME`pFO>MV`xg&3?-26N2)b!<~aKRsj($bi&F1q;#n#@hsh`Ba32QdPcJNk}xR^vG)I zM^YLaw}DIWzSZ1Uh|XpHS#2JOf>BN_`_AiUh|YU+j{?WdsZu!EX~i)^bEb@prwq@- zoR5bqd_PczXmVJ6USBT$M~+4!bGFu+;9=p6MFo~*Mki0zB-_PVV@}~66ZW=Y)2M|w z>jt!ms+-AB)ltoY8&%Dp9xTZ-!%j|orCgkJj-IX>WctokI6YdkEKD|z3x!oCnAkV~ z94shaOHku$T1+tJ0s9Ipb4V;Rwp>4K(&4MI(xDVe;O~q4*jDrzn1o=18pn3Qg>A59cfl7(0gdLt$#XwQVCmc?xQbXv?Y2s zt%0Jd8(5Cxb2 z>Mg`4pFIo;1`^grlY=VrwGi)(6Jud5z%#Gtq{s-S!=Hwx$IlE|*7kdrUR_gBhx0%V z|P2f<*Zi`^-RsG#jwfE zCRk#aATa283)auMq!0IVRq1D{bt|2Qcix|77=sO80ku1vs(GstClm@bI-JsQE)z@4 zF63Ih4XFU=(PUQhSYQQZ_A2keKqCe1_3FTmk!TT&(@#JPsG{qf0rBN5$M_46u0yDX z{{!VBL`RqcE3-tTvl&1`pZL&1!KTQkDK_bZ>~2qZGAbU7pN!$8=;k%NVC>?HqffI? zTNx(A8GD}S9#|C(4zI_G$mw@Ieos>WXFN0wZf|_K=C*$phM<2c%10OLajoPdG*h6B zl}&jdcp(e5wdpZ?GxIv`i0Y~SNjZV5bIhZpz5@Gse!n_YFw;u7D}F=aCz+-rwTXvD zQ87DpMa_Xfs&2iCREj1ttofTQx=Kn=1FMZk&2t_P$sO9Ym- zMsu9=S5jKWBxiy<9FjBi$7?gFs`9s*B-wKG_}jmbRu{&;xrlU&A0bUcf8d;Kpn1(8 zO~detybk%^lM{zwnmmIqOSJW0BM*pU%Ff_zZ}3JZ2~(*#QGDXXw&6uMUg2?dbk6zu z)ZKSJkGKaHz{j2Z{w9wE^$UqEA{F;jNTHwNhp5)@?v?cGQ^FllN<7(b61sTp>E&NQ z2xGsmkxCbsAzF82adz1TY<>-Syy!H-628#-?DTH<7N?d!_wp8q3>Fo8A@$vaCkHeA|SyseLWlcxbcWNHL@$E3;<1M@XWRWiyDC%PmVDB2J+|Jrp(+89DP`BSHA{v(Uh{8u0LUs&|-e$T&g zsqMcSd8pYz7FE?Lmue$+=*ek1yjdX#6&Wp*iHuc)*ZC8 zY%9A#%0;{^C$?qF@{P@Osi~|>qumgfod}w}DMt6h0iIFhFf)K6U1Oo(Mi%z29AsBi@ItSOp(C@SXm;_l+P zLHua5Y*KV+&=ArT%4JZ94;gtB!Vl__V`cs0{dG(_5t2md!1bH4qHoyTY&0C85B~4y zk2c9W92A8r{cIJWFV@cJ6{Yo))DePW6NtZyGql(@2%W%zn}!`?Hsq7TTC7#DuFAWB zGq}x9(Vcq!QaYQ(hiJh+UODL>mwf-NDQ9W-X93dA(1za3^3Srhf}x9rij$$6sgtvz zjj)BOv9+nwzg<;~>V`9lD(cq;`igC)kY;yDKQgLNCK~~&)QbXS{#>KMw_gTL>vndD zC0QG$?h8sth&|Uy>S260!=x4wW3@a>q_JNsL(U{g`)^X#7j+`>FJaj4i)ZckI#tM(60At#L`!%iKr$Ra)p!!+(~5si3?%yxX51 z2Wx&9z$RoXKfpSUH-ZYM?WHJ@#$nJTFkJ|Eu(c?ODwRxM=ld+}AqQ()W&~ZM(imIx z432n?@48XCdfg{7fPhg$vL;~z#$mHLc$19{Ffa@G=%JyQdZ|$@#ChIU=rKG>b-5bP zEayuNWOxj4#Y070Kr=AiG+>PTJeFF?-%WJ_)Q@9R2eVD9Ye+~P> zt}etvKQ0hU6UE2KaI11dX2nMoVnAp+0{OyD>}H5Dg%Kb3Az1}V>Lj9R#LHpQF;kbh z=nYEGf2`>IBEN^8SE1Vd`re8x;)qpQzu4Z6)Y$!hOV%`WmnNwdH!!c2T+>lBP3gHzNm zxq;V29dZbwwP&>Pjn1j3QQTFd+YaFH973$Y@dG1<#YQjl?6lGXw@h2Xfbio}NY057hi=aDPuEHD5#%7XV2owY8!Qg?A^l7+Dtt#;J8b znnPu?it}Zij}hu(+BgB5!|l4TY)d}dMwb>m&0Ay>3zH+{nbf{_LN_PZ5@Dwz&mR~m zBhPE2@$;v^Ik)`2!@Hej(e8MXw(&fIh-e=-Z1vzObM78AeR}k+Zljn3+VWwQaJMOL z&_sQgU<|K#rSt^dlHw)%jUUYB07Nh*ho-rZhvn)_T-vJ88R?HlB)(LZR#8p)bho~Y zYgHd99l3@6QeQzChT+#X@6@>Ql1?h?Rik_@0Gb{}K}iP=^hY#0IrSH z`~_<$zT-Bq9P_Vu>~?kkxs_5<^er|a8C)aH%K zugqsJaEv=<%qjP1ixA6jtVt|7S>tG@+Th5Y!SKUiEPDxps@h*RpfE_+q#w3~-kFeE zE3%F6nT!&#Ek87S48ZUbbdo1t)~5|$mD5S$>1Y!>*wnzD#gTQVD}1vRFi;ZIJ< zmW}h_snQZ6b|iZF?&sZT`R-(KfVonB(IP~^+|88vNKe1`nfo+Z{Cxk)ShoFB_SVze zrTN=h4}w2P9fm%`db^)*@sSltkyXLX1dU9BN>m%#}Hh!%dWVoYYr} z>fREIK1J?FY35Ng2*SWBl&h31CKaK)Ia%u=g~m|bX};a*G-2ql#Yh{FkH$q92*0qk zV9waJ-vHIkPtzRkVc3CT3#r6oH6grmK+uz0Ht}_XEtoZCXQl_70j(N)0a!KcSuUsG z19ow=PcWNdSLGYAc;|^M=>@;W7Ix{2zwQJxP@=y<~IyE z6GIym6C@;!dI{M<#5g(#y5;IjqR8bsVGZw`z6D#0Bt8*KoaQaW&*O6E6%mm~(7c?$q2$cqFrN__WklD|_h2C8;-5 zDj-s@w;!A=S(Who6>BQE6HA<`o+Ryw2QWXrOlzLN?4Gt|`QZuLikHRBrQqo)I3#{E zt1e(Ii2g2LgZRb~-16Z86V`?3Pb&`39{BOXJg}7Zm>p;gYul6@S8ldM)w*}sycU5K za4nCmE}Mi+3J~mhE8Hd-I7}g=#4-aDhJ|}m!@nKNx2*>Daby zyOR!Ye*1jqj{EI<&K_f}QR5x&TK`nlQ&rD==A2bYBr$9z6+%tc-rTqgQ1^gBo6>eq zUuKxA^PvvKr=@$LlfFQ6g+(u7RBeE>7N7O{zH;?T)zCo;Fmm{i@}AzKMlY%sm{fLN z*xFZDxlMz+S_j}Z_Au%b_c9J`T)ag4kVcI<85#b~en7zzy1^ z5VZyGR;68Nz?q;VNncl6^nZy{mQZOQ4IdAMYZ(TMx>{Eb7sxGJDD;)2WltgrkD-wB zHM8mxbS~V}X~YeJNtkhdA$^aiENpS4{ock;L`#_TB&=#N25y3SJ!Y z@hObNytE?t@qB;$EP;y1Ktib@ZSF=}ylmqQVrcTN_K6dUw7L83)(jm(ShA#)EC06= zW`etrWSAjo$xOw7ZrgBp#tBmr`n`OrpfIRCD{ze)QSU;i937!~*m}>&z)&@LN_T2c zHw40t)*Uy^V+?B7soi<-7w78%`xi~Ku&YJU=dgy%zVc*1rZ+JoDWiEV&z>w09Ib?I zKP;p8JYNQJ%kpTlG->!C2IR$dJxecHyyvfb`5`+|FmoT zn-J2?6=2Kw|85k2%U_OXW#1w96$MObH6=a*LH)hgc4%c=y!Q{zB_x0DG#?LLVJWP+P1P+Wwv#e z(l%S*)MsbxlC`u>rGQW#rmI9$nCjs(qPc`RN@~o)cCu#^#vUg7%DI@>9?Q6=i8O1x zRs}SdpObM-SA&R?3;V2JHRp8nYjzsJefT$8RlFsXx`dSjVuvK@$&2niXO|vYEmk&I z(D?o5RPMa&-E{f-;dP59P&VLt8^^rJYiNh8Ivoz^H0_|-;Rx1?S(!sr?$7+!=VE64 z;Akb2gGv!FT2q)BC`2dyCuc4c!j48%?n{8FsBkq>*o-mD?x7hj)Nh4zr7u* zM;NEr$>SaUVIC)2`2*I!qZ-O6o84#`9Y%A8B&eo+VN>CryJM0O;sysCyl*c=DLW_G z+*HQ{)ryDrXEWNjg`xzEsiEh{u1xF*Y%Oy#N$#QQ-1$LFztn-p!ZkH#urMl_my2U% zlE_w9QXuYgC;H-w_M6ygD$lcS0B6L8sW?TmFpa#cQ2sfVpR8tq>b));fOnLOz zr?3cfrzQgAr02IzXT-a!#Uh*9pus`MMaF0gDkJojp+&i7)Sq+!AT2vkun(PwOx^4c z7s5`FjK6NY@Ftzb@lMhogH93jv%RRnY6(UJO%5tYP?6%NQ1EIxRinnCpWozn2pkYDhY{tmd!){O^D%$!QMd8{(+;R z1(eq)d~yCbe?kLLx8}4uSNWCBo*Owcue4NE{qNa5(!HzaaOY{FbjA@wxx86{ZChHH z+>7c>Fb+Gv2+M9Lg82wDUW;G;SuNH**GQ=^}OGtnIie<$n z^`}y@ROWpN25)~Ad-tXrCtF}^t`|GZwL1`5n&q;(iS~->V~ss~OIg>dL)V4dKPfcU zOHjEdjc#0kd(%tIPG!cYx!r-L8ua0u=1BvlrWMp5#0PR8Z{9A?tS~ag z6UKCnQf8Z|wpI!6$&s6AKW!Nd>4@~}UB6icLZ)XJapilNS~3)MpF5XN!>F%O_3-S3*Cn&jFWH~QZLoL~)d(=s?LZrMR_5g(>nIdgDZx)ZUE z-k<<=N&}%6T~Kdqr2Oe?s}^X67YL2<(+4yS$?L+JM~1V2z~?(- z_$3WEc^E3V__6twZ5qh+pnh`O_SkB2zC7O_N5A;+tTRMxpx1-#$S-2%3PZY{oW9P} zg~U18VUoGF@J$JOJ5{bg5Efs>JmETQynHwm9I|$P@GS;cP2l#AECrD4R8js4-tw%W zQkk*-WFXj~*=Sb6A#Zt}gj~5Ow91xf9@6HJ5%eia7;P$IesR$q8cPylf_(T;Dbq)| zXxg_%f|_9{R3J8+acFS)cTX|jH=#B4kU9At6thjmbDpyuJ@6BvQLve~6ShBd($k@Q z{endjJ5d55l1A}!*ZkR^&^F)M;<6Pwtz3)yaI{GNN(4rqV}Aa)|Mifg*5?PUqfwh;`fAn^Qam zHTHB%k6J?RfhgNNhW@+A1i4crR=8u7yEL4LALD^zn&<$nJH!76cHepG4)rzuAIlRz z4{4<%`5;)l^cjwctIvW`%qAG+e5TVEs%@xMU4=tE1^?xMe-fAAsd8uBF9Nm;?0?#V z1pe>D<$v6Q!~iZ|V#GehIM>wRORak`kHc3R%{`&dQQEd^M7kFQi}(sbY;7x#xbMgGdh-gtFBj zYHFd=)I>HnufXf!dU*V|Ql{yfqsQ~ZJ=vn(tm%+>78!{~J2@=*mSb%W&D8S)AA4CO zhEV!eMyl0A|KF?Vla~H7_pvHj>%Y^PIu(8ocXcivb1{1QM5$KOeVjQ!Hp}<85c`>s z=W}uMdjZxwQ@)u>Eo}&K40e7|D++0OL*owUb?H|u>8jI?t>9HP+y%9WP)>=2}lD~zroG*xt( zwdR-sPm2+or+TI{oM~24D09d^@ycsx>BZ?@S=S#!br&(4}NqCc`Ozq~K>h7r@J-x#F+>F*tQ-M3^t1rrR;QC;+Q|KiTl zld$dGt>E%7`%wg|2!ao8#TchUOOx9)P zzhbD)=|lW_!{&OI!zdOnP8f&&RYnzr*!D@8Xb`_i%8ai)vg62X-Y1B<5R7gh{|POI zE-UV%FJ8ywf8=#A{@JHyoBDv3*U7Oqt1J@L3dtSnsFPzJxKx{dfQ5i6(V5 zN7Znir)<@5UB&5u&+jV(z@E#=N#*k~K~k?8U|jd*c+K{WIgaI8!aM+F03gZikfNMS zOYnyZ(M)ml-WTck!#z!|2FD)*oY_2(fn^EJjWe>T`SI!+A;x%5WHnng!-~Bn6Ib`c z4O%3BLjh9bC#YSr5Py?0mi8GIx`ECZi+O(+n_JudxWkdj?IbIuD3Rf|e1CyX%zdXRDT;#LU->$L>+(j7d^=5Zfp>{&T190pNJCWSljaBbJ} zb82@O*Ur)n<#It048u?sA`AlBVE|%sasEr<2|aIU-KE1f0p-ceoq7av-*hcPo8Iq> z-Kd3xwR*f*5T(pO$uwoiF)(8H_ieO=rpO3S-)~@mUr8w`-5Ynh!8d)@W~zzt5fdNeSLt> z-Fy5ujQX*g!7d-%rs*nr`)jCf(`qgE<;=#5d_hNkg0?`zQ%HPae`>y7QQ#OaRn`HAA;>z{&>6&k+9?xyr#b;e_>^pjzx{& zBxoZ_=xaK1jmjbCDtLe%e9D_izD!6B-t;T?T|Ydg^ilN*d}du9 z(K_sr!UIgf;7=vts)XP5oc%bx({^od(cx1#uvG@wWz5`~>DjA0Y z#&ferTaLE-Jj-*x!taWZ)?R$>5g-2;`$7L|(4^FSo>X^lUhBEJoRHp;UHG0}Q7O?&4PLEINIa^tR;a652@`7wH3U}; z_ndH}X;8@Ti6<3Hp&M#5;(g>Yn)C@1nZtmdw(D-FM;r{c50L6-cLh&Ewzf{oeGL~UxQCrN5GmSmlqglj%&52)kY>j*{B~-FWBP{w*HGb(8g`<7G9S`ZMj%spv3$krv^84{bFgu~j z70;21E*#kzaUQAHFF~T~O5+80tva71^$Gnb&x${;n6Ow-GG7!hW3bRl%65T`;}SNr zKDtw3=1}op7C5!0_$Gp1Y+>-Py!(GgYT5qhRr$ZelX?a9##&!G@`ZkBVQl!?BQkhHStesG(d!}{#0To)^NWa5C}UeUDm zFEQyD#mwiT1y*o5U8x7-E9WVXrPrLlf6vD?za2A=-*}sor+HN{I^JhE!n~y0V?2h~ zx2JrGqqm)N%m(S9fU?H0SI{b{ZE0-deZEJFG`RvA2hEfy-c89>H`a63&s_ALw|taU z6SixZHqG)u;>7%SGC^|IWN!9i0qEaNm5w(v*#_muG2o~*Q|HJ>VVk8Gr46cKGJan% za5s;`in`4C)$?iJkN4fuC%x9F&GgniQ5zlrB%e4YyA&V)RrWH^PZQyXY#}QA&pzF6^AXg^%ot!#u(EblKava>xB>& z{1uDm*!hXz5L@BHApw+YCH9?b0a$gIOmJW!wUA9G4HW<;8C(p3^~)kQXdjMWxWD+k zqtu4=VvDW0O;u+471#+37KW>saSAdv?D(TI*#H}4@RSS#s_fnMgIpny7+~wxwD=mv z4<2dC<(NnWQ~L9J6M?6QM1o1g^A(R)|0xkFs3le*{V!$5I4j{MCETq2EnQCpv%MzpH0uTOJ`BE{V3!zQOrXwnpEr99$3!Yks^42eno_nF7XDc z>{`=nNId^&6F$S?dY<}6(w8NpgYdj65)H`)L3vqxOF>f9KF*j!%WhM)Erj+3h|G_` znvcj+cD+f}h;!(^O>a!Y!ApFR>*HJy(~dQG93dh>#nO+HCsE!lR> zwmHLg?!taf8g$p<&()RL@ggs)*Dp3Dq7mItmEt=zc5vkN%nAE;sUVr4h$!_)Ey4&G z8j=WgVbF7rtDMywKQ^Kxr_ayq&(Gd@*K|=md?QbpP(=Y^rZr0mJl3DRuk<7fT z3wU-4aGWiilntkPEavFIRXIr>UNh9|73%e|bv?YMJN!sxUglKB()-C-W7?FK^(+@s zd;sloqAQ@PrFwUr{>qI*a|#htm6{}ORUua`a%H2f-lc!&Xjm?SXeN)I2iixH#T-_{ zJSVXRc^F4#ReuJx0ATJXDhvas&Ve1n3}^yHK148LZTIK=gwadt^w%MKpK}bJq-LC zl%u@o!6??*H@xO^XsN%G{&6Ei;SY2?=COy%fEw@+dq89g!0hnBU2NFKn>URcM2o2~O+ zPQC4hny9Rd6nf!}AGn}eu~}fTti0|zf0gfSjbe?Q#@pY8>G~(Xvzb;CvH9rs@&Fs) zJ4KAvGJ;$hwo8p-8?Q*CFq@3@zqJ&mY)tB~%uF?o23=}}(#hBRF0F2{>@+)O z*rx2nZs$hxqxA^m!4wj}d!O3`K^a#}8I12>)1x`(#B88aLf$u0}@;!!l zlKu)J%zrt1U%RxVQ=jTQ4!TCpW=kV&r{57|B(T@^pxW4HM!KCQM}WDtwuQtE91X0} z7<3rCNljajRyb3^O@;pw>}&Tm!F0E{4<#}<-X*wq^l6O4#OxC8BygBX86KzAFlLM3 z^y=8Y_+WuQ5Qw4zxIKj*&qGM&_e5KZntr7|MnoSM`^YHk^skQ?~~ zqf<-2)l;6tU!&bPvGNMyiI`gq6FxR|v=pSB`jBtdEE|1^Q4QW}9TQkK#=Y%aZe2^l zsWvBjsD(s05DxMz?wg)L&CikSdME6Q=0S628r1aO+%H4ubRjZ3s`NVt6x0X$&}9`a zRIZLZLPE}$FM=cv94on-zO zW~f=K#y|G3B6E7Rvb$!`tmgS=(>B!3yk}UGkww#snb)$*cVC!pZeAo4h$-g0ItYtq zOIGY7h!$EcZpp9=b{W>V$Zs-SiuP3n1wT(*<7;$h^zKio6qBA~Xs%nd5>PZ~l+A`M zY+%+n_8>;V;ZXz`SU9Pg`^B@KFVFZ`qRRuf$*GSL{r>ce^BPjWQi8X9h$)xy>GvIe z6NqP2;z6OA&%ILdrSED#jehpqd?5ch)isGja}BkJ*i|C&$0J6taSWtwm#A*I z9q~8xV4;4Fen(w-=wmyE`NG>z2*Y{Q0NE_DutuC?=Gc&KR98CJVRq{GV3n7l>?ByU z>c5nq%8DOJ{@x(ZKko>2h{~{@Ip&9dp}#cxlB&sRmvmmwM6rpdlvYgs3{h_C8UKXe zR(<{81@#+vMAUc`nV5>Pf`3M2-#Na`3lc|k!+jRO4;wC54;UBS)ZzNT{Y33S*UMQ< zPc+u$eIsOcB9DqIrAK6MVZ5u;4Z83o|3R%i06OZ+sO^|-Qe%V&K3K+WEA!@mk_Yi) zsP=$ zq)HV4M>1UPOUB(VUq(&*oseN%i}SB5^cc)z3%oNwG=<7)Cw_9unyg`>x{OT`x9_00U;TQ;~3+aXt&l6APj)LnBz zh7h~KeI49pMW!x*8vxaD*Zu$}a#M1KJ9g}8!p8e+eyk33yf)Un(R6U53HGfj7?jfG zk7CP-zSm{r`BANXi%NxmJ5nsChuE}>ZawSmIVF0P`6-1Rm-!vHtMjIs==r^$qFGNY zG};IhrCFdyzVQDPN)wAVh%FAtS^Jx)cb$`Fn)+?jrjjzwP1ZUJA2#rI$(!;K7oAXJII?0lbb=RjUx$~^bceAgZF&ZWOQabj5cUraJ zaioSvS0k7#lHE&ube6HckoUuO8@jR=F7nGy?A0+Z6i69jE_`Q%!}R38a)xQaXEPlq zy_n{Gzisk#NID{~@7o z*=}!VpK@4PUYlK8;)&}zuDiyAm@@w4=HrSCzHN5ue8EG=3tmj7GCp9bfql&aX6uW* zlMQ)#;$=Xi<&rN)ALP6dh)tr||4=rq^Tb&>`LN-rgMKD%hqEO$iQ@U0)6$y-x-IDl zqgx^O-cN2cwn%-T|3=qqa;D`77ky(eW%H=Le~NfbYUbE!i9)$oeJdI+yloPP;ebq?rTXX7xkapu^ zX`FHcdG$1&*AGi5r1&b{snnM@cx^p^DG-&(y22G%J4AVF;=8yT=k(?VZRqgwit-z~ zhI%(o_IZix<4}aoR?N@x=J4+Mf{h3jichQ{w1V=gHhhZ}~vsXYfjr^B9?-wfaW`lq3MK2iVr zMP7f%KTqI)&SAb9^gsFkG#)qnUw_+8GfRX$mrA$0cMjcD-hDJ_b8b(h*_R zlPic31J#5}hGXf6(%Wb7B=!Q2Dt7ohN3&FazH_hf_3$1fYHXCIcfo{v6Y`z+By>yx z|79FC%aTWg2!6Dwc%ZW2Db*MCM@t8;2uBvjJZ^`l58xDtD zL`j}T#wN|7UcAC0iI!P>3?}^_1Xz3?B>NGs|OLNp5Cb!l2M0`bL1v@#0p9NlA z-{AdLq!#zXC-zEs(kmuu19+?~dq5;M1NqRdX}5>O<_lWn{eroVCl;1@82X>+82#DE zY6bLA&Z)(C*=*fU)$0?;(wV2mZparx&D30iv4KU(hBmmtP}^|QV;yX4i9+r0NwH((>I z#b@4ue}8F7d?EEU#lwePmcwO>LjP{;6a1e70+Nyb(cYIaQVZUHf~x5M=ge91U$)um zU*@(_4tC~p4h}YMj{lZL$ExTnE(oFV_k&#e=eHK-KZ~ntp|rCj1L09nlfem6joh_S z^EgC#*XemL+2%1sW5_j3ua_}I?wjG%K7`}{a*81rIwkehxeL& zXFWn2FIu8ywXXfPPQ4!bP~ZU|pM+N}H@_7_%l=gC zXkbGyEW*p%wk{vCrCwk~%|2lQx(_!m`IgQLl>FTo;7PWz&_mY0q2c1wxXyEO`HQnf zXVRc$-uB7;>FX+z#U%$Z%0=M=L1QLPJ!~=Im*fH^UH?(0SC837x`f;r2pYH~TrWHD zG$jUOm^ADtZ0SlwsjNuafbz3!vI;18J#(s862AiU$)sE+x+Ml0?cZ2GcW`Rbn1Z#f z`E(=>m{&eS-zzex?01f&PWa@{7N#|A_BgyMco@yoE8ZLb>Tlo@W704w)0u!gVGrfa zXU$zv8qElr3@Eg1uqcaUT!kOd8^_QYeZZC)_zk!=y+FHIwyJlD4r5m#dfpI>7=!Z+ zD?R_qo=8LngK7Ay7?JTGixL0EB>L}S#D7hd|HCBur`|*+Z2CV~shgrsE zt|d*^c`B{Bg6l$cdCexFp*`?z%FWqvu9|aJ1Zmwg@jZVNNag}KA@sj(Pkgcpb{lSg zV+t+!F}-=k9FQivfNKrIoz|XgTA_a#JGj(JQK>IH0jk|6)v0GZ@euVu;qI1vk78F` z|Ddi>G(91(pIMhpvK{ueZRozlvZ4}^Jw}u_LBYxTm-!p9(epuj{^^t!3X^kzih55U z&>Q}QAKa}wjS=$kM`>H@;=2zu9xRvPK1Rx5sY>)=rfXJT#gF7IDGz!`iZsn>I0d56 z-(b2Bj!TLOj)Fl4|1#<|#wBn+{&J{C{f`m~n*S7e|DW#sx3HVk_VHCc{QD^&otcyi zK}C%Y0#cynBVQR2A-o_0t2Wn1r36ZqO;Kh?Hd-+Xt#o~o&C}AB<&tB6-%y>ERsjbz zDJyrG$YVM7pK6PCdCFSf7}R%FZ9nFx1SE0LKfj(2m;E~KyuRnVcIoasZrhLN|87)K zl3e$hX~RL^-B2hCeWhVq0Ana#*HQSJq+I;94_O@1hS@<4wxW|jlk_K0$*WOQ+B3Mz z+R=jqTVCzCJw-~Sy7uJ!Rw6~fVI|)w?58WEIu^%ozUb|o7%@-dcpOD0bpx#}NB4eh zOHIAYZ^#D-^w@|$ZTgT?lqv>&aD4V;s0ul*Vrl*StUH~mZ`T07o2Ylw!Eg&6Sj^++ zu#`>sV{zLVRD;{WczZDp{radE*WXQF@xA%*&b5^rQ<%OO(QabWWMm^D4Fu}jSj(;y zeQ)eG6tPifI7t#B@D%&TUENN66EKw7=@dm^^U$!RVJSU0c|(xZ7CGrCs0ulb11k)u z9tCnkauXyI8E`Uv)FCJo=gUE1lUmH$h0N*>8x5n=AxAy*rW{8o*=@Wi3gl>~YpL?p zs53g)cHc3^(h(H}bSgt&M40nddux!)nJvtfU79Y%$Q6?6vC10N+gDo=)Q+_$Lz0wa z>nhVIS5u%47e8(-^pzVYBfUM%7YYLH%$-q|aKI;rVxzXkCHR7k%)?d!e%^))(AKAy`iT6j87kUMKZAzx zd#Wek-_+Si+MRSsM0s)@ZYrl7nVlc}JE3|gR2EY$;^zJx6&ATOl+Q5;h4r{mpxL;C zs6N=J!rF0X&Izr-Jrmf+AS_JGQ)HV^b8hb&=ycrq6l@F~vf4Y`ZeimX;^H|U0&Zbv7K#OlgNdq{E zwy6^0ucE-)!E$Lx6Guy|--q_sHxSxNn*A328`4Ky>zY(82M<{^n-(ldGjnwTP13Ug zRdZjj-UYrlX+N`9D*fJ^?dO1qzdM426x48=g3{Oh8G<#(Od2G}cGsyZSLw~1&Al@; zl%#tD_x>AN6HJ6VEd-GEN3KS|M~aN77R_j9omZlB*>l#UYi@AZ_yA}BiFqwd!oF~D zPQnb}D?D~|Kyr2dfDcd^!`~%I}g* zQ!^9)84j0oHg9IJTr+(ou!HMM?+Enfnma+HY%TYXt1A>;L?sw>nO)+DhrS+d73(h3 z2}y5PjQk_M;2qz>y~fzAA@TY|l~}CPPwd2*hoXYo>&aC_s!6QbiunX>(49b!3;`*B z+d4OW`YuZ%gc?NH2k^p~il0$#&e%!2MaK?q4JZ_V$AmhxQtu0{>S2aCPZnd0rrWLD zU`qcob2#JFHn+Sz7Hy{X^W7lzRO1>8gbwl4?Gwi6QIZk~v1VwgY?2b2q*z9qV?i*E z*r{QFGnMEuWg!@1&OmY0X&U3!0HGxJ`xH`j4W4h(W7CLS(0P2x4 zdF*YzfR<-IK)}bIKpcAe=wg`OuA^O%GYSRr&Ev)d+Mvgy4G@Vv{&!M-Xgk{zdK=Y| zv9Vhs<%1zbG3p$bg}|UrjrCUZ1{8bvMw9`=pcYi{$izuRII}%tQ%(VRgNpo(vhqG} z%oASF6uWEdGOebwcq-8FMpkXM%|VvymbO+#i^p0b?ea{B-E!WYKrpC|}i9=wX!eMSn_e@ml|g(%ZiVkdsC!PB}*h$>?*^ ztha?b)8->neU7Iy>Xef#$#RF;w4~NmlGp4e4U5u^0EF|X4PPLJ%`yx6n)H20_Haaa zx=OHu1~ol11|YEfYS^kks(fPKi?V11I*?5xry>ZIhMpqZ-Ectd_3d=c%={-4)2;ZGo zWCD*#4J7|%fOL1P*c=9j(iHtM)~dtgO-^Zd;Gf2Uq{ugaw~}1mpS^{GM_BZJ{461g z=0Ry!P(64NnWM+jXnb7!Bcd%FkToJ6nQE2CWeX{Zy*Nvror1DU%k|sc8SA#M2AW$y zGLzvuvRTP-GQeKIJ2@gzZzv35FV`h^^k=wiIb~+di7|p%{OS=KSGi=VJ#z=$git6O z`z~^@PHltaBUQaWYBI4GTSca8`bJ-v_OSb{&Ds^24NV_)MVq<&JjUlyjtwU}`>U?I z{i)UJFPF`*W(>-~*4Sbyz)^{m#{E7V&!Ch@nyOxU#G)ZjZhJ8BLPSm@_R?w205!o9 z(?>7X+DEHbGkq!nU*6f5tNR#teHXO0)CMfa=H5Awsm1<5;+J9Rd1z5Ptkp>E<3q%X zS9dwzx}4$X4>`^``H&|!4m)cHJHvCpWu#L8<{elPbWWL}Y9+z$_17m?>gXuqcu&it zm6F=1zaH9AAU@cB*FT-y=1j&4ncyI{5~h7I9p_XuJAgzdK1m>mJt%a2plM1#!SW)P z5EZ&RQb3`cib(vZJ%6wjAIU8gGF3bD7x`?NS-Ys&{m&pTt4?S6P`D9S-rI6h&O=hP z&btw&dY&TC!HHK_Ouy#zSudze&2JSM!-El}A!O|xb+DL)G_zfJ7kuN_i+dfM;YB|w z8aSMCUP1io)31scvAG>oTxzY@4__MOo@O*<>JyoG3&lD_WXwO_70EHf)?rX^%5Kp^ z?IS4!yJs|PG|*{bur1i!9NgxD9};3nUe4fn`6oV@+#R`^CD*GtUf`A2)bvj^f+qC3 z#p0dWB!@AehMkMJgNL!YbVleXBV|~1(aIH*h@+@qKAQmq-0b#~1DlI7WOK+E?>K(3 z2xG245b9-ALUun5DSYCef^n@zz-NqeXIWlz>k0ZuueA8p%gBEY{R~VbZH2nwvN;w` zE<^2W18;adPz~@03CPYxlAlHH+Yk{MM&Y3~C@j0X2A9Y}RR9!D#=2w6k8)Bp6Qc5E zir!|i@QX@9rzxN}Q`YrHrjO!1R()xsTf&@~YMh1bIj+Q}a>mT>RM(!zZM}2jpn=;M zr@R}7`PYthp%)zYFz-UyFZ~yX4o69$PECiFq0r}VT6#}jEO|_C3f}U* zM_O`%hY*$<=2{s0$9mclSrgg#PP@Q!d2Zc_amG_kmiHk4OR)jpm+Ay_pAXGc={ot! zcY{*R)5lH@ ze!Aaqndot3VJA55Lhr4TCCIYWxJT30$|0DqUC%jTld}Oi6OKfsG4}9GN|&9u$ z5=0yP>ISXrM=_#9hj$B&#AM4Aq6g;5x~z@cbTn*6rADOmC60@|9}L*n>CKx?+sXl| z3aIEX(d#KS#j_TX56e4sBO8s8*Pgci2w6M!1fU$zaq+rz%;L?IMf%o!jVe4C=3&Lq z1eei7!f%a*SO_1A7?j;zebX8rxNhhrOr)WAXh$V=R6B|VW9msF``@h3!yNw@-?$zT zhE%#>$p<#Kqh-!(Xf=_XX=ZlQT~kTM;W^5gs-?xg(~ z={HvhWZ11zk0tI<|MzQQU;5B~fG>Y6X}>4U4((mL9e~dTYZ}?tz2%*W%LQTP{)*)G z&95&>ZjG|!rs#Y7Hhr4`dkl*URxNXl(EHz=5oUu=bC_=IA6c_x9Ea!jk?NlkFkkKw z@Ns-2ub*sxa0mQP$Iw2yQ5#-Yg*_RtB(iAp~IG&fSyTs zBsx-f+)lC3uyp8#1&$)-%QIr}|#7Zn3PfioGXY zOfhL($c3ggbd=VGWeYTO$xasHI2*X30qu}DDpwxRJMgdest97xf4yamZ4EM zndCSj)UG(K77KwgPe$H7cUA^)w1M~JiBZYej=Sn z#hr+Knqc2wLE4H5%=n1Odq*JvI?DCI_V8*^6xi?1{X|ZVToCB1m{LYc?FI8B|HSWI z0}%=s1&MX6q05bdh18w}?Ih7obg(Ll_ z!wPMqEA+1j`7bXp+)x2CWd;hO84Dw1(A1l`j&f#BhGJv}N$#jpT<}VXQEtg(jQ!Pe zHb|vu_Ap+dkFN9<9HV{|hT2M_VVU4k?Ji|CHRbywg_7XQ$%hWLSl6bnET@T(lOl$Qy({elPebpw{qBr`HZf!rvd83w< zA1c8*wU(Lg4;Wp1jCCAk054?O>eTRQbF{Mgyt3VTIL>-gd6RxT&$``2E!~h+BMvaw z>sKS5WccZ+(4~U=q9w?=c&f~NOJ@_nJC2`2oUsa17{jWPz6g_h2oAB>7lZhC`)bRGhIldz~r2=o^{1pp7YK9-$EaWX;u4W6b=7_IuPN;UL?$(XT4Ghq=xG|)Rn5&xu zeSqS>G5iN-?&-;Ui$(eN?U~{~;mjoeGukEn-<-&QL%G;v7EGmfFbLGK{HF%8!!5@4tJmAs)wjB!$RBy=j zf!>Px)GigY*s^vy>r4bV^W@dk)Q*yJC)6Rj50P8It=Hd=EVT*zgL6yL(HwveL5z?^ z7|~_(TE9hBNJp~cew%Nrd^wD&UKu}-nBF(m8lKvI>4RlNF}H z=3u1X8}SL0ncbUSXxxhtkzzQ>V@WM0>f7 z$IpTDj&Ec#C3_iiCY&az7`!6eBHJ*OSo9r{o)Zc16{KuK5)+ zy^6)_cdG8~J}%LwX~_*$K7_7ld&B39Q0Y6r*gP`izZTOl5)=kk+hr0xB{26BldyDN}JviUAHlzl=(ukp@k37|4eXe zqJ>{tUr_GUe}r?1{+9{)AqY4+9k%{zV2D8zZaw2 zCJ-j=ue0^JJNUOYQ6n=er1&%z@vrNca_b6HGk!6xnp0G+byWSS9(DC_b}yfgp{O2P z<=6e$KAHP7qR=VR+&vdyVrSxHA7IIYGuXpHn+T>3M^|H@Pm^qkx#lSR zfn%F#acLD_nv`gF#^H8(sll>pH6%Bt|2|wMNL*2L=c=CRdP1YYdprY@XksM?jmE}ocqW>$%RFkwVt6DxFxeo{m*K-BN z!`+Rv00iz-5`D9FNeN?<94J}k19QZ9d^E*?6=KEo^kJ<61d7bn^ma;X@dGvo>E!VJ z%`-72_4Kl1Fk4$3d2OriZRv~yr{iTM^R`ecYk{muXCIhdi^bsG5yV*4<90V-wA6!D9jNoRK7*h{5L%;EcK&21y&X)4BK(bZy0lw+V^xjak& zt3!#J53>N*cE|c3fWC6>oGCLJYzqA}sq{0s9P6%MQfQiJ(lrreJ=%P;=S7VdUuK%Z zji3TMjCNR;^0Ehemh&pBh_bkXK&PB3(>c=76lY#S`XVoJHOcXe(m0Hn23N8*;xWTW zQw>@_Fy1>foNR}gGiAI3*K)bqE!oNw-xD!cEYL>v&{P7>WPVI%n|ul4*#R{{!4>2d zV6PS*x^4WhiUk=4n`zh1aH`yZj0U9U)rs)%8C2h~@!a(gVdMo&In=N2qbhE5iXS8{ipv$_vdHxd4T)*-8Ji&F)ZdFi80ys(qF8bg%XGMhzowF!kZ>e>qD}7x%R9L zpU^PsOKTn@5Vi@GDKY_Y(@r0x(|IL+fY!{#jt}eziZ6Se;=HhdC0v~{sU{S~RlImR z0jFo+Npf&q%u>uaUCH;>Cpo^qP6sOZu;u>peejBOUY@}eDiejqr2HP1_V*$6huT20}kkr1qHK)N-VpvbzM^&Asmm1JGES`noIx@?~_h(eYOp zLYbo5#*=;pD}KfLB_6$=mc)qA?wKQtwpU%Dls>*F^8>AcQ?(UNAZjkQomPR(6(hY)iNq0&~H%N%mA>C|J z!hd`2y`OPCNAEuw3k)3i1*oO}g1c#96bNY8@li3|SQFcTWPfIPqxThf#_1oht6o1)`tz!9Z3W z*B8!GNutS9lM=Cih>=@wy^*62k{MBvg_Bf~iN9=wje^H%Mk$)cRdUU!zN&*?o#=m5 zB0}2pz;uW$*M{A4d~)#Fl>u|NF%CmV+jaM9%0C$ROqxG^T0j7<>m`(C4z%bIroc`~^}J2u;VjA8YZ4!&@-L+RA^~2R9mn}%t{);l z0bz|u3EwbG^|;EuHR5;O3n8BpI(XeeGi6GhAVk+y5V0V1Ic0io=ubaffJ8c z8CCeEBAAWO=^pZ4{QVc#UJ)-j*Uyg4yn8kMp4~dQ4Xq-WgC{OSLsMgr_c(}h_q#k!MhChDj0 z1BO>fHx$z|;p2m`rc1s&m4uF8D(chhQah$K{LyDi{4)c{z^&ePhNX|R z!u3p?)+4xtk$Re$+)n{G#AEGJtJ{ZIanUIMQ2~(D(&=@Pp2w zhR98d>wBgVNj#HLBb%%{7zXEkungTwQ(v-RawhU=y(1iek$*(TLl2s5%NjhWPLm#g)VdDK%2MV{rfgc4`X&B8Y>CXu5pNZ2(K zBL+mNWn^`llU|SZAgnyRX5_m&Mrf4C-=1pu+LPF9h1A(^v3BeHYJ^~dp z!6&a;w2+hYN5!8^ipF2RaC>%|A|AZ^X)1o65x?TVx$?vrSCfpUVBKwOWPd-S?v?sN z_iGXTcg-fbZ;N|UbUDjQb?i=X8v&^oMUX2wR|rx`gY#>dDatq7MD1|g98dQy z-01N%92~3-T6}@&Zqf8e28`oXy>kimXtwK*f;Oa*x%4Ksy{|D05UdTVeV1)nyMMsKjw9ZKn$;Q=iVkai~|Z zC@$&EV~3y0J6Z!TBHmt*aVK_n?c;k-5-Fa{-b6~Yl72+H`e16mIJscj-XwE7hBX?I0z=P1>gP=|VguvtOn9ua#y8;(SyqlAHo)d>;g zEx$IM3;wWnU4Nz_Y93K=1$ltNi`SjdQRAUc81`PI3nzUH$zK>$K5;t&o)O+fui2Ok z4#m);wB0ej2we%qL*Kiw6F7o zBgyz;=t`Jr=(YL9U|s(W_lqlFyTJpKrJmWB;I0Pa^qt++G*%egr`t9Ul3sZ^h(i5*q@!vuCVk9J& z6`;S5D|vujgAFDg0cNzd^U8tGl0&>pi_J#e@O$MKmMvsrg|&xx5BvHC)aduVG^%UjZGc_NfNnQ*$pY5QRv z;ZuJP&r;{L!qDPFCOtKfjxDY9j-<;GVh(;-i}!0M9mEihS&Cy%Em-nOsQ?7rot_o`GOd3uQ9#yhB}jCRZCk z4Mn@r&Q*uP3okFB}}&Q=-pBnVtcfi2?XbnufKM7zKRY zNOz_ztk~m)ZE0}N5976@0NzuRfz9SesZdFeZZ1jKY$d(S`{p-g`isZjZw)@Q2uC+c zGa$5uy4xJV=^S<|P|^?HYZT=A(xj{pMfI6JJ}Ej=t$tqz?N^T&}@~oR~ZPXGsl2j>Mhs(yw zQ!qGWKyo{tnPQc5u`em-vFvqpDVtHv2u45TuhO7C9#Ztu=BVG4xBODIydpW3NX>0e zDQ#1x>=GR{@k;KrkDbwrEPE`Vd8tlc>@!y;AU;a79bfJVm-Q8 z`@v1-n>f=2@PmDd;MRu~c8@^2RYF>#2PnDCU72)grm4rmnb#I^Fe_BU#~({C-f_>y z6vJ5w1mEw}xU)V_{?t#DXXM4*R+3FcTtK_laL>_jX8^CZC^t=iT=-J`YKrz&&GS+k zveDxV{MC*mUm?F3(2?pGY_|L`-{l=2dE4b<=PRTR9p5;t5d2%~(_9yV2E|U7EuwVo zBM&CnFg;wI+Q_zKZ~#x!g$?x;lAvKr;~iLq(Y!=4QGxoJLgM@L>G=r63fs(c!JAR# zk@=t*ysb0eRx9TB28b^X1$|E`p|JRnmBS=arU($n;ll7oKuN+h7E4E@EIlT39UY2_ zcv?Hg{gKng<8)=O!5hpoHD0Xq_(Wo!hn(wEn4u=;6vu>7tBh0Y1V_};cPC9zR;X;# zuIY(~7&4Z*dj$Ea!1t1O*708cg<(~I>3O^0(G%+Twx zs3mIr_-0xWl8(9pJc8yU2Q#0XRo}70#0DRigPy5s3%F<25ELEv!Awkmm{~~5Md2gL ziA9_o5L1+@ur*;_atvPdO>N8w1h?$U%-!#4s9bw_6cY6m`v;B}@5&xAf3EWovO+xm6o-?f5f%S^?ZUJ_P}4~Eoj?scKKW4vV?Rcy|)3dJ&)TPY>xlv+F@y`GyQDb{`E9;bNONG?nul`o%goNp9Ie4DPv05{6Ij z`F0fXur3|IQKdmGE6D=OUYf*cW}fi{bf1$zhB*1j@{lu3HQahK(QH=8o+VTr^7aox?UIZWa=fse^;VIKEQ| zi_o|R#{^0XJs6l?^4hfMIGO<%14I|($;Bul^Y}?ZP#XuqWM)HkNXGs6*ge32HJlMW z4ZfKRqS&9`nX@A3aXG{pO)PB76}yu>^V$>mFo61P3u(dCyH8;Kc6QHUO^*?FF~L2A zv7IqR?S&k1$Y?I9F^uO$RaPb{*5cyHwJ9hvKEI|g`b1NS9-*)a-cA?0EJ40&-q{)| zeOxRoJdox8rgmNMh-&x*=JDkvJXxtOUWOd^3)CXcVwYQF0wSH9*c#yg8@Q{KD_|IM z4+~m7M97tU>#IujLnPNS8~c2p7ZK3bC0$u^mI~V@nM(0Wbf&Dr$4}EogQ}w*A=Ely zlbiOwN@v*-c5n3@wKo5}9lw2TJ&JoUf|eGiL=ska3IEcdFoC8P+`t~Tl$*x{EVKgX zz6pj6K}g^P7VH7Px`5~@PrG^yh|-H7ggfZKzp{b%ExJqSs zq3rzX89-x;*Tvr4;#&3Nth&~{we}bnq5`RrKbs0)2U@XxV}MU`%(A#wU^UMq-81y? z7n&1o5(G1w+ylpID^V}*o>#b7@F>EzI27igEz=T3lsj&L`LTXVL0Kv^@fdW1TpSC( z9HVTbHzIK$?*sEK;{b_obvJ#m_+V4FY{MSzd44Lvgv^uK&}x|N#V4Tmlt@FHuv;qB z5#Kol@mOQ-VK2@_`Y5iQcT4WtJ$@X_k6nq0o%j>m5YM$@G69z6Adw#Zr-MWcC>TJo z8*xlB0`x2P`&PZdI24ouoU_(Vn+#Ej82^AWuXKHI=E^2!<>37_e*q5T2-|6}E2XV~ zL9)47UX%SPe;`XR;E7Mf10t(mXh+U`hEX46BP1N}-D}I!pStYOmWv4Ob+l=R_`FJ81Pm)!7f?d^n@6=ZTPq{zEvlYGHf6aJ?eber}ljMKIEK0ed zN`M8$51vhD9+C5I`w@{i;XT-wn4yO=DH)IPBu8f1j-W{I;kp!@lddU4yff_u)OY~t zu2+3q9{kpeG`6lPHH&Mpz&Z6h*XuQgHpzGpG5?rW5V`>yg4j8i>_>!qd1XE+BgMs zB0CKkoL`}JyCYu2!=#F&p%PM z0xQ?CPt6`98t82SXp;*Xk~4<@p$K zSCS`3DRYHg9}mh270lD`$j%x_aFx1KFBQz|S~b~pig=W`GaqUm2GKwk_#_dj9&Vhw z%nC~RsT@Y0m)aQSdlab0kyX4EnH}F`S6>*$KCNrZ=XNFZBuZ>z^Q}6Btq|c_6;V^o6?Dyhhr!)wG@C(*qRRXqU}7Om)A{uW#Qc3JbHzD|tx{=6{gj`qx5hmdylFC&?$sDN3e9u@Bs|+{@QsEKIS>CUV@5Se%5uUbK&WsD=Uz(;x@< zbX69Eul0+H0_*Kw^ztcbGO9=t9>JcM^Lr8!sDS<2BrC zGd_BZ1GCt9*jN1g?xBs4C_|gV!jwj;W_jnXf~S?a)Y?lbOIvNdi~7W--QXJ+Pz!Fm z(fCp8Kdg(0IKufbhaU(pSvk|AmX%s!*d1YxHcH8yY~dAabpl4Y$VbT5gs;I{5|o)L zu^p?*93|i4tUuv8b35&-hwN$F$4_4ahEmq23SRNA*{aX61Xme_8=IsOJB_W!T8I3e0 z>VOtvkMwlJCLSXD$GsPhjOPjiuceRFkQy{aXzZZadz&9`zT71#Dig@Pj-z>dDEkPT z1-pk~3%BSwB+VcTO%?_Nb%2EYK#jkg8k?hISgvbp${5y_t%(p?3=>_8P1TqtPCYP= zU4ls@*{h0eac{)I{zAbM2zV_uZ2s~L`ibD1k8@r}$2usWR7oqh(qYON#G)w53(Bdk zi+ZO#w~ISt2D<#Vgm67OZkJSNK}7L-@S3Ud;E0NrLP^Z)=*m)Z3R7yyx6dRxB_PUM^uJ`+YjbTtc?kcU6YF!R zYGuxNyP9$Q0PPpV-0uTzh1ON5ZOg`fyU+w2Yq~o2`*KF_4+rQuIeEA*EO9i2GSI_* zZ)3-+!O)jblc(>7m?+oNsG{zz9=C*9w3n zz>n{V@2*qW!qIxQC)XoC;j)b;R)9N~!|sZ=Y@mC1`tHqR@ySB+s6@p3=nuFH93^ao zqtlaPsA%d^4yux&)2BTWWIG~NG1EJyJGR2nf=^!M)}|tj#2v$!AB#I-1@S^V#Te(b z^h9l5vr+56EyFW-I*Uxm0_&qbfI80Zn#O5p&b{Dd6M+IS6q8TJwcvirVXq{95=zG( z{CIe2$1TPilQ$x?Ip*oCnj<}xmq-nl%y2Y}Uv93u$IMJQ22@sUqYJOyP{UZ@qWmP2s1-gCwBWA4qHy-D$SX z^`83n0;K1~qm7eMZjZEwt|0WLbJuvqK6sNho}xO`4?0ii_b5!YP`A*xV~S}=3!mom zB=>H`y*nipH1Qk)A}sqN+@Frt2$-=}wPAxpo}iH0*S!MYoU+K z`Sj?i?}s)MX1VDvL_25%W2$e6JI#2pw!TACSV~5H|FF3ay3xpP8_P)%z&V8_J_Nsi%qHqZ$I zq2dF2!Lti;5i)V?9;)`J{6y5%ZE>Vx-{4D(dnI?)xCu*-lQX8!Goa}Zzy#(Uohl|pLC-t(h? z=Ib9!r_Kpw)*zbmljDc-OYn(OPN)@Hk>Ke>AkS`|tLuO$gKmO$w1dH)C>au*w_eE& z7ZDHg#^~`Bu0S!R@bvR14)n%v9DI(HxyIW+S!t}+<1e`Y=C@`;NN9w2==+)e{kzH& z7FPBGMA2M(GmB+bTq{AFY%7*2J^$6L=)LRfu)HeV2;_}18EfCuu$qI2rQ3-#R z*(Pis!q{V0L7i(R52QXGZ~bh-^OSU0NlzH;a8+CqXT+%%}djJnWnkkaHFg=`qLK$A5VjLLtPom zYeR|~@NOqcY&km>u1p4JANZcoT3(IMwQm|^lM2y4xdpVJmG7e9qGgXg{e)5dno|K? ziGat`5;VsI0SAU+w4KF%dch>T zqP#=X32KCv!YR2Cu;kgIyTE7j|*Ie(E=V)CWVbV3~eU`-VqG@crJ21Lq2}HrUfAoR3FV5_N4pZMEhoS6m5<;f9fYN-onG69={f#GCPp83pKpgB1a<0cwZdlHL2eiQz4 z_YB4Ib{Aux#)JvgXT#Ma^|F2Amz9^}l{*_EumQ?br5~&}eAyjg#TohL;_EKtmv?ZQ zE>wo9`H0T?eb6Oa*R>iSb#@J-f2M6GufldAgppLlv6d1cR7kdqlpf$1eq?*~CN08r zix1gg_83j8BmC?Y(^Xv2EU7u!-joKb?G~iY)k>ODY-Gs?hu5F-mMq@6Ucz!TF*Imq zNbNrcHbV6z5QHihNw%ZPB z7F#WPwKn=D8^bEyW7h&U`eol@<@VwzQculbgN-5ZV7HMNhGK{0 zO5I0TbKmwckH47!&?C;GG~WB8S)h@=RfD@5q||2K%#%puy>Tnl0d<0_tgM_W;welwZdO!uN=omnmmuJVl{|!ldS(!QmRLh}OOQ zkfY5~9)T_{B79y-)0GfDmEgN+FCCzuTYL`a*!Qlyt zb`mAgnmS}dc;6y&6xT=Y$q_8W-%nO7#GcRB?=y!rX^mzf#2rmdxmH|IGyn2vbtGX@ zGX-_tR=bV#LrRuKubwC{9X~Fw*z&{<*05&|7jhwIo(AT$En>SpyuB+;_TrO)fg()p zN5S!qf^|yA%M662?kBB|WcEpImDh{`{d;P1idcj`dGIIpTkntd4#L$A?y^WaHfCqR zs(8v?ueUM8x?CTbFn>8HT1_6bbsoEd;$#>{QHwx!$%}Zq|LE#c_wm&#`9={t9xgi- z`IzqTSbVK!o+OnC7CG=xsMb?cqPAQK`y){=%16*ioBm|xeDuC&^6(oH+osN@6LPOt zLda`KAN5MRdAV(LH$I2AaV=woUuh)+s8s4-g&*ub+5MoUVoL#9bWcE4WLTIYCoON9Q_>h2h!<-mzi0Ak^`U z6{H!W0(IiohqR;Q#u$iFhZE<~)v{jpX$ow*sCY@{u)4WaNoNV80$JWI?iX1NY@wI<}Rw zIi}zqdfn!+>r*a{p}Sxl{?@B61oqSY~lP7$B_)>7$UMCAOGL zttBXY)g8x&yivfH(nrM;K^5;b;Lf@l1F`;^uM_cjdVwT~e)NJD3OwX0sarAc1g#gd zEz%q)o4aZk8|Z?hSuJ9tM`@g~IjU5}vJ1#c;9fP<3NxHMBd!r6yY581O-pD$N%Z#T z-#@|86nYC{o1ySYr~OQjcn(FiF(N-zCqD_4e>aDdKlifPQKV-%f z=d_;ZfM6D11r_4_$Jwh`ccHz$BQT4{PV~O9un+zU*XZQ;mTWf&4n2l7P<~?Q4>1;Z zLCmlG*gk&|LCij@>3fdl2GE_&*FQ0))HqRZh_I|nK`D`RjiAb!Kz4m0(h(Wstci3M zuz`styQu2Fph7c+X)=v=o=$82FDVMKE#SRlF`D;h~dNT%pgaL*D z1`7)k2m~Vqt8U6C+C>5b>!1b$Lj~QAe>4RNH4#P`MM-9P88Hb(RS9)9C@|3W_P^ag zro$GLf?kIN{T1T}H!L9Dp#O8DAfhNEDWR&yq#*gXt{AtUi=%f>@<1jyx{{iH`u{?~O&HsFuC>kBeZlJ*D0pW80FtrGv59r?q|G(qr zf1OoW%(O{t5R^73fPM_qW12sPQw6E*I9UE>{rn$?oce(V76C$I`(a>CptAOF2lnSP zxK!t=Y5@Xi1_g@H4?tRse*mQJVEg|Qo*PiyJaC{mK?Hr&f4rD*u>2nNH*@#B*7=Xl z)1Um8^S@@w?7QpYZ=8QG(*0E~{hO`w{@(e&0`4~u-)qwT7-hlyKS2DSnBbpkfB$@C z`d-KItKi8uyB7Her2kp*_GjGh#jAe2XE90tfcs0qs=wDv{2AwaC7-WSSl_Hh@%K1? zD2(+p==b_EUqynx8KTM$p#P~m{E=kP&nVx^Vf?ss`>MZ0`A@s&|EOH^Gw%1Q0AIy6 zzFD5;KjZ#ZdgEuP?`agj$_#unblrc1`pxI-d(OSD$9UgN!RD8K|A3P5=lA|S5#5gw z?rHZA82>)X`Fk$EpK-o#0scyB_ss_E{|x6hll6W3?AK1>Z`R=dOMt)YEB^VNf8X2r z<0{Mt{MzyFdvSlp_`Y8KwM+Dyr3C#G#&722`zqttV)r+r%KoL>UzWaqezV^f#D2VO z4dnjP>p#^ie|G-;q4w9B+Bb8~|F!c!sIdJE^8G31k4uX1`j;Soa9aK|#`l}EujirP o%n!7o`Ytj0&(-zc7=Lp*sw@Wu%FMyQ$U$GLpnV-;?bqM_A9CD*LjV8( literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..94c356a --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..3185a43 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/lombok.config b/lombok.config new file mode 100644 index 0000000..14fae36 --- /dev/null +++ b/lombok.config @@ -0,0 +1,16 @@ +# this is the highest directory lombok should search for config files +config.stopBubbling = true + +# use jetbrains nullability annotations +lombok.addNullAnnotations = jetbrains + +# add annotations that @Getter and @Setter should copy from the field +lombok.copyableAnnotations += dev.latvian.mods.rhino.util.HideFromJS +# all the api status annotations +lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.Experimental +lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.Internal +lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.Obsolete +lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.ScheduledForRemoval +lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.AvailableSince +lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.NonExtendable +lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.OverrideOnly diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..5c1624c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,28 @@ +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + maven { url = 'https://maven.neoforged.net/releases' } + maven { url = "https://maven.quiltmc.org/repository/release" } + } + plugins { + id 'org.jetbrains.kotlin.jvm' version '2.3.20' + } +} + +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' +} + +dependencyResolutionManagement { + repositories { + mavenCentral() + } + versionCatalogs { + forge { + from(files("gradle/forge.versions.toml")) + } + } +} + +rootProject.name = "${mod_id}" diff --git a/shell.nix b/shell.nix new file mode 100644 index 0000000..a35c327 --- /dev/null +++ b/shell.nix @@ -0,0 +1,20 @@ +with import {}; +let + libs = [ + pkgs.glfw + pkgs.libGL + pkgs.libpulseaudio + ]; + + existingLDPath = builtins.getEnv "LD_LIBRARY_PATH"; + + LDPath = if builtins.stringLength existingLDPath == 0 then + "${lib.makeLibraryPath libs}" + else + "${lib.makeLibraryPath libs}:${existingLDPath}" + ; +in + mkShell { + buildInputs = libs; + LD_LIBRARY_PATH = LDPath; + } diff --git a/src/main/java/com/modularmc/registrate/AbstractRegistrate.java b/src/main/java/com/modularmc/registrate/AbstractRegistrate.java new file mode 100644 index 0000000..733cf03 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/AbstractRegistrate.java @@ -0,0 +1,1320 @@ +package com.modularmc.registrate; + +import com.modularmc.registrate.builders.*; +import com.modularmc.registrate.builders.BlockEntityBuilder.BlockEntityFactory; +import com.modularmc.registrate.builders.MenuBuilder.ForgeMenuFactory; +import com.modularmc.registrate.builders.MenuBuilder.MenuFactory; +import com.modularmc.registrate.builders.MenuBuilder.ScreenFactory; +import com.modularmc.registrate.builders.base.*; +import com.modularmc.registrate.internal.RegistrationTracker; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; +import com.modularmc.registrate.internal.lifecycle.RegistrateLifecycle; +import com.modularmc.registrate.internal.util.DebugMarkers; +import com.modularmc.registrate.internal.util.RegistrateLogger; +import com.modularmc.registrate.providers.*; +import com.modularmc.registrate.providers.core.*; +import com.modularmc.registrate.util.CreativeModeTabModifier; +import com.modularmc.registrate.util.entry.ItemEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.*; + +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.Util; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType.EntityFactory; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.*; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.data.event.GatherDataEvent; +import net.neoforged.neoforge.data.loading.DatagenModLoader; +import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; +import net.neoforged.neoforge.fluids.BaseFlowingFluid; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.registries.*; + +import com.google.common.collect.*; +import com.mojang.serialization.Codec; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.message.Message; +import org.jspecify.annotations.Nullable; + +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * Manages all registrations and data generators for a mod. + *

+ * Generally not thread-safe, as it holds the current name of the object being built statefully, and uses + * non-concurrent collections. + *

+ * Begin a new object via {@link #object(String)}. This name will be used for all future entries until the next + * invocation of {@link #object(String)}. Alternatively, the methods that accept a name + * parameter (such as {@link #block(String, NonNullFunction)}) can be used. These do not affect the current name state. + *

+ * A simple use may look like: + * + *

+ * {@code
+ *
+ * public static final Registrate REGISTRATE = Registrate.create("mymod");
+ *
+ * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
+ *         .block(MyBlock::new)
+ *         .defaultItem()
+ *         .register();
+ * }
+ * 
+ * + * For specifics as to building different registry entries, read the documentation on their respective builders. + */ +public abstract class AbstractRegistrate> { + + private static final Logger LOGGER = RegistrateLogger.core(); + private static final Logger DATAGEN_LOGGER = RegistrateLogger.datagen(); + + /** + * Checks if Minecraft is running from a dev environment. Enables certain debug logging. + * + * @return {@code true} when in a dev environment (specifically, {@link FMLEnvironment#isProduction()} == false) + */ + public static boolean isDevEnvironment() { + return !FMLEnvironment.isProduction(); + } + + private final class LifecycleHooks implements RegistrateLifecycle.Hooks { + + @Override + public @Nullable IEventBus modEventBus() { + return modEventBus; + } + + @Override + public void setModEventBus(IEventBus bus) { + modEventBus = bus; + } + + @Override + public boolean doDatagen() { + return doDatagen.get(); + } + + @Override + public void onRegister(RegisterEvent event) { + AbstractRegistrate.this.onRegister(event); + } + + @Override + public void onRegisterLate(RegisterEvent event) { + AbstractRegistrate.this.onRegisterLate(event); + } + + @Override + public void onBuildCreativeModeTabContents(BuildCreativeModeTabContentsEvent event) { + AbstractRegistrate.this.onBuildCreativeModeTabContents(event); + } + + @Override + public void onData(GatherDataEvent event) { + AbstractRegistrate.this.onData(event); + } + } + + private final RegistrationTracker registrationTracker; + private final RegistrateLifecycle lifecycle; + + private final Table>>, GeneratorType, Consumer> datagensByEntry = HashBasedTable.create(); + private final ListMultimap, NonNullConsumer> datagens = ArrayListMultimap.create(); + private final Multimap, Consumer> creativeModeTabModifiers = ArrayListMultimap.create(); + private ResourceKey defaultCreativeModeTab = CreativeModeTabs.SEARCH; + + @Accessors(fluent = true) + @Getter + private final NonNullSupplier doDatagen = NonNullSupplier.lazy(DatagenModLoader::isRunningDataGen); + + /** + * The mod ID that this {@link AbstractRegistrate} is creating objects for + */ + @Getter + private final String modid; + + /** + * Get the mod event bus that event listeners will be registered to. Useful when Registrate is used in mods that use + * alternative language loaders, such as forgelin. + */ + @Getter + @Setter + private @Nullable IEventBus modEventBus; + + private @Nullable String currentName; + private boolean skipErrors; + + /** + * Construct a new Registrate for the given mod ID. + * + * @param modid + * The mod ID for which objects will be registered + */ + protected AbstractRegistrate(String modid) { + this.modid = modid; + this.registrationTracker = new RegistrationTracker(modid); + this.lifecycle = new RegistrateLifecycle(this, new LifecycleHooks()); + } + + /** + * Use this in custom implementations to hide unsafe casts to {@link S} when returning self. + * + * @return This {@link AbstractRegistrate} object, cast to {@link S} + */ + @SuppressWarnings("unchecked") + protected final S self() { + return (S) this; + } + + /** + * Called during {@link Registrate#create(String) creation} to initialize event listeners. Custom implementations + * may add their own event listeners by overriding this. + *

+ * Always call {@code super} in your override unless you know what you are doing! + * + * @param bus + * The event bus + * @return This {@link AbstractRegistrate} object + */ + public S registerEventListeners(IEventBus bus) { + lifecycle.register(bus); + return self(); + } + + /** + * Called once per registry to gather collected registrations and add entries to the registry. May be overriden in + * custom implementations to perform additional actions upon entry registration, but + * must call {@code super}. + * + * @param event + * The {@link RegisterEvent} being fired, use {@link RegisterEvent#getRegistryKey()} to query the + * registry type + */ + protected void onRegister(RegisterEvent event) { + registrationTracker.onRegister(event, skipErrors, isDevEnvironment()); + } + + /** + * Called once per registry at the {@link EventPriority#LOWEST lowest priority} to perform any actions that must + * happen after all other entries have been registered, including from other mods. May + * be overriden in custom implementations to perform additional actions upon entry registration, but must + * call {@code super}. + * + * @param event + * The {@link RegisterEvent} being fired, use {@link RegisterEvent#getRegistryKey()} to query the + * registry type + */ + protected void onRegisterLate(RegisterEvent event) { + registrationTracker.onRegisterLate(event); + } + + /** + * Called when a {@link CreativeModeTab} is being populated to fill in any entries that belong there. Can be + * overriden in custom implementations. + * + * @param event + * The event + */ + protected void onBuildCreativeModeTabContents(BuildCreativeModeTabContentsEvent event) { + var modifier = new CreativeModeTabModifier(event::getFlags, event::hasPermissions, event::accept, event::getParameters); + + creativeModeTabModifiers.forEach((key, value) -> { + if (event.getTabKey().equals(key)) value.accept(modifier); + }); + } + + private @Nullable RegistrateDataProvider provider; + + /** + * Called when datagen begins to add our provider to the generator. Can be overriden in custom implementations. + * + * @param event + * The event + */ + protected void onData(GatherDataEvent event) { + event.getGenerator().addProvider(true, provider = new RegistrateDataProvider(this, modid, event)); + } + + /** + * Get the current name (from the last call to {@link #object(String)}), throwing an exception if it is not set. + * + * @return The current entry name + * @throws NullPointerException + * if {@link #currentName} is null + */ + protected String currentName() { + String name = currentName; + Objects.requireNonNull(name, "Current name not set"); + return name; + } + + /** + * Allows retrieval of a previously created entry, of the current name (from the last invocation of + * {@link #object(String)}. Useful to retrieve a different entry than the final state of your + * chain may produce, e.g. + * + *

+     * {@code
+     *
+     * public static final RegistryObject MY_BLOCK_ITEM = REGISTRATE.object("my_block")
+     *         .block(MyBlock::new)
+     *         .defaultItem()
+     *         .lang("My Special Block")
+     *         .build()
+     *         .get(Item.class);
+     * }
+     * 
+ * + * @param + * The type of the registry for which to retrieve the entry + * @param + * The type of the entry to return + * @param type + * A {@link ResourceKey} for the registry + * @return A {@link RegistryEntry} which will supply the requested entry, if it exists + * @throws IllegalArgumentException + * if no such registration has been done + * @throws NullPointerException + * if current name has not been set via {@link #object(String)} + */ + public RegistryEntry get(ResourceKey> type) { + return this.get(currentName(), type); + } + + /** + * Allows retrieval of a previously created entry. Useful to retrieve arbitrary entries that may have been created + * as side-effects of earlier registrations. + * + *
+     * {@code
+     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
+     *         .block(MyBlock::new)
+     *             .defaultItem()
+     *             .register();
+     *
+     * ...
+     *
+     * public static final RegistryObject MY_BLOCK_ITEM = REGISTRATE.get("my_block", ForgeRegistries.ITEMS.getRegistryKey());
+     * }
+     * 
+ * + * @param + * The type of the registry for which to retrieve the entry + * @param + * The type of the entry to return + * @param name + * The name of the registry entry to request + * @param type + * A {@link ResourceKey} for the registry + * @return A {@link RegistryEntry} which will supply the requested entry, if it exists + * @throws IllegalArgumentException + * if no such registration has been done + */ + public RegistryEntry get(String name, ResourceKey> type) { + return registrationTracker.get(name, type); + } + + /** + * Allows retrieval of a previously created entry that may or may not exist. Possibly useful in some very specific + * scenarios, internally used during fluid registration. + * + * @param + * The type of the registry for which to retrieve the entry + * @param + * The type of the entry to return + * @param name + * The name of the registry entry to request + * @param type + * A class representing the registry type + * @return A {@link RegistryEntry} which will supply the requested entry, if it exists + */ + public Optional> getOptional(String name, ResourceKey> type) { + return registrationTracker.getOptional(name, type); + } + + /** + * Gather a collection of all entries registered for a certain registry + *

+ * Note that this can be called before registration is complete, but the {@link RegistryEntry entries} will be empty + * at that time. + * + * @param + * Registry type + * @param type + * A {@link ResourceKey} for the registry in question + * @return A collection of {@link RegistryEntry} objects representing all entries in the given registry which are + * known to this {@link AbstractRegistrate} object. + */ + @SuppressWarnings({ "null", "unchecked" }) + public Collection> getAll(ResourceKey> type) { + return registrationTracker.getAll(type); + } + + /** + * Add a callback to be invoked when a certain entry has been registered. This will be invoked immediately + * following registration, before further entries are registered. + * + * @param + * Registry type + * @param + * Entry type + * @param name + * The name of the entry to watch (implicitly within the {@link #getModid() modid} of this + * instance + * @param registryType + * A {@link ResourceKey} for the registry in question + * @param callback + * The callback to invoke, which will be passed the created entry object + * @return This {@link AbstractRegistrate} instance + */ + public S addRegisterCallback(String name, ResourceKey> registryType, NonNullConsumer callback) { + registrationTracker.addRegisterCallback(name, registryType, callback); + return self(); + } + + /** + * Add a callback to be invoked when a certain registry has fully completed registration, i.e. all objects of that + * type have been registered. + * + * @param + * The registry type + * @param registryType + * A {@link ResourceKey} for the registry in question + * @param callback + * The callback to invoke + * @return This {@link AbstractRegistrate} instance + */ + public S addRegisterCallback(ResourceKey> registryType, Runnable callback) { + registrationTracker.addAfterRegisterCallback(registryType, callback); + return self(); + } + + /** + * Check if a certain registry has completed registration. + * + * @param + * The registry type + * @param registryType + * A {@link ResourceKey} for the registry in question + * @return {@code true} iff the given registry has finished the registration step + */ + public boolean isRegistered(ResourceKey> registryType) { + return registrationTracker.isRegistered(registryType); + } + + /** + * Get the data provider instance for a given {@link GeneratorType}. Only works within datagen context, not during + * registration or init. + * + * @param

+ * The type of the provider + * @param type + * A {@link GeneratorType} representing the desired provider + * @return An {@link Optional} holding the provider, or empty if this provider was not registered. This can happen + * if datagen is run only for client or server providers. + * @throws IllegalStateException + * if datagen has not started yet + */ + public

Optional

getDataProvider(GeneratorType

type) { + RegistrateDataProvider provider = this.provider; + if (provider != null) { + return provider.getSubProvider(type); + } + throw new IllegalStateException("Cannot get data provider before datagen is started"); + } + + /** + * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data + * gen callback if it exists. + * + * @param

+ * The type of provider + * @param + * The registry type + * @param builder + * The builder for the entry + * @param type + * The {@link GeneratorType} to generate data for + * @param cons + * A callback to be invoked during data generation + * @return this {@link AbstractRegistrate} + */ + public S setDataGenerator(Builder builder, GeneratorType type, NonNullConsumer cons) { + return this.setDataGenerator(builder.getName(), builder.getRegistryKey(), type, cons); + } + + /** + * Mostly internal, removes the data generator for a certain entry/type combination if one was previously + * registered. + * + * @param

+ * The type of provider + * @param + * The registry type + * @param builder + * The builder for the entry + * @param type + * The {@link GeneratorType} to stop generating data for + * @return this {@link AbstractRegistrate} + */ + public S removeDataGenerator(Builder builder, GeneratorType type) { + return this.removeDataGenerator(builder.getName(), builder.getRegistryKey(), type); + } + + /** + * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data + * gen callback if it exists. + * + * @param

+ * The type of provider + * @param + * The registry type + * @param entry + * The name of the entry which the provider is for + * @param registryType + * A {@link Class} representing the registry type of the entry + * @param type + * The {@link GeneratorType} to generate data for + * @param cons + * A callback to be invoked during data generation + * @return this {@link AbstractRegistrate} + */ + public S setDataGenerator(String entry, ResourceKey> registryType, GeneratorType type, NonNullConsumer cons) { + if (!doDatagen.get()) return self(); + @SuppressWarnings("null") + Consumer existing = datagensByEntry.put(Pair.of(entry, registryType), type, cons); + if (existing != null) { + datagens.remove(type, existing); + } + return addDataGenerator(type, cons); + } + + /** + * Mostly internal, removes the data generator for a certain entry/type combination if one was previously + * registered. + * + * @param

+ * The type of provider + * @param + * The registry type + * @param entry + * The name of the entry which the provider is for + * @param registryType + * The registry type of the entry + * @param type + * The {@link GeneratorType} to stop generating data for + * @return this {@link AbstractRegistrate} + */ + public S removeDataGenerator(String entry, ResourceKey> registryType, GeneratorType type) { + if (!doDatagen.get()) return self(); + @SuppressWarnings("null") + Consumer existing = datagensByEntry.remove(Pair.of(entry, registryType), type); + if (existing != null) { + datagens.remove(type, existing); + } + return self(); + } + + /** + * Add a data generator callback that is not associated with any entry, which can never replace an existing data + * generator. + *

+ * This is useful to add data generator callbacks for miscellaneous data not strictly associated with an entry. + * + * @param + * The type of provider + * @param type + * The {@link GeneratorType} to generate data for + * @param cons + * A callback to be invoked during data generation + * @return this {@link AbstractRegistrate} + */ + public S addDataGenerator(GeneratorType type, NonNullConsumer cons) { + if (doDatagen.get()) { + if (provider != null) throw new IllegalStateException("Cannot add data generator after construction of root generator"); + datagens.put(type, cons); + } + return self(); + } + + private @Nullable DataProviderInitializer initializer; + + /** + * Access datapack registry and data provider dependency settings + */ + public DataProviderInitializer getDataGenInitializer() { + if (initializer == null) { + initializer = new DataProviderInitializer(); + } + return initializer; + } + + private final NonNullSupplier>> extraLang = NonNullSupplier.lazy(() -> { + final List> ret = new ArrayList<>(); + addDataGenerator(ProviderType.LANG, prov -> ret.forEach(p -> prov.add(p.getKey(), p.getValue()))); + return ret; + }); + + /** + * Add a custom translation mapping using the vanilla style of Identifier -> translation key conversion. + * + * @param type + * Type of the object, this is used as a prefix (e.g. + * {@code ["block", "mymod:myblock"] -> "block.mymod.myblock"}) + * @param id + * ID of the object, which will be converted to a lang key via + * {@link Util#makeDescriptionId(String, Identifier)} + * @param localizedName + * (English) translation value + * @return A {@link MutableComponent} representing the translated text + */ + public MutableComponent addLang(String type, Identifier id, String localizedName) { + return addRawLang(Util.makeDescriptionId(type, id), localizedName); + } + + /** + * Add a custom translation mapping using the vanilla style of Identifier -> translation key conversion. Also + * appends a suffix to the key. + * + * @param type + * Type of the object, this is used as a prefix (e.g. + * {@code ["block", "mymod:myblock"] -> "block.mymod.myblock"}) + * @param id + * ID of the object, which will be converted to a lang key via + * {@link Util#makeDescriptionId(String, Identifier)} + * @param suffix + * A suffix which will be appended to the generated key (separated by a dot) + * @param localizedName + * (English) translation value + * @return A {@link MutableComponent} representing the translated text + */ + public MutableComponent addLang(String type, Identifier id, String suffix, String localizedName) { + return addRawLang(Util.makeDescriptionId(type, id) + "." + suffix, localizedName); + } + + /** + * Add a custom translation mapping directly to the lang provider. + * + * @param key + * The translation key + * @param value + * The (English) translation value + * @return A {@link MutableComponent} representing the translated text + */ + public MutableComponent addRawLang(String key, String value) { + if (doDatagen.get()) { + extraLang.get().add(Pair.of(key, value)); + } + return Component.translatable(key); + } + + @SuppressWarnings("null") + private Optional>>> getEntryForGenerator(GeneratorType type, NonNullConsumer generator) { + for (Map.Entry>>, Consumer> e : datagensByEntry.column(type).entrySet()) { + if (e.getValue() == generator) { + return Optional.of(e.getKey()); + } + } + return Optional.empty(); + } + + /** + * For internal use, calls upon registered data generators to actually create their data. + * + * @param + * The type of the provider + * @param type + * The type of provider to run + * @param gen + * The provider + */ + @SuppressWarnings("unchecked") + public void genData(GeneratorType type, T gen) { + if (!doDatagen.get()) return; + if (provider != null) { + provider.putSubProvider(type, gen); + } + datagens.get(type).forEach(cons -> { + Optional>>> entry = Optional.empty(); + if (DATAGEN_LOGGER.isEnabled(Level.DEBUG, DebugMarkers.DATA)) { + entry = getEntryForGenerator(type, cons); + if (entry.isPresent()) { + DATAGEN_LOGGER.debug( + DebugMarkers.DATA, + RegistrateLogger.modMessage("Generating data of type {} for entry {} [{}]"), + modid, + RegistrateDataProvider.getTypeName(type), + entry.get().getLeft(), + entry.get().getRight().identifier()); + } else { + DATAGEN_LOGGER.debug( + DebugMarkers.DATA, + RegistrateLogger.modMessage("Generating unassociated data of type {} ({})"), + modid, + RegistrateDataProvider.getTypeName(type), + type); + } + } + try { + ((Consumer) cons).accept(gen); + } catch (Exception e) { + if (entry.isEmpty()) { + entry = getEntryForGenerator(type, cons); + } + Message err; + if (entry.isPresent()) { + err = DATAGEN_LOGGER.getMessageFactory().newMessage( + RegistrateLogger.modMessage("Unexpected error while running data generator of type {} for entry {} [{}]"), + modid, + RegistrateDataProvider.getTypeName(type), + entry.get().getLeft(), + entry.get().getRight().identifier()); + } else { + err = DATAGEN_LOGGER.getMessageFactory().newMessage( + RegistrateLogger.modMessage("Unexpected error while running unassociated data generator of type {} ({})"), + modid, + RegistrateDataProvider.getTypeName(type), + type); + } + if (skipErrors) { + DATAGEN_LOGGER.error(err); + } else { + throw new RuntimeException(err.getFormattedMessage(), e); + } + } + }); + } + + /** + * Enable skipping of registry entries and data generators that error during registration/generation. + *

+ * Should only be used for debugging! {@code skipErrors(true)} will do nothing outside of a dev + * environment. + * + * @param skipErrors + * {@code true} to skip errors during registration/generation + * @return this {@link AbstractRegistrate} + */ + public S skipErrors(boolean skipErrors) { + if (skipErrors && !isDevEnvironment()) { + LOGGER.warn( + RegistrateLogger.modMessage("Ignoring skipErrors(true) because the runtime is not a development environment"), + modid); + } else { + this.skipErrors = skipErrors; + } + return self(); + } + + /** + * Begin a new object, this is typically used at the beginning of a builder chain. The given name will be used until + * this method is called again. This makes it simple to create multiple entries + * with the same name, as is often the case with blocks/items, items/entities, and blocks/TEs. + * + * @param name + * The name to use for future entries + * @return this {@link AbstractRegistrate} + */ + public S object(String name) { + this.currentName = name; + return self(); + } + + /** + * Set the default CreativeModeTab to be passed onto future builders. + *

+ * This special case method should be used if your creative tab instance was not created by Registrate, otherwise + * use {@link #defaultCreativeTab()}. + * + * @param creativeModeTab + * The new default CreativeModeTab type + * @return This {@link AbstractRegistrate} instance + */ + public S defaultCreativeTab(ResourceKey creativeModeTab) { + defaultCreativeModeTab = creativeModeTab; + return self(); + } + + /** + * Registers a new modifier callback to be used to modify the given CreativeModeTab. + * + *

+ * Registers a new callback to be invoked during the {@link BuildCreativeModeTabContentsEvent} event and + * used to modify what items are displayed on the given {@link CreativeModeTab}. + *

+ * Calling this method multiple times will add additional callbacks. + * + * @param creativeModeTab The {@link CreativeModeTab} to register this callback for + * @param modifier The modifier callback to be registered + * @return This {@link AbstractRegistrate} instance + */ + public S modifyCreativeModeTab(ResourceKey creativeModeTab, Consumer modifier) { + creativeModeTabModifiers.put(creativeModeTab, modifier); + return self(); + } + + /** + * Apply a transformation to this {@link AbstractRegistrate}. Useful to apply helper methods within a fluent chain, + * e.g. + * + *

+     * {@code
+     *
+     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
+     *         .transform(Utils::createMyBlock)
+     *         .get(Block.class);
+     * }
+     * 
+ * + * @param func + * The {@link UnaryOperator function} to apply + * @return this {@link AbstractRegistrate} + */ + public S transform(NonNullUnaryOperator func) { + return func.apply(self()); + } + + /** + * Apply a transformation to this {@link AbstractRegistrate}. Similar to {@link #transform(NonNullUnaryOperator)}, + * but for actions that return a builder in-progress. Useful to apply helper methods + * within a fluent chain, e.g. + * + *
+     * {@code
+     *
+     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
+     *         .transform(Utils::createMyBlock)
+     *         .lang("My Block") // Can modify the builder afterwards
+     *         .register();
+     * }
+     * 
+ * + * @param + * Registry type + * @param + * Entry type + * @param

+ * Parent type + * @param + * Self type + * @param func + * The {@link Function function} to apply + * @return the resultant {@link Builder} + */ + public > S2 transform(NonNullFunction func) { + return func.apply(self()); + } + + /** + * Create a builder for a new entry. This is typically not needed, unless you are implementing a + * custom builder type. + *

+ * Uses the currently set name (via {@link #object(String)}) as the name for the new entry, and passes it to the + * factory as the first parameter. + * + * @param + * Registry type + * @param + * Entry type + * @param

+ * Parent type + * @param + * Self type + * @param factory + * The factory to create the builder + * @return The {@link Builder} instance + */ + public > S2 entry(NonNullBiFunction factory) { + return entry(currentName(), callback -> factory.apply(currentName(), callback)); + } + + /** + * Create a builder for a new entry. This is typically not needed, unless you are implementing a + * custom builder type. + * + * @param + * Registry type + * @param + * Entry type + * @param

+ * Parent type + * @param + * Self type + * @param name + * The name to use for the entry + * @param factory + * The factory to create the builder + * @return The {@link Builder} instance + */ + public > S2 entry(String name, NonNullFunction factory) { + return factory.apply(this::accept); + } + + /** + * Factory method to accept a completed builder and add it to the registration queue. + *

+ * Satisfies the functional interface {@link BuilderCallback}, which is typically given to new builder instances + * when they are constructed. + * + * @param + * Registry type + * @param + * Entry type + * @param name + * Thename of the entry being created + * @param type + * The registry to add the entry to + * @param builder + * The builder instance that was used to create this entry. Not used by default implementation, + * but custom extensions may use it for some purpose + * @param creator + * Constructor for the new entry object + * @param entryFactory + * Optional custom factory to create special {@link RegistryEntry} types + * @return A {@link RegistryEntry} that will hold the created entry after registration is complete + */ + protected RegistryEntry accept(String name, ResourceKey> type, Builder builder, NonNullSupplier creator, NonNullFunction, ? extends RegistryEntry> entryFactory) { + return registrationTracker.track(name, type, creator, entryFactory); + } + + /** + * Helper to create a new registry for custom objects. The returned {@link ResourceKey} can be used immediately in + * methods like {@link #simple(ResourceKey, NonNullSupplier) simple} or + * {@link #generic(ResourceKey, NonNullSupplier) generic}. + *

+ * Alternatively, a custom {@link Builder builder} can be created. + *

+ * This method will automatically subscribe to the {@link NewRegistryEvent} and create the registry at the proper + * time. Thus, the new registry will not exist immediately after this is called. + * + * @param + * The type of object the new registry will contain + * @param name + * The ID of this registry + * @param builder + * A function to create the {@link RegistryBuilder} that defines the other properties/behaviors of + * the created registry + * @return A {@link ResourceKey resource key} referencing the to-be-created registry. + */ + public ResourceKey> makeRegistry(String name, Function>, RegistryBuilder> builder) { + final ResourceKey> registryId = ResourceKey.createRegistryKey(Identifier.fromNamespaceAndPath(getModid(), name)); + OneTimeEventReceiver.addModListener(this, NewRegistryEvent.class, e -> e.register(builder.apply(registryId).create())); + return registryId; + } + + /** + * Registers the given registry key as an unsynced datapack registry, which will cause data to be loaded from + * a datapack folder based on the registry's name. The datapack registry is not required to be present + * on clients when connecting to servers with the mod/registry. + *

+ * Data JSONs will be loaded from {@code data//modid/registryname/}, where {@code modid} is the + * namespace of the registry key. + * + * @param name The ID of this registry + * @param codec The codec to be used for loading data from datapacks on servers + * @see #makeDatapackRegistry(String, Codec, Codec) + */ + public ResourceKey> makeDatapackRegistry(String name, Codec codec) { + return makeDatapackRegistry(name, codec, null); + } + + /** + * Registers the registry key as a datapack registry, which will cause data to be loaded from + * a datapack folder based on the registry's name. + *

+ * Data JSONs will be loaded from {@code data//modid/registryname/}, where {@code modid} is the + * namespace of the registry key. + * + * @param name The ID of this registry + * @param codec The codec to be used for loading data from datapacks on servers + * @param networkCodec The codec to be used for syncing loaded data to clients. + * If {@code networkCodec} is null, data will not be synced, and clients are not required to + * have this + * datapack registry to join a server. + *

+ * If {@code networkCodec} is not null, clients must have this datapack registry/mod + * when joining a server that has this datapack registry/mod. + * The data will be synced using the network codec and accessible via + * {@link ClientPacketListener#registryAccess()}. + * @see #makeDatapackRegistry(String, Codec) + */ + public ResourceKey> makeDatapackRegistry(String name, Codec codec, @Nullable Codec networkCodec) { + final ResourceKey> registryId = ResourceKey.createRegistryKey(Identifier.fromNamespaceAndPath(getModid(), name)); + OneTimeEventReceiver.addModListener(this, DataPackRegistryEvent.NewRegistry.class, event -> event.dataPackRegistry(registryId, codec, networkCodec)); + return registryId; + } + + /* === Builder helpers === */ + + // Generic + + public RegistryEntry simple(ResourceKey> registryType, NonNullSupplier factory) { + return simple(currentName(), registryType, factory); + } + + public RegistryEntry simple(String name, ResourceKey> registryType, NonNullSupplier factory) { + return simple(this, name, registryType, factory); + } + + public RegistryEntry simple(P parent, ResourceKey> registryType, NonNullSupplier factory) { + return simple(parent, currentName(), registryType, factory); + } + + public RegistryEntry simple(P parent, String name, ResourceKey> registryType, NonNullSupplier factory) { + return generic(parent, name, registryType, factory).register(); + } + + public NoConfigBuilder generic(ResourceKey> registryType, NonNullSupplier factory) { + return generic(self(), registryType, factory); + } + + public NoConfigBuilder generic(String name, ResourceKey> registryType, NonNullSupplier factory) { + return generic(self(), name, registryType, factory); + } + + public NoConfigBuilder generic(P parent, ResourceKey> registryType, NonNullSupplier factory) { + return generic(parent, currentName(), registryType, factory); + } + + public NoConfigBuilder generic(P parent, String name, ResourceKey> registryType, NonNullSupplier factory) { + return entry(name, callback -> new NoConfigBuilder<>(this, parent, name, callback, registryType, factory)); + } + + // Items + + public ItemBuilder item(NonNullFunction factory) { + return item(self(), factory); + } + + public ItemBuilder item(String name, NonNullFunction factory) { + return item(self(), name, factory); + } + + public ItemBuilder item(P parent, NonNullFunction factory) { + return item(parent, currentName(), factory); + } + + public ItemBuilder item(P parent, String name, NonNullFunction factory) { + return entry(name, callback -> ItemBuilder.create(this, parent, name, callback, factory) + .transform(builder -> this.defaultCreativeModeTab == null ? builder : builder.tab(this.defaultCreativeModeTab))); + } + + // Blocks + + public BlockBuilder block(NonNullFunction factory) { + return block(self(), factory); + } + + public BlockBuilder block(String name, NonNullFunction factory) { + return block(self(), name, factory); + } + + public BlockBuilder block(P parent, NonNullFunction factory) { + return block(parent, currentName(), factory); + } + + public BlockBuilder block(P parent, String name, NonNullFunction factory) { + return entry(name, callback -> BlockBuilder.create(this, parent, name, callback, factory)); + } + + // Entities + + public EntityBuilder entity(EntityFactory factory, MobCategory classification) { + return entity(self(), factory, classification); + } + + public EntityBuilder entity(String name, EntityFactory factory, MobCategory classification) { + return entity(self(), name, factory, classification); + } + + public EntityBuilder entity(P parent, EntityFactory factory, MobCategory classification) { + return entity(parent, currentName(), factory, classification); + } + + public EntityBuilder entity(P parent, String name, EntityFactory factory, MobCategory classification) { + return entry(name, callback -> EntityBuilder.create(this, parent, name, callback, factory, classification)); + } + + // Block Entities + + public BlockEntityBuilder blockEntity(BlockEntityFactory factory) { + return blockEntity(self(), factory); + } + + public BlockEntityBuilder blockEntity(String name, BlockEntityFactory factory) { + return blockEntity(self(), name, factory); + } + + public BlockEntityBuilder blockEntity(P parent, BlockEntityFactory factory) { + return blockEntity(parent, currentName(), factory); + } + + public BlockEntityBuilder blockEntity(P parent, String name, BlockEntityFactory factory) { + return entry(name, callback -> BlockEntityBuilder.create(this, parent, name, callback, factory)); + } + + // Fluids + + public FluidBuilder fluid() { + return fluid(self()); + } + + public FluidBuilder fluid(FluidBuilder.FluidTypeFactory typeFactory) { + return fluid(self(), typeFactory); + } + + public FluidBuilder fluid(NonNullSupplier fluidType) { + return fluid(self(), fluidType); + } + + public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture) { + return fluid(self(), stillTexture, flowingTexture); + } + + public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + return fluid(self(), stillTexture, flowingTexture, typeFactory); + } + + public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + return fluid(self(), stillTexture, flowingTexture, fluidType); + } + + public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidFactory fluidFactory) { + return fluid(self(), stillTexture, flowingTexture, fluidFactory); + } + + public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { + return fluid(self(), stillTexture, flowingTexture, typeFactory, fluidFactory); + } + + public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, + NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { + return fluid(self(), stillTexture, flowingTexture, fluidType, fluidFactory); + } + + public FluidBuilder fluid(String name) { + return fluid(self(), name); + } + + public FluidBuilder fluid(String name, FluidBuilder.FluidTypeFactory typeFactory) { + return fluid(self(), name, typeFactory); + } + + public FluidBuilder fluid(String name, NonNullSupplier fluidType) { + return fluid(self(), name, fluidType); + } + + public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture) { + return fluid(self(), name, stillTexture, flowingTexture); + } + + public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + return fluid(self(), name, stillTexture, flowingTexture, typeFactory); + } + + public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + return fluid(self(), name, stillTexture, flowingTexture, fluidType); + } + + public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidFactory fluidFactory) { + return fluid(self(), name, stillTexture, flowingTexture, fluidFactory); + } + + public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { + return fluid(self(), name, stillTexture, flowingTexture, typeFactory, fluidFactory); + } + + public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, + NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { + return fluid(self(), name, stillTexture, flowingTexture, fluidType, fluidFactory); + } + + public

FluidBuilder fluid(P parent) { + return fluid(parent, currentName()); + } + + public

FluidBuilder fluid(P parent, FluidBuilder.FluidTypeFactory typeFactory) { + return fluid(parent, currentName(), typeFactory); + } + + public

FluidBuilder fluid(P parent, NonNullSupplier fluidType) { + return fluid(parent, currentName(), fluidType); + } + + public

FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture) { + return fluid(parent, currentName(), stillTexture, flowingTexture); + } + + public

FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + return fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory); + } + + public

FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + return fluid(parent, currentName(), stillTexture, flowingTexture, fluidType); + } + + public FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidFactory fluidFactory) { + return fluid(parent, currentName(), stillTexture, flowingTexture, fluidFactory); + } + + public FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { + return fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory, fluidFactory); + } + + public FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, + NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { + return fluid(parent, currentName(), stillTexture, flowingTexture, fluidType, fluidFactory); + } + + public

FluidBuilder fluid(P parent, String name) { + return fluid(parent, name, defaultStillTexture(), defaultFlowingTexture()); + } + + public

FluidBuilder fluid(P parent, String name, FluidBuilder.FluidTypeFactory typeFactory) { + return fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), typeFactory); + } + + public

FluidBuilder fluid(P parent, String name, NonNullSupplier fluidType) { + return fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), fluidType); + } + + private Identifier defaultStillTexture() { + return Identifier.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_still"); + } + + private Identifier defaultFlowingTexture() { + return Identifier.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_flow"); + } + + public

FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture) { + return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, FluidType::new)).model(stillTexture, flowingTexture); + } + + public

FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, typeFactory)).model(stillTexture, flowingTexture); + } + + public

FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidType)).model(stillTexture, flowingTexture); + } + + public FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidFactory fluidFactory) { + return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidFactory)).model(stillTexture, flowingTexture); + } + + public FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, + FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { + return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, typeFactory, fluidFactory)).model(stillTexture, flowingTexture); + } + + public FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, + NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { + return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidType, fluidFactory)).model(stillTexture, flowingTexture); + } + + // Menu + + public > MenuBuilder menu(MenuFactory factory, NonNullSupplier> screenFactory) { + return menu(currentName(), factory, screenFactory); + } + + public > MenuBuilder menu(String name, MenuFactory factory, NonNullSupplier> screenFactory) { + return menu(self(), name, factory, screenFactory); + } + + public , P> MenuBuilder menu(P parent, MenuFactory factory, NonNullSupplier> screenFactory) { + return menu(parent, currentName(), factory, screenFactory); + } + + public , P> MenuBuilder menu(P parent, String name, MenuFactory factory, NonNullSupplier> screenFactory) { + return entry(name, callback -> new MenuBuilder<>(this, parent, name, callback, factory, screenFactory)); + } + + public > MenuBuilder menu(ForgeMenuFactory factory, NonNullSupplier> screenFactory) { + return menu(currentName(), factory, screenFactory); + } + + public > MenuBuilder menu(String name, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { + return menu(self(), name, factory, screenFactory); + } + + public , P> MenuBuilder menu(P parent, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { + return menu(parent, currentName(), factory, screenFactory); + } + + public , P> MenuBuilder menu(P parent, String name, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { + return entry(name, callback -> new MenuBuilder<>(this, parent, name, callback, factory, screenFactory)); + } + + // Creative Tab + + public NoConfigBuilder defaultCreativeTab() { + return defaultCreativeTab(self()); + } + + public NoConfigBuilder defaultCreativeTab(String name) { + return defaultCreativeTab(self(), name); + } + + public

NoConfigBuilder defaultCreativeTab(P parent) { + return defaultCreativeTab(parent, currentName()); + } + + public

NoConfigBuilder defaultCreativeTab(P parent, String name) { + return defaultCreativeTab(parent, name, tab -> {}); + } + + public NoConfigBuilder defaultCreativeTab(Consumer config) { + return defaultCreativeTab(self(), config); + } + + public NoConfigBuilder defaultCreativeTab(String name, Consumer config) { + return defaultCreativeTab(self(), name, config); + } + + public

NoConfigBuilder defaultCreativeTab(P parent, Consumer config) { + return defaultCreativeTab(parent, currentName(), config); + } + + public

NoConfigBuilder defaultCreativeTab(P parent, String name, Consumer config) { + this.defaultCreativeModeTab = ResourceKey.create(Registries.CREATIVE_MODE_TAB, Identifier.fromNamespaceAndPath(this.modid, name)); + return this.generic(parent, name, Registries.CREATIVE_MODE_TAB, () -> { + var builder = CreativeModeTab.builder() + .icon(() -> getAll(Registries.ITEM).stream().findFirst().map(ItemEntry::cast).map(ItemEntry::asStack).orElse(new ItemStack(Items.AIR))) + .title(this.addLang("itemGroup", this.defaultCreativeModeTab.identifier(), RegistrateLangProvider.toEnglishName(name))); + config.accept(builder); + return builder.build(); + }); + } +} diff --git a/src/main/java/com/modularmc/registrate/Registrate.java b/src/main/java/com/modularmc/registrate/Registrate.java new file mode 100644 index 0000000..9e8d07d --- /dev/null +++ b/src/main/java/com/modularmc/registrate/Registrate.java @@ -0,0 +1,43 @@ +package com.modularmc.registrate; + +import com.modularmc.registrate.internal.util.RegistrateLogger; + +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.ModList; + +import org.apache.logging.log4j.Logger; + +import java.util.Optional; + +public class Registrate extends AbstractRegistrate { + + private static final Logger LOGGER = RegistrateLogger.core(); + + /** + * Create a new {@link Registrate} and register event listeners for registration and data generation. Used in lieu + * of adding side-effects to constructor, so that alternate initialization + * strategies can be done in subclasses. + * + * @param modid + * The mod ID for which objects will be registered + * @return The {@link Registrate} instance + */ + public static Registrate create(String modid) { + var ret = new Registrate(modid); + + Optional modEventBus = ModList.get().getModContainerById(modid) + .map(ModContainer::getEventBus); + + modEventBus.ifPresentOrElse(ret::registerEventListeners, () -> LOGGER.fatal( + RegistrateLogger.modMessage( + "Failed to locate the mod event bus during Registrate.create; registration listeners were not attached"), + modid)); + + return ret; + } + + protected Registrate(String modid) { + super(modid); + } +} diff --git a/src/main/java/com/modularmc/registrate/RegistrateLib.java b/src/main/java/com/modularmc/registrate/RegistrateLib.java new file mode 100644 index 0000000..f992d5f --- /dev/null +++ b/src/main/java/com/modularmc/registrate/RegistrateLib.java @@ -0,0 +1,27 @@ +package com.modularmc.registrate; + +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.common.Mod; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * Runtime entrypoint for the ModularMCLib variant of Registrate. + * + *

+ * This library is intended to load as its own NeoForge mod so downstream + * mods can depend on it as a prerequisite during development. Integration + * scenarios, sample registrations, and visual validation belong in the test + * harness under {@code src/test}. + */ +@Mod(RegistrateLib.MOD_ID) +public final class RegistrateLib { + + public static final String MOD_ID = "registratelib"; + public static final String MOD_NAME = "Registrate Lib"; + + public static final Logger LOGGER = LogManager.getLogger(MOD_NAME); + + public RegistrateLib(IEventBus modEventBus) {} +} diff --git a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java new file mode 100644 index 0000000..e325beb --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java @@ -0,0 +1,392 @@ +package com.modularmc.registrate.builders; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.builders.BlockEntityBuilder.BlockEntityFactory; +import com.modularmc.registrate.builders.base.AbstractBuilder; +import com.modularmc.registrate.builders.base.BuilderCallback; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; +import com.modularmc.registrate.internal.util.RegistrateDistExecutor; +import com.modularmc.registrate.providers.DataGenContext; +import com.modularmc.registrate.providers.RegistrateLangProvider; +import com.modularmc.registrate.providers.core.GeneratorType; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.generators.RegistrateBlockModelGenerator; +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; +import com.modularmc.registrate.providers.loot.RegistrateBlockLootTables; +import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider.LootType; +import com.modularmc.registrate.util.entry.BlockEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullBiConsumer; +import com.modularmc.registrate.util.nullness.NonNullBiFunction; +import com.modularmc.registrate.util.nullness.NonNullFunction; +import com.modularmc.registrate.util.nullness.NonNullSupplier; +import com.modularmc.registrate.util.nullness.NonNullUnaryOperator; + +import net.minecraft.client.color.block.BlockTintSource; +import net.minecraft.client.renderer.block.dispatch.SingleVariant; +import net.minecraft.client.renderer.block.dispatch.Variant; +import net.minecraft.core.registries.Registries; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent; +import net.neoforged.neoforge.client.extensions.common.IClientBlockExtensions; +import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; +import net.neoforged.neoforge.registries.DeferredHolder; + +import org.jspecify.annotations.Nullable; + +import java.util.List; +import java.util.function.Supplier; + +import javax.annotation.Nonnull; + +/** + * A builder for blocks, allows for customization of the {@link Block.Properties}, creation of block items, and + * configuration of data associated with blocks (loot tables, recipes, etc.). + * + * @param + * The type of block being built + * @param

+ * Parent object type + */ +public class BlockBuilder extends AbstractBuilder> { + + /** + * Create a new {@link BlockBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + *

+ * The block will be assigned the following data: + *

    + *
  • A default blockstate file mapping all states to one model (via {@link #defaultBlockstate()})
  • + *
  • A simple cube_all model (used in the blockstate) with one texture (via {@link #defaultBlockstate()})
  • + *
  • A self-dropping loot table (via {@link #defaultLoot()})
  • + *
  • The default translation (via {@link #defaultLang()})
  • + *
+ * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the block + * @return A new {@link BlockBuilder} with reasonable default data generators. + */ + public static BlockBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory) { + return new BlockBuilder<>(owner, parent, name, callback, factory, () -> BlockBehaviour.Properties.of()) + .defaultBlockstate().defaultLoot().defaultLang(); + } + + private final NonNullFunction factory; + + private NonNullSupplier initialProperties; + private NonNullFunction propertiesCallback = NonNullUnaryOperator.identity(); + + private @Nullable NonNullSupplier>> tintSources; + + protected BlockBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory, NonNullSupplier initialProperties) { + super(owner, parent, name, callback, Registries.BLOCK); + this.factory = factory; + this.initialProperties = initialProperties; + } + + /** + * Modify the properties of the block. Modifications are done lazily, but the passed function is composed with the + * current one, and as such this method can be called multiple times to perform + * different operations. + *

+ * If a different properties instance is returned, it will replace the existing one entirely. + * + * @param func + * The action to perform on the properties + * @return this {@link BlockBuilder} + */ + public BlockBuilder properties(NonNullUnaryOperator func) { + propertiesCallback = propertiesCallback.andThen(func); + return this; + } + + /** + * Replace the initial state of the block properties, without replacing or removing any modifications done via + * {@link #properties(NonNullUnaryOperator)}. + * + * @param block + * The block to create the initial properties from (via + * {@link Block.Properties#ofFullCopy(BlockBehaviour)}) + * @return this {@link BlockBuilder} + */ + public BlockBuilder initialProperties(NonNullSupplier block) { + initialProperties = () -> BlockBehaviour.Properties.ofFullCopy(block.get()); + return this; + } + + /** + * Create a standard {@link BlockItem} for this block, building it immediately, and not allowing for further + * configuration. + *

+ * The item will have no lang entry (since it would duplicate the block's) + * + * @return this {@link BlockBuilder} + * @see #item() + */ + public BlockBuilder simpleItem() { + return item().build(); + } + + /** + * Create a standard {@link BlockItem} for this block, and return the builder for it so that further customization + * can be done. + *

+ * The item will have no lang entry (since it would duplicate the block's) + * + * @return the {@link ItemBuilder} for the {@link BlockItem} + */ + public ItemBuilder> item() { + return item(BlockItem::new); + } + + /** + * Create a {@link BlockItem} for this block, which is created by the given factory, and return the builder for it + * so that further customization can be done. + *

+ * By default, the item will have no lang entry (since it would duplicate the block's) and a simple block item + * model. + * + * @param + * The type of the item + * @param factory + * A factory for the item, which accepts the block object and properties and returns a new item + * @return the {@link ItemBuilder} for the {@link BlockItem} + */ + public ItemBuilder> item(NonNullBiFunction factory) { + return getOwner().>item(this, getName(), p -> factory.apply(getEntry(), p.useBlockDescriptionPrefix())) + .removeData(ProviderType.LANG) + .model(() -> (ctx, prov) -> { + getOwner().getDataProvider(ProviderType.BLOCKSTATE) + .map(g -> g.seenBlockstates.get(getEntry())) + .flatMap(b -> b.simpleModels()) + .map(b -> b.models().get("")) + .map(unbaked -> { + if (unbaked instanceof SingleVariant.Unbaked(Variant variant)) { + return variant.modelLocation(); + } + return null; + }) + .ifPresent(model -> prov.createWithExistingModel(ctx.get(), model)); + }); + } + + /** + * Create a {@link BlockEntity} for this block, which is created by the given factory, and assigned this block as + * its one and only valid block. + * + * @param + * The type of the block entity + * @param factory + * A factory for the block entity + * @return this {@link BlockBuilder} + */ + public BlockBuilder simpleBlockEntity(BlockEntityFactory factory) { + return blockEntity(factory).build(); + } + + /** + * Create a {@link BlockEntity} for this block, which is created by the given factory, and assigned this block as + * its one and only valid block. + *

+ * The created {@link BlockEntityBuilder} is returned for further configuration. + * + * @param + * The type of the block entity + * @param factory + * A factory for the block entity + * @return the {@link BlockEntityBuilder} + */ + public BlockEntityBuilder> blockEntity(BlockEntityFactory factory) { + return getOwner().>blockEntity(this, getName(), factory).validBlock(asSupplier()); + } + + /** + * Register a set of block tint sources for this block. The {@link BlockTintSource} instances can be shared across + * many blocks. + * + * @param tintSources The tint sources to register for this block, indexed by tint index + * @return this {@link BlockBuilder} + */ + public BlockBuilder color(NonNullSupplier>> tintSources) { + if (this.tintSources == null) { + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerBlockColor); + } + this.tintSources = tintSources; + return this; + } + + protected void registerBlockColor() { + OneTimeEventReceiver.addModListener(getOwner(), RegisterColorHandlersEvent.BlockTintSources.class, e -> { + NonNullSupplier>> tintSources = this.tintSources; + if (tintSources != null) { + e.register(tintSources.get().get(), getEntry()); + } + }); + } + + /** + * Assign the default blockstate, which maps all states to a single model file (via + * {@link RegistrateBlockModelGenerator#createTrivialCube(Block)}). This is the default, so it is generally not + * necessary + * to call, unless for undoing previous changes. + * + * @return this {@link BlockBuilder} + */ + public BlockBuilder defaultBlockstate() { + return blockstate(() -> (ctx, prov) -> prov.createTrivialCube(ctx.getEntry())); + } + + /** + * Configure the blockstate/models for this block. + * + * @param cons + * The callback which will be invoked during data generation. + * @return this {@link BlockBuilder} + * @see #setData(GeneratorType, NonNullBiConsumer) + */ + public BlockBuilder blockstate(NonNullSupplier, RegistrateBlockModelGenerator>> cons) { + if (!getOwner().doDatagen().get()) return this; + return setData(ProviderType.BLOCKSTATE, cons.get()); + } + + /** + * Assign the default translation, as specified by + * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, net.minecraft.resources.ResourceKey)}. This is + * the default, so it is generally + * not necessary to call, unless for undoing previous changes. + * + * @return this {@link BlockBuilder} + */ + public BlockBuilder defaultLang() { + return lang(Block::getDescriptionId); + } + + /** + * Set the translation for this block. + * + * @param name + * A localized English name + * @return this {@link BlockBuilder} + */ + public BlockBuilder lang(String name) { + return lang(Block::getDescriptionId, name); + } + + /** + * Assign the default loot table, as specified by {@link RegistrateBlockLootTables#dropSelf(Block)}. This is the + * default, so it is generally not necessary to call, unless for + * undoing previous changes. + * + * @return this {@link BlockBuilder} + */ + public BlockBuilder defaultLoot() { + return loot(RegistrateBlockLootTables::dropSelf); + } + + /** + * Configure the loot table for this block. This is different than most data gen callbacks as the callback does not + * accept a {@link DataGenContext}, but instead a + * {@link RegistrateBlockLootTables}, for creating specifically block loot tables. + *

+ * If the block does not have a loot table (i.e. {@link Block.Properties#noLootTable()} is called) this action will + * be skipped. + * + * @param cons + * The callback which will be invoked during block loot table creation. + * @return this {@link BlockBuilder} + */ + public BlockBuilder loot(NonNullBiConsumer cons) { + return setData(ProviderType.LOOT, (ctx, prov) -> prov.addLootAction(LootType.BLOCK, tb -> { + if (ctx.getEntry().getLootTable().isPresent()) { + cons.accept(tb, ctx.getEntry()); + } + })); + } + + /** + * Configure the recipe(s) for this block. + * + * @param cons + * The callback which will be invoked during data generation. + * @return this {@link BlockBuilder} + * @see #setData(GeneratorType, NonNullBiConsumer) + */ + public BlockBuilder recipe(NonNullBiConsumer, RegistrateRecipeProvider> cons) { + return setData(ProviderType.RECIPE, cons); + } + + private @Nullable NonNullSupplier> clientExtension; + + /** + * Register a client extension for this block. + * The {@link IClientBlockExtensions} instance can be shared across many items. + * + * @param clientExtension + * The client extension to register for this block + * @return this {@link BlockBuilder} + */ + public BlockBuilder clientExtension(NonNullSupplier> clientExtension) { + if (this.clientExtension == null) { + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); + } + this.clientExtension = clientExtension; + return this; + } + + protected void registerClientExtension() { + OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, e -> { + NonNullSupplier> clientExtension = this.clientExtension; + if (clientExtension != null) { + e.registerBlock(clientExtension.get().get(), getEntry()); + } + }); + } + + /** + * Assign {@link TagKey}{@code s} to this block. Multiple calls will add additional tags. + * + * @param tags + * The tags to assign + * @return this {@link BlockBuilder} + */ + @SafeVarargs + public final BlockBuilder tag(TagKey... tags) { + return tag(ProviderType.BLOCK_TAGS, tags); + } + + @Override + protected T createEntry() { + @Nonnull + BlockBehaviour.Properties properties = this.initialProperties.get(); + properties = propertiesCallback.apply(properties); + return factory.apply(properties.setId(getResourceKey())); + } + + @Override + protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { + return new BlockEntry<>(getOwner(), delegate); + } + + @Override + public BlockEntry register() { + return (BlockEntry) super.register(); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java new file mode 100644 index 0000000..11635d5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java @@ -0,0 +1,166 @@ +package com.modularmc.registrate.builders; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.builders.base.AbstractBuilder; +import com.modularmc.registrate.builders.base.BuilderCallback; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; +import com.modularmc.registrate.internal.util.RegistrateDistExecutor; +import com.modularmc.registrate.util.entry.BlockEntityEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullFunction; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.Registries; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; +import net.neoforged.neoforge.registries.DeferredHolder; + +import org.jspecify.annotations.Nullable; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * A builder for block entities, allows for customization of the valid blocks. + * + * @param + * The type of block entity being built + * @param

+ * Parent object type + */ +public class BlockEntityBuilder extends AbstractBuilder, BlockEntityType, P, BlockEntityBuilder> { + + public interface BlockEntityFactory { + + public T create(BlockEntityType type, BlockPos pos, BlockState state); + } + + /** + * Create a new {@link BlockEntityBuilder} and configure data. Used in lieu of adding side-effects to constructor, + * so that alternate initialization strategies can be done in subclasses. + *

+ * The block entity will be assigned the following data: + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the block entity + * @return A new {@link BlockEntityBuilder} with reasonable default data generators. + */ + public static BlockEntityBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, BlockEntityFactory factory) { + return new BlockEntityBuilder<>(owner, parent, name, callback, factory); + } + + private final BlockEntityFactory factory; + private final Set> validBlocks = new HashSet<>(); + private @Nullable NonNullSupplier>> renderer; + + protected BlockEntityBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, BlockEntityFactory factory) { + super(owner, parent, name, callback, Registries.BLOCK_ENTITY_TYPE); + this.factory = factory; + } + + /** + * Add a valid block for this block entity. + * + * @param block + * A supplier for the block to add at registration time + * @return this {@link BlockEntityBuilder} + */ + public BlockEntityBuilder validBlock(NonNullSupplier block) { + validBlocks.add(block); + return this; + } + + /** + * Add valid blocks for this block entity. + * + * @param blocks + * An array of suppliers for the block to add at registration time + * @return this {@link BlockEntityBuilder} + */ + @SafeVarargs + public final BlockEntityBuilder validBlocks(NonNullSupplier... blocks) { + Arrays.stream(blocks).forEach(this::validBlock); + return this; + } + + /** + * Register an {@link BlockEntityRenderer} for this block entity. + *

+ * + * @apiNote This requires the {@link Class} of the block entity object, which can only be gotten by inspecting an + * instance of it. Thus, the entity will be constructed to register the renderer. + * + * @param renderer + * A (server safe) supplier to an {@link Function} that will provide this block entity's renderer + * given the renderer dispatcher + * @return this {@link BlockEntityBuilder} + */ + public BlockEntityBuilder renderer(NonNullSupplier>> renderer) { + if (this.renderer == null) { // First call only + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerRenderer); + } + this.renderer = renderer; + return this; + } + + protected void registerRenderer() { + OneTimeEventReceiver.addModListener(getOwner(), FMLClientSetupEvent.class, $ -> { + var renderer = this.renderer; + if (renderer != null) { + BlockEntityRenderers.register(getEntry(), renderer.get()::apply); + } + }); + } + + /** + * Register {@link net.neoforged.neoforge.capabilities.Capabilities} for this block entity. + * + * @param registerCapabilitiesEvent A consumer for the register capabilities event + * @return this {@link BlockEntityBuilder} + */ + public BlockEntityBuilder registerCapability(Consumer registerCapabilitiesEvent) { + OneTimeEventReceiver.addModListener(getOwner(), RegisterCapabilitiesEvent.class, registerCapabilitiesEvent); + return this; + } + + @Override + protected BlockEntityType createEntry() { + BlockEntityFactory factory = this.factory; + final var supplier = asSupplier(); + return new BlockEntityType<>((pos, state) -> factory.create(supplier.get(), pos, state), validBlocks.stream().map(NonNullSupplier::get).toArray(Block[]::new)); + } + + @Override + protected RegistryEntry, BlockEntityType> createEntryWrapper(DeferredHolder, BlockEntityType> delegate) { + return new BlockEntityEntry<>(getOwner(), delegate); + } + + @Override + public BlockEntityEntry register() { + return (BlockEntityEntry) super.register(); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java new file mode 100644 index 0000000..86edccd --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java @@ -0,0 +1,294 @@ +package com.modularmc.registrate.builders; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.builders.base.AbstractBuilder; +import com.modularmc.registrate.builders.base.BuilderCallback; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; +import com.modularmc.registrate.internal.util.RegistrateDistExecutor; +import com.modularmc.registrate.providers.DataGenContext; +import com.modularmc.registrate.providers.RegistrateLangProvider; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.loot.RegistrateEntityLootTables; +import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider.LootType; +import com.modularmc.registrate.util.entry.EntityEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullBiConsumer; +import com.modularmc.registrate.util.nullness.NonNullConsumer; +import com.modularmc.registrate.util.nullness.NonNullFunction; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.client.renderer.entity.EntityRenderer; +import net.minecraft.client.renderer.entity.EntityRendererProvider; +import net.minecraft.core.registries.Registries; +import net.minecraft.tags.TagKey; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.SpawnPlacements.SpawnPredicate; +import net.minecraft.world.entity.ai.attributes.AttributeSupplier; +import net.minecraft.world.item.CreativeModeTabs; +import net.minecraft.world.item.SpawnEggItem; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.levelgen.Heightmap; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.client.event.EntityRenderersEvent; +import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent; +import net.neoforged.neoforge.event.entity.RegisterSpawnPlacementsEvent; +import net.neoforged.neoforge.registries.DeferredHolder; + +import org.jspecify.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * A builder for entities, allows for customization of the {@link EntityType.Builder}, easy creation of spawn egg items, + * and configuration of data associated with entities (loot tables, etc.). + * + * @param + * The type of entity being built + * @param

+ * Parent object type + */ +public class EntityBuilder extends AbstractBuilder, EntityType, P, EntityBuilder> { + + /** + * Create a new {@link EntityBuilder} and configure data. Used in lieu of adding side-effects to constructor, so + * that alternate initialization strategies can be done in subclasses. + *

+ * The entity will be assigned the following data: + *

    + *
  • The default translation (via {@link #defaultLang()})
  • + *
+ * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the entity + * @param classification + * The {@link MobCategory} of the entity + * @return A new {@link EntityBuilder} with reasonable default data generators. + */ + public static EntityBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, EntityType.EntityFactory factory, + MobCategory classification) { + return new EntityBuilder<>(owner, parent, name, callback, factory, classification) + .defaultLang(); + } + + private final NonNullSupplier> builder; + + private NonNullConsumer> builderCallback = $ -> {}; + + private @Nullable NonNullSupplier>> renderer; + + private boolean attributesConfigured, spawnConfigured; + + protected EntityBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, EntityType.EntityFactory factory, MobCategory classification) { + super(owner, parent, name, callback, Registries.ENTITY_TYPE); + this.builder = () -> EntityType.Builder.of(factory, classification); + } + + /** + * Modify the properties of the entity. Modifications are done lazily, but the passed function is composed with the + * current one, and as such this method can be called multiple times to perform + * different operations. + * + * @param cons + * The action to perform on the properties + * @return this {@link EntityBuilder} + */ + public EntityBuilder properties(NonNullConsumer> cons) { + builderCallback = builderCallback.andThen(cons); + return this; + } + + /** + * Register an {@link EntityRenderer} for this entity. + *

+ * + * @param renderer + * A (server safe) supplier to an {@link EntityRendererProvider} that will provide this entity's + * renderer + * @return this {@link EntityBuilder} + */ + public EntityBuilder renderer(NonNullSupplier>> renderer) { + if (this.renderer == null && FMLEnvironment.getDist().isClient()) { // First call only + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerRenderer); + } + this.renderer = renderer; + return this; + } + + protected void registerRenderer() { + OneTimeEventReceiver.addModListener(getOwner(), EntityRenderersEvent.RegisterRenderers.class, evt -> { + var renderer = this.renderer; + if (renderer != null) { + try { + var provider = renderer.get(); + evt.registerEntityRenderer(getEntry(), provider::apply); + } catch (Exception e) { + throw new IllegalStateException("Failed to register renderer for Entity " + get().getId(), e); + } + } + }); + } + + /** + * Register a attributes for this entity. The entity must extend {@link LivingEntity}. + *

+ * Cannot be called more than once per builder. + * + * @param attributes + * A supplier to the attributes for this entity, usually of the form + * {@code EntityClass::createAttributes} + * @return this {@link EntityBuilder} + * @throws IllegalStateException + * When called more than once + */ + @SuppressWarnings("unchecked") + public EntityBuilder attributes(Supplier attributes) { + if (attributesConfigured) { + throw new IllegalStateException("Cannot configure attributes more than once"); + } + attributesConfigured = true; + OneTimeEventReceiver.addModListener(getOwner(), EntityAttributeCreationEvent.class, e -> e.put((EntityType) getEntry(), attributes.get().build())); + return this; + } + + /** + * Register a spawn placement for this entity. The entity must extend {@link Mob} and allow construction with a + * {@code null} {@link Level}. + *

+ * Cannot be called more than once per builder. + * + * @param type + * The type of placement to use + * @param heightmap + * Which heightmap to use to choose placement locations + * @param predicate + * A predicate to check spawn locations for validity + * @return this {@link EntityBuilder} + * @throws IllegalStateException + * When called more than once + */ + @SuppressWarnings("unchecked") + public EntityBuilder spawnPlacement(SpawnPlacementType type, Heightmap.Types heightmap, SpawnPredicate predicate, RegisterSpawnPlacementsEvent.Operation operation) { + if (spawnConfigured) { + throw new IllegalStateException("Cannot configure spawn placement more than once"); + } + spawnConfigured = true; + this.onRegister(t -> { + OneTimeEventReceiver.addModListener(getOwner(), RegisterSpawnPlacementsEvent.class, e -> { + e.register(t, type, heightmap, predicate, operation); + }); + }); + return this; + } + + /** + * Create a spawn egg item for this entity and build it immediately. + * + * @return this {@link EntityBuilder} + */ + public EntityBuilder spawnEgg() { + return spawnEgg($ -> {}); + } + + /** + * Create a spawn egg item for this entity and expose its builder for further customization. + * + *

+ * The created egg uses the modern {@link net.minecraft.world.item.Item.Properties#spawnEgg(EntityType)} API and is + * added to {@link CreativeModeTabs#SPAWN_EGGS} by default. + * + *

+ * No default item model is generated. If a consumer wants spawn egg visuals, + * it should provide them explicitly via the nested {@link ItemBuilder}. + * + * @param consumer + * A callback for customizing the nested egg {@link ItemBuilder} + * @return this {@link EntityBuilder} + */ + public EntityBuilder spawnEgg(NonNullConsumer>> consumer) { + NonNullSupplier> entityType = asSupplier(); + ItemBuilder> eggBuilder = getOwner() + .item(this, getName() + "_spawn_egg", SpawnEggItem::new) + .properties(properties -> properties.spawnEgg(entityType.get())) + .tab(CreativeModeTabs.SPAWN_EGGS); + consumer.accept(eggBuilder); + return eggBuilder.build(); + } + + /** + * Assign the default translation, as specified by + * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, net.minecraft.resources.ResourceKey)}. This is + * the default, so it is generally + * not necessary to call, unless for undoing previous changes. + * + * @return this {@link EntityBuilder} + */ + public EntityBuilder defaultLang() { + return lang(EntityType::getDescriptionId); + } + + /** + * Set the translation for this entity. + * + * @param name + * A localized English name + * @return this {@link EntityBuilder} + */ + public EntityBuilder lang(String name) { + return lang(EntityType::getDescriptionId, name); + } + + /** + * Configure the loot table for this entity. This is different than most data gen callbacks as the callback does not + * accept a {@link DataGenContext}, but instead a + * {@link RegistrateEntityLootTables}, for creating specifically entity loot tables. + * + * @param cons + * The callback which will be invoked during entity loot table creation. + * @return this {@link EntityBuilder} + */ + public EntityBuilder loot(NonNullBiConsumer> cons) { + return setData(ProviderType.LOOT, (ctx, prov) -> prov.addLootAction(LootType.ENTITY, tb -> cons.accept(tb, ctx.getEntry()))); + } + + /** + * Assign {@link TagKey}{@code s} to this entity. Multiple calls will add additional tags. + * + * @param tags + * The tags to assign + * @return this {@link EntityBuilder} + */ + @SafeVarargs + public final EntityBuilder tag(TagKey>... tags) { + return tag(ProviderType.ENTITY_TAGS, tags); + } + + @Override + protected EntityType createEntry() { + EntityType.Builder builder = this.builder.get(); + builderCallback.accept(builder); + return builder.build(getResourceKey()); + } + + @Override + protected RegistryEntry, EntityType> createEntryWrapper(DeferredHolder, EntityType> delegate) { + return new EntityEntry<>(getOwner(), delegate); + } + + @Override + public EntityEntry register() { + return (EntityEntry) super.register(); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java new file mode 100644 index 0000000..3bee7af --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java @@ -0,0 +1,660 @@ +package com.modularmc.registrate.builders; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.builders.base.AbstractBuilder; +import com.modularmc.registrate.builders.base.BuilderCallback; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; +import com.modularmc.registrate.internal.util.RegistrateDistExecutor; +import com.modularmc.registrate.providers.RegistrateLangProvider; +import com.modularmc.registrate.providers.RegistrateTagsProvider; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.util.entry.FluidEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.*; + +import net.minecraft.client.data.models.model.ModelTemplates; +import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.client.renderer.block.FluidModel; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.TagKey; +import net.minecraft.util.Util; +import net.minecraft.world.item.BucketItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.LiquidBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Fluid; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.neoforge.client.event.RegisterFluidModelsEvent; +import net.neoforged.neoforge.client.extensions.common.IClientBlockExtensions; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; +import net.neoforged.neoforge.common.util.Lazy; +import net.neoforged.neoforge.fluids.BaseFlowingFluid; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.NeoForgeRegistries; + +import com.google.common.annotations.Beta; +import com.google.common.base.Preconditions; +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import java.util.function.ToIntFunction; + +public class FluidBuilder extends AbstractBuilder> { + + @FunctionalInterface + public interface FluidTypeFactory { + + FluidType create(FluidType.Properties properties); + } + + @FunctionalInterface + public interface FluidFactory { + + T create(BaseFlowingFluid.Properties properties); + } + + private @Nullable NonNullSupplier> model; + private @Nullable Material blockParticleTexture; + + private @Nullable NonNullSupplier> clientExtension; + + /** + * Register a client extension for this block. The {@link IClientBlockExtensions} instance can be shared across many + * items. + * + * @param clientExtension + * The client extension to register for this block + * @return this {@link BlockBuilder} + */ + public FluidBuilder clientExtension(NonNullSupplier> clientExtension) { + if (this.clientExtension == null) { + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); + } + this.clientExtension = clientExtension; + return this; + } + + public FluidBuilder model(Identifier stillTexture, Identifier flowingTexture) { + this.blockParticleTexture = new Material(stillTexture); + return model(() -> () -> new FluidModel.Unbaked(new Material(stillTexture), new Material(flowingTexture), null, null)); + } + + public FluidBuilder model(NonNullSupplier> model) { + if (this.model == null) { + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerModel); + } + this.model = model; + return this; + } + + protected void registerModel() { + var modEventBus = getOwner().getModEventBus(); + java.util.function.Consumer listener = e -> { + NonNullSupplier> model = this.model; + if (model != null) { + NonNullSupplier source = this.source; + if (source != null) { + e.register(model.get().get(), source.get(), getEntry()); + } else { + e.register(model.get().get(), getEntry()); + } + } + }; + if (modEventBus != null) { + modEventBus.addListener(listener); + } else { + OneTimeEventReceiver.addModListener(getOwner(), RegisterFluidModelsEvent.class, listener); + } + } + + protected void registerClientExtension() { + OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, e -> { + NonNullSupplier> clientExtension = this.clientExtension; + if (clientExtension != null) { + e.registerFluidType(clientExtension.get().get(), fluidType.get()); + } + }); + } + + /** + * Create a new {@link FluidBuilder} and configure data. The created builder will use a default ({@link FluidType}) + * and fluid class ({@link BaseFlowingFluid.Flowing}). + * + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @return A new {@link FluidBuilder} with reasonable default data generators. + * @see #create(AbstractRegistrate, Object, String, BuilderCallback, FluidTypeFactory, FluidFactory) + */ + public static

FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback) { + return create(owner, parent, name, callback, FluidType::new, BaseFlowingFluid.Flowing::new); + } + + /** + * Create a new {@link FluidBuilder} and configure data. The created builder will use a default fluid class + * ({@link BaseFlowingFluid.Flowing}). + * + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param typeFactory + * A factory that creates the fluid type + * @return A new {@link FluidBuilder} with reasonable default data generators. + * @see #create(AbstractRegistrate, Object, String, BuilderCallback, FluidTypeFactory, FluidFactory) + */ + public static

FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, FluidTypeFactory typeFactory) { + return create(owner, parent, name, callback, typeFactory, BaseFlowingFluid.Flowing::new); + } + + /** + * Create a new {@link FluidBuilder} and configure data. The created builder will use a default fluid class + * ({@link BaseFlowingFluid.Flowing}). + * + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param fluidType + * An existing and registered fluid type. + * @return A new {@link FluidBuilder} with reasonable default data generators. + * @see #create(AbstractRegistrate, Object, String, BuilderCallback, FluidTypeFactory, FluidFactory) + */ + public static

FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullSupplier fluidType) { + return create(owner, parent, name, callback, p -> fluidType.get(), BaseFlowingFluid.Flowing::new); + } + + /** + * Create a new {@link FluidBuilder} and configure data. The created builder will use a default ({@link FluidType}) + * and fluid class ({@link BaseFlowingFluid.Flowing}). + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param fluidFactory + * A factory that creates the flowing fluid + * @return A new {@link FluidBuilder} with reasonable default data generators. + */ + public static FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, + FluidFactory fluidFactory) { + return create(owner, parent, name, callback, FluidType::new, fluidFactory); + } + + /** + * Create a new {@link FluidBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + *

+ * The fluid will be assigned the following data: + *

    + *
  • The default translation (via {@link #defaultLang()})
  • + *
  • A default {@link BaseFlowingFluid.Source source fluid} (via {@link #defaultSource})
  • + *
  • A default block for the fluid, with its own default blockstate and model that configure the particle texture + * (via {@link #defaultBlock()})
  • + *
  • A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid + * (via {@link #defaultBucket()})
  • + *
+ * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param typeFactory + * A factory that creates the fluid type + * @param fluidFactory + * A factory that creates the flowing fluid + * @return A new {@link FluidBuilder} with reasonable default data generators. + */ + public static FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, + FluidTypeFactory typeFactory, FluidFactory fluidFactory) { + FluidBuilder ret = new FluidBuilder<>(owner, parent, name, callback, typeFactory, fluidFactory) + .defaultLang().defaultSource().defaultBlock().defaultBucket(); + return ret; + } + + /** + * Create a new {@link FluidBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + *

+ * The fluid will be assigned the following data: + *

    + *
  • The default translation (via {@link #defaultLang()})
  • + *
  • A default {@link BaseFlowingFluid.Source source fluid} (via {@link #defaultSource})
  • + *
  • A default block for the fluid, with its own default blockstate and model that configure the particle texture + * (via {@link #defaultBlock()})
  • + *
  • A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid + * (via {@link #defaultBucket()})
  • + *
+ * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param fluidType + * An existing and registered fluid type + * @param fluidFactory + * A factory that creates the flowing fluid + * @return A new {@link FluidBuilder} with reasonable default data generators. + */ + public static FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, + NonNullSupplier fluidType, FluidFactory fluidFactory) { + return new FluidBuilder<>(owner, parent, name, callback, fluidType, fluidFactory) + .defaultLang().defaultSource().defaultBlock().defaultBucket(); + } + + private final String sourceName, bucketName; + + private final FluidFactory fluidFactory; + + private @Nullable final NonNullSupplier fluidType; + + private @Nullable Boolean defaultSource, defaultBlock, defaultBucket; + + private NonNullConsumer typeProperties = $ -> {}; + + private NonNullConsumer fluidProperties = $ -> {}; + + private boolean registerType; + + private @Nullable NonNullSupplier source; + private final List> tags = new ArrayList<>(); + + public FluidBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, FluidTypeFactory typeFactory, FluidFactory fluidFactory) { + super(owner, parent, "flowing_" + name, callback, Registries.FLUID); + this.sourceName = name; + this.bucketName = name + "_bucket"; + this.fluidFactory = fluidFactory; + this.fluidType = NonNullSupplier.lazy(() -> typeFactory.create(makeTypeProperties())); + this.registerType = true; + } + + public FluidBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullSupplier fluidType, FluidFactory fluidFactory) { + super(owner, parent, "flowing_" + name, callback, Registries.FLUID); + this.sourceName = name; + this.bucketName = name + "_bucket"; + this.fluidFactory = fluidFactory; + this.fluidType = fluidType; + this.registerType = false; // Don't register if we have a fluid from outside. + } + + /** + * Modify the properties of the fluid type. Modifications are done lazily, but the passed function is composed with + * the current one, and as such this method can be called multiple times to perform + * different operations. + * + * @param cons + * The action to perform on the attributes + * @return this {@link FluidBuilder} + */ + public FluidBuilder properties(NonNullConsumer cons) { + typeProperties = typeProperties.andThen(cons); + return this; + } + + /** + * Modify the properties of the flowing fluid. Modifications are done lazily, but the passed function is composed + * with the current one, and as such this method can be called multiple times to perform + * different operations. + * + * @param cons + * The action to perform on the attributes + * @return this {@link FluidBuilder} + */ + public FluidBuilder fluidProperties(NonNullConsumer cons) { + fluidProperties = fluidProperties.andThen(cons); + return this; + } + + /** + * Assign the default translation, as specified by {@link RegistrateLangProvider#toEnglishName(String)}. This is the + * default, so it is generally not necessary to call, unless for + * undoing previous changes. + * + * @return this {@link FluidBuilder} + */ + public FluidBuilder defaultLang() { + return lang(f -> f.getFluidType().getDescriptionId(), RegistrateLangProvider.toEnglishName(sourceName)); + } + + /** + * Set the translation for this fluid. + * + * @param name + * A localized English name + * @return this {@link FluidBuilder} + */ + public FluidBuilder lang(String name) { + return lang(f -> f.getFluidType().getDescriptionId(), name); + } + + /** + * Create a standard {@link BaseFlowingFluid.Source} for this fluid which will be built and registered along with + * this fluid. + * + * @return this {@link FluidBuilder} + * @see #source(NonNullFunction) + * @throws IllegalStateException + * If {@link #source(NonNullFunction)} has been called before this method + */ + public FluidBuilder defaultSource() { + if (this.defaultSource != null) { + throw new IllegalStateException("Cannot set a default source after a custom source has been created"); + } + this.defaultSource = true; + return this; + } + + /** + * Create a {@link BaseFlowingFluid} for this fluid, which is created by the given factory, and which will be built + * and registered along with this fluid. + * + * @param factory + * A factory for the fluid, which accepts the properties and returns a new fluid + * @return this {@link FluidBuilder} + */ + public FluidBuilder source(NonNullFunction factory) { + this.defaultSource = false; + this.source = NonNullSupplier.lazy(() -> factory.apply(makeProperties())); + return this; + } + + /** + * Create a standard {@link LiquidBlock} for this fluid, building it immediately, and not allowing for further + * configuration. + * + * @return this {@link FluidBuilder} + * @see #block() + * @throws IllegalStateException + * If {@link #block()} or {@link #block(NonNullBiFunction)} has been called before + * this method + */ + public FluidBuilder defaultBlock() { + if (this.defaultBlock != null) { + throw new IllegalStateException("Cannot set a default block after a custom block has been created"); + } + this.defaultBlock = true; + return this; + } + + /** + * Create a standard {@link LiquidBlock} for this fluid, and return the builder for it so that further customization + * can be done. + * + * @return the {@link BlockBuilder} for the {@link LiquidBlock} + */ + public BlockBuilder> block() { + return block(LiquidBlock::new); + } + + /** + * Create a {@link LiquidBlock} for this fluid, which is created by the given factory, and return the builder for it + * so that further customization can be done. + * + * @param + * The type of the block + * @param factory + * A factory for the block, which accepts the block object and properties and returns a new block + * @return the {@link BlockBuilder} for the {@link LiquidBlock} + */ + public BlockBuilder> block(NonNullBiFunction factory) { + if (this.defaultBlock == Boolean.FALSE) { + throw new IllegalStateException("Only one call to block/noBlock per builder allowed"); + } + this.defaultBlock = false; + final NonNullSupplier supplier = asSupplier(); + final var lightLevel = Lazy.of(() -> fluidType.get().getLightLevel()); + final ToIntFunction lightLevelInt = $ -> lightLevel.get(); + final Material particleTexture = this.blockParticleTexture; + final var ret = getOwner().>block(this, sourceName, p -> factory.apply(supplier.get(), p)) + .properties(p -> BlockBehaviour.Properties.ofFullCopy(Blocks.WATER).noLootTable()) + .properties(p -> p.lightLevel(lightLevelInt)) + .blockstate(() -> (ctx, prov) -> { + if (particleTexture != null) { + prov.generateWithTemplate(ctx.get(), ModelTemplates.PARTICLE_ONLY, TextureMapping.particle(particleTexture)); + } else { + prov.createNonTemplateModelBlock(ctx.get()); + } + }); + this.fluidProperties(p -> p.block(ret.asSupplier())); + return ret; + } + + @Beta + public FluidBuilder noBlock() { + if (this.defaultBlock == Boolean.FALSE) { + throw new IllegalStateException("Only one call to block/noBlock per builder allowed"); + } + this.defaultBlock = false; + return this; + } + + /** + * Create a standard {@link BucketItem} for this fluid, building it immediately, and not allowing for further + * configuration. + * + * @return this {@link FluidBuilder} + * @see #bucket() + * @throws IllegalStateException + * If {@link #bucket()} or {@link #bucket(NonNullBiFunction)} has been called before + * this method + */ + public FluidBuilder defaultBucket() { + if (this.defaultBucket != null) { + throw new IllegalStateException("Cannot set a default bucket after a custom bucket has been created"); + } + defaultBucket = true; + return this; + } + + /** + * Create a standard {@link BucketItem} for this fluid, and return the builder for it so that further customization + * can be done. + * + * @return the {@link ItemBuilder} for the {@link BucketItem} + */ + public ItemBuilder> bucket() { + return bucket(BucketItem::new); + } + + /** + * Create a {@link BucketItem} for this fluid, which is created by the given factory, and return the builder for it + * so that further customization can be done. + * + * @param + * The type of the bucket item + * @param factory + * A factory for the bucket item, which accepts the fluid object supplier and properties and returns + * a new item + * @return the {@link ItemBuilder} for the {@link BucketItem} + */ + public ItemBuilder> bucket(NonNullBiFunction factory) { + if (this.defaultBucket == Boolean.FALSE) { + throw new IllegalStateException("Only one call to bucket/noBucket per builder allowed"); + } + this.defaultBucket = false; + NonNullSupplier source = this.source; + if (source == null) { + throw new IllegalStateException("Cannot create a bucket before creating a source block"); + } + final var ret = getOwner().>item(this, bucketName, p -> factory.apply(source.get(), p)) + .properties(p -> p.craftRemainder(Items.BUCKET).stacksTo(1)) + .model(() -> (ctx, prov) -> prov.generateFluidBucket(ctx.getEntry(), source.get())); + this.fluidProperties(p -> p.bucket(ret.asSupplier())); + return ret; + } + + @Beta + public FluidBuilder noBucket() { + if (this.defaultBucket == Boolean.FALSE) { + throw new IllegalStateException("Only one call to bucket/noBucket per builder allowed"); + } + this.defaultBucket = false; + return this; + } + + /** + * Assign {@link TagKey}{@code s} to this fluid and its source fluid. Multiple calls will add additional tags. + * + * @param tags + * The tags to assign + * @return this {@link FluidBuilder} + */ + @SafeVarargs + public final FluidBuilder tag(TagKey... tags) { + FluidBuilder ret = this.tag(ProviderType.FLUID_TAGS, tags); + if (this.tags.isEmpty()) { + ret.getOwner()., Fluid>setDataGenerator(ret.sourceName, getRegistryKey(), ProviderType.FLUID_TAGS, + prov -> this.tags.stream().map(prov::tag).forEach(p -> p.add(getSource()))); + } + this.tags.addAll(Arrays.asList(tags)); + return ret; + } + + /** + * Remove {@link TagKey}{@code s} from this fluid and its source fluid. Multiple calls will remove additional tags. + * + * @param tags + * The tags to remove + * @return this {@link FluidBuilder} + */ + @SafeVarargs + public final FluidBuilder removeTag(TagKey... tags) { + this.tags.removeAll(Arrays.asList(tags)); + return this.removeTag(ProviderType.FLUID_TAGS, tags); + } + + private BaseFlowingFluid getSource() { + NonNullSupplier source = this.source; + Preconditions.checkNotNull(source, "Fluid has no source block: " + sourceName); + return source.get(); + } + + private BaseFlowingFluid.Properties makeProperties() { + NonNullSupplier source = this.source; + BaseFlowingFluid.Properties ret = new BaseFlowingFluid.Properties(fluidType, source == null ? null : source::get, asSupplier()); + fluidProperties.accept(ret); + return ret; + } + + private FluidType.Properties makeTypeProperties() { + FluidType.Properties properties = FluidType.Properties.create(); + Optional> block = getOwner().getOptional(sourceName, Registries.BLOCK); + this.typeProperties.accept(properties); + + // Force the translation key after the user callback runs + // This is done because we need to remove the lang data generator if using the block key, + // and if it was possible to undo this change, it might result in the user translation getting + // silently lost, as there's no good way to check whether the translation key was changed. + if (block.isPresent() && block.get().isBound()) { + properties.descriptionId(block.get().get().getDescriptionId()); + removeData(ProviderType.LANG); + } else { + properties.descriptionId(Util.makeDescriptionId("fluid", Identifier.fromNamespaceAndPath(getOwner().getModid(), sourceName))); + } + + return properties; + } + + @Override + protected T createEntry() { + return fluidFactory.create(makeProperties()); + } + + /** + * {@inheritDoc} + *

+ * Additionally registers the source fluid and the fluid type (if constructed). + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public FluidEntry register() { + // Check the fluid has a type. + if (this.fluidType != null) { + // Register the type. + if (this.registerType) { + getOwner().simple(this, this.sourceName, NeoForgeRegistries.Keys.FLUID_TYPES, this.fluidType); + } + } else { + throw new IllegalStateException("Fluid must have a type: " + getName()); + } + + if (defaultSource == Boolean.TRUE) { + source(BaseFlowingFluid.Source::new); + } + if (defaultBlock == Boolean.TRUE) { + block().register(); + } + if (defaultBucket == Boolean.TRUE) { + bucket().register(); + } + + NonNullSupplier source = this.source; + if (source != null) { + getCallback().accept(sourceName, Registries.FLUID, (FluidBuilder) this, source::get); + } else { + throw new IllegalStateException("Fluid must have a source version: " + getName()); + } + + return (FluidEntry) super.register(); + } + + @Override + protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { + return new FluidEntry<>(getOwner(), delegate); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java new file mode 100644 index 0000000..2462102 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java @@ -0,0 +1,357 @@ +package com.modularmc.registrate.builders; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.builders.base.AbstractBuilder; +import com.modularmc.registrate.builders.base.BuilderCallback; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; +import com.modularmc.registrate.internal.util.RegistrateDistExecutor; +import com.modularmc.registrate.providers.DataGenContext; +import com.modularmc.registrate.providers.RegistrateLangProvider; +import com.modularmc.registrate.providers.core.GeneratorType; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator; +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; +import com.modularmc.registrate.util.CreativeModeTabModifier; +import com.modularmc.registrate.util.entry.ItemEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullBiConsumer; +import com.modularmc.registrate.util.nullness.NonNullFunction; +import com.modularmc.registrate.util.nullness.NonNullSupplier; +import com.modularmc.registrate.util.nullness.NonNullUnaryOperator; + +import net.minecraft.client.color.item.ItemTintSource; +import net.minecraft.client.data.models.model.ModelTemplates; +import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; +import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.datamaps.builtin.Compostable; +import net.neoforged.neoforge.registries.datamaps.builtin.FurnaceFuel; +import net.neoforged.neoforge.registries.datamaps.builtin.NeoForgeDataMaps; + +import com.google.common.collect.Maps; +import org.jspecify.annotations.Nullable; + +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * A builder for items, allows for customization of the {@link Item.Properties} and configuration of data associated + * with items (models, recipes, etc.). + * + * @param + * The type of item being built + * @param

+ * Parent object type + */ +public class ItemBuilder extends AbstractBuilder> { + + /** + * Create a new {@link ItemBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + *

+ * The item will be assigned the following data: + *

    + *
  • A simple generated model with one texture (via {@link #defaultModel()})
  • + *
  • The default translation (via {@link #defaultLang()})
  • + *
+ * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning {@link AbstractRegistrate} object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the item + * @return A new {@link ItemBuilder} with reasonable default data generators. + */ + public static ItemBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory) { + return new ItemBuilder<>(owner, parent, name, callback, factory) + .defaultModel().defaultLang(); + } + + private final NonNullFunction factory; + + private NonNullSupplier initialProperties = Item.Properties::new; + private NonNullFunction propertiesCallback = NonNullUnaryOperator.identity(); + + private Map, NonNullBiConsumer, CreativeModeTabModifier>> creativeModeTabs = Maps.newLinkedHashMap(); + + protected ItemBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory) { + super(owner, parent, name, callback, Registries.ITEM); + this.factory = factory; + + onRegister(item -> { + creativeModeTabs.forEach((creativeModeTab, consumer) -> owner.modifyCreativeModeTab(creativeModeTab, modifier -> consumer.accept(DataGenContext.from(this), modifier))); + creativeModeTabs.clear(); // this registration should only fire once, to doubly ensure this, clear the map + }); + } + + /** + * Modify the properties of the item. Modifications are done lazily, but the passed function is composed with the + * current one, and as such this method can be called multiple times to perform + * different operations. + *

+ * If a different properties instance is returned, it will replace the existing one entirely. + * + * @param func + * The action to perform on the properties + * @return this {@link ItemBuilder} + */ + public ItemBuilder properties(NonNullUnaryOperator func) { + propertiesCallback = propertiesCallback.andThen(func); + return this; + } + + /** + * Replace the initial state of the item properties, without replacing or removing any modifications done via + * {@link #properties(NonNullUnaryOperator)}. + * + * @param properties + * A supplier to to create the initial properties + * @return this {@link ItemBuilder} + */ + public ItemBuilder initialProperties(NonNullSupplier properties) { + initialProperties = properties; + return this; + } + + /** + * Sets a tab modifier for the given tab which can be used to define custom logic for how the item stack is created + * and/or added to the tab. + * + *

+ * CreativeModeTab registration is delegated off until the item has been finalized and registered to the + * {@link net.minecraft.core.registries.BuiltInRegistries#ITEM Item registry}.
+ * This means you can call this method as many times as you like during the build process with no added side + * effects. + *

+ * Calling this method with different {@link ResourceKey tab keys} will add the modifier to all the specified tabs. + *

+ * Calling this method multiple times with the same {@link ResourceKey tab key} will replace any existing modifier + * for that tab. + * + * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to use the modifier for + * @param modifier A {@link Consumer consumer} accepting a {@link CreativeModeTabModifier} used to update the tab + * @return This builder + * @deprecated Use {@link #tab(ResourceKey, NonNullBiConsumer)} which provides access to the registered item. + */ + @Deprecated + public ItemBuilder tab(ResourceKey tab, Consumer modifier) { + return tab(tab, ($, m) -> modifier.accept(m)); + } + + /** + * Sets a tab modifier for the given tab which can be used to define custom logic for how the item stack is created + * and/or added to the tab. + * + *

+ * CreativeModeTab registration is delegated off until the item has been finalized and registered to the + * {@link net.minecraft.core.registries.BuiltInRegistries#ITEM Item registry}.
+ * This means you can call this method as many times as you like during the build process with no added side + * effects. + *

+ * Calling this method with different {@link ResourceKey tab keys} will add the modifier to all the specified tabs. + *

+ * Calling this method multiple times with the same {@link ResourceKey tab key} will replace any existing modifier + * for that tab. + * + * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to use the modifier for + * @param modifier A {@link NonNullBiConsumer consumer} accepting a context object and + * {@link CreativeModeTabModifier} used to update the tab + * @return This builder + */ + public ItemBuilder tab(ResourceKey tab, NonNullBiConsumer, CreativeModeTabModifier> modifier) { + creativeModeTabs.put(tab, modifier); // Should we get the current value in the map [if one exists] and + // .andThen() the 2 together? right now we replace any consumer that + // currently exists + return this; + } + + /** + * Adds the item built from this builder into the given CreativeModeTab using the default ItemStack instance. + *

+ * CreativeModeTab registration is delegated off until the item has been finalized and registered to the + * {@link net.minecraft.core.registries.BuiltInRegistries#ITEM Item registry}.
+ * This means you can call this method as many times as you like during the build process with no added side + * effects. + *

+ * Calling this method with different {@link ResourceKey tab keys} will add the item to all the specified tabs. + *

+ * Calling this method multiple times with the same {@link NonNullSupplier tab supplier} will have no effect. + * + * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to add to + * @return This builder + * @see #tab(ResourceKey, NonNullBiConsumer) + */ + public ItemBuilder tab(ResourceKey tab) { + return tab(tab, (item, modifier) -> modifier.accept(item)); + } + + /** + * Removes the modifier from this builder from the given {@link CreativeModeTab}. + * + * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to remove the modifier from + * @return This builder + */ + public ItemBuilder removeTab(ResourceKey tab) { + creativeModeTabs.remove(tab); + return this; + } + + /** + * Assign the default model to this item, which is simply a generated model with a single texture of the same name. + * + * @return this {@link ItemBuilder} + */ + public ItemBuilder defaultModel() { + return defaultModel(new ItemTintSource[0]); + } + + /** + * Assign the default generated model to this item and apply the supplied item tint sources to its layers. + * + * @param tints + * Tint sources to apply to the generated model layers + * @return this {@link ItemBuilder} + */ + public ItemBuilder defaultModel(ItemTintSource... tints) { + return model(() -> (ctx, prov) -> prov.generateFlatItem(ctx.get(), ModelTemplates.FLAT_ITEM, TextureMapping.layer0(ctx.get()), tints)); + } + + /** + * Configure the model for this item. + * + * @param cons + * The callback which will be invoked during data creation + * @return this {@link ItemBuilder} + * @see #setData(GeneratorType, NonNullBiConsumer) + */ + public ItemBuilder model(NonNullSupplier, RegistrateItemModelGenerator>> cons) { + if (!getOwner().doDatagen().get()) return this; + return setData(ProviderType.ITEM_MODEL, cons.get()); + } + + /** + * Assign the default translation, as specified by + * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, net.minecraft.resources.ResourceKey)}. This is + * the default, so it is generally + * not necessary to call, unless for undoing previous changes. + * + * @return this {@link ItemBuilder} + */ + public ItemBuilder defaultLang() { + return lang(Item::getDescriptionId); + } + + /** + * Set the translation for this item. + * + * @param name + * A localized English name + * @return this {@link ItemBuilder} + */ + public ItemBuilder lang(String name) { + return lang(Item::getDescriptionId, name); + } + + /** + * Configure the recipe(s) for this item. + * + * @param cons + * The callback which will be invoked during data generation. + * @return this {@link ItemBuilder} + * @see #setData(GeneratorType, NonNullBiConsumer) + */ + public ItemBuilder recipe(NonNullBiConsumer, RegistrateRecipeProvider> cons) { + return setData(ProviderType.RECIPE, cons); + } + + /** + * Add burn time for the item + * + * @param tick time in ticks for this item to burn in furnace. + */ + public ItemBuilder burnTime(int tick) { + return dataMap(NeoForgeDataMaps.FURNACE_FUELS, new FurnaceFuel(tick)); + } + + /** + * Add compost chance for the item + * + * @param chance chance for composter to increase one level when composting this item. + */ + public ItemBuilder compostable(float chance) { + return dataMap(NeoForgeDataMaps.COMPOSTABLES, new Compostable(chance)); + } + + private @Nullable NonNullSupplier> clientExtension; + + /** + * Register a client extension for this item. The {@link IClientItemExtensions} instance can be shared across many + * items. + * + * @param clientExtension + * The client extension to register for this item + * @return this {@link ItemBuilder} + */ + public ItemBuilder clientExtension(NonNullSupplier> clientExtension) { + if (this.clientExtension == null) { + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); + } + this.clientExtension = clientExtension; + return this; + } + + protected void registerClientExtension() { + OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, e -> { + NonNullSupplier> clientExtension = this.clientExtension; + if (clientExtension != null) { + e.registerItem(clientExtension.get().get(), getEntry()); + } + }); + } + + /** + * Assign {@link TagKey}{@code s} to this item. Multiple calls will add additional tags. + * + * @param tags + * The tag to assign + * @return this {@link ItemBuilder} + */ + @SafeVarargs + public final ItemBuilder tag(TagKey... tags) { + return tag(ProviderType.ITEM_TAGS, tags); + } + + @Override + protected T createEntry() { + Item.Properties properties = this.initialProperties.get(); + properties = propertiesCallback.apply(properties); + return factory.apply(properties.setId(getResourceKey())); + } + + @Override + protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { + return new ItemEntry<>(getOwner(), delegate); + } + + @Override + public ItemEntry register() { + return (ItemEntry) super.register(); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.java b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.java new file mode 100644 index 0000000..9b0b6d1 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.java @@ -0,0 +1,80 @@ +package com.modularmc.registrate.builders; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.builders.base.AbstractBuilder; +import com.modularmc.registrate.builders.base.BuilderCallback; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; +import com.modularmc.registrate.internal.util.RegistrateDistExecutor; +import com.modularmc.registrate.util.entry.MenuEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; +import net.neoforged.api.distmarker.Dist; +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; +import net.neoforged.neoforge.common.extensions.IMenuTypeExtension; +import net.neoforged.neoforge.registries.DeferredHolder; + +import org.jspecify.annotations.Nullable; + +public class MenuBuilder, P> extends AbstractBuilder, MenuType, P, MenuBuilder> { + + public interface MenuFactory { + + T create(MenuType type, int windowId, Inventory inv); + } + + public interface ForgeMenuFactory { + + T create(MenuType type, int windowId, Inventory inv, @Nullable RegistryFriendlyByteBuf buffer); + } + + public interface ScreenFactory> { + + T create(M menu, Inventory inv, Component displayName); + } + + private final ForgeMenuFactory factory; + private final NonNullSupplier> screenFactory; + + public MenuBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, MenuFactory factory, NonNullSupplier> screenFactory) { + this(owner, parent, name, callback, (type, windowId, inv, $) -> factory.create(type, windowId, inv), screenFactory); + } + + public MenuBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { + super(owner, parent, name, callback, Registries.MENU); + this.factory = factory; + this.screenFactory = screenFactory; + } + + @Override + protected MenuType createEntry() { + ForgeMenuFactory factory = this.factory; + final var supplier = this.asSupplier(); + MenuType ret = IMenuTypeExtension.create((windowId, inv, buf) -> factory.create(supplier.get(), windowId, inv, buf)); + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { + ScreenFactory screenFactory = this.screenFactory.get(); + OneTimeEventReceiver.addModListener(this.getOwner(), RegisterMenuScreensEvent.class, event -> { + event.register(ret, screenFactory::create); + }); + }); + return ret; + } + + @Override + protected RegistryEntry, MenuType> createEntryWrapper(DeferredHolder, MenuType> delegate) { + return new MenuEntry<>(getOwner(), delegate); + } + + @Override + public MenuEntry register() { + return (MenuEntry) super.register(); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java new file mode 100644 index 0000000..d67442b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java @@ -0,0 +1,183 @@ +package com.modularmc.registrate.builders.base; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.RegistrateLangProvider; +import com.modularmc.registrate.providers.RegistrateTagsProvider; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.util.entry.LazyRegistryEntry; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullBiFunction; +import com.modularmc.registrate.util.nullness.NonNullFunction; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.Registry; +import net.minecraft.data.tags.TagsProvider; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagEntry; +import net.minecraft.tags.TagKey; +import net.neoforged.neoforge.registries.DeferredHolder; + +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimap; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import java.util.Arrays; + +/** + * Base class which most builders should extend, instead of implementing [@link {@link Builder} directly. + *

+ * Provides the most basic functionality, and some utility methods that remove the need to pass the registry class. + * + * @param + * Type of the registry for the current object. This is the concrete base class that all registry entries + * must extend, and the type used for the forge registry itself. + * @param + * Actual type of the object being built. + * @param

+ * Type of the parent object, this is returned from {@link #build()} and {@link #getParent()}. + * @param + * Self type + * @see Builder + */ +@RequiredArgsConstructor +public abstract class AbstractBuilder> implements Builder { + + @Getter(onMethod_ = { @Override }) + private final AbstractRegistrate owner; + @Getter(onMethod_ = { @Override }) + private final P parent; + @Getter(onMethod_ = { @Override }) + private final String name; + @Getter(AccessLevel.PROTECTED) + private final BuilderCallback callback; + @Getter(onMethod_ = { @Override }) + private final ResourceKey> registryKey; + + private final Multimap>, TagKey> tagsByType = HashMultimap.create(); + + /** A supplier for the entry that will discard the reference to this builder after it is resolved */ + private final LazyRegistryEntry safeSupplier = new LazyRegistryEntry<>(this); + + /** Indicates whether this entry should generate tags as optional tag */ + private boolean isOptional = false; + + /** + * Create the built entry. This method will be lazily resolved at registration time, so it is safe to bake in values + * from the builder. + * + * @return The built entry + */ + @SuppressWarnings("null") + protected abstract T createEntry(); + + @Override + public RegistryEntry register() { + return callback.accept(name, registryKey, this, this::createEntry, this::createEntryWrapper); + } + + protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { + return new RegistryEntry<>(getOwner(), delegate); + } + + @Override + public NonNullSupplier asSupplier() { + return safeSupplier; + } + + /** + * Tag this entry with a tag (or tags) of the correct type. Multiple calls will add additional tags. + * + * @param type + * The provider type (which must be a tag provider) + * @param tags + * The tags to add + * @return this {@link Builder} + */ + @SuppressWarnings("unchecked") + @SafeVarargs + public final & RegistrateTagsProvider> S tag(ProviderType type, TagKey... tags) { + if (!tagsByType.containsKey(type)) { + setData(type, (ctx, prov) -> tagsByType.get(type).stream() + .map(t -> (TagKey) t) + .map(prov::rawBuilder) + .forEach(b -> b.add(asTag()))); + } + tagsByType.putAll(type, Arrays.asList(tags)); + return (S) this; + } + + /** + * Mark this entry as optional when generating tags + */ + @SuppressWarnings("unchecked") + public S asOptional() { + isOptional = true; + return (S) this; + } + + protected TagEntry asTag() { + Identifier id = Identifier.fromNamespaceAndPath(getOwner().getModid(), getName()); + if (isOptional) return TagEntry.optionalElement(id); + return TagEntry.element(id); + } + + /** + * Remove a tag (or tags) from this entry of a given type. Useful to remove default tags on fluids, for example. + * Multiple calls will remove additional tags. + * + * @param type + * The provider type (which must be a tag provider) + * @param tags + * The tags to remove + * @return this {@link Builder} + */ + @SuppressWarnings("unchecked") + @SafeVarargs + public final & RegistrateTagsProvider> S removeTag(ProviderType type, TagKey... tags) { + if (tagsByType.containsKey(type)) { + for (TagKey tag : tags) { + tagsByType.remove(type, tag); + } + } + return (S) this; + } + + /** + * Set the lang key for this entry to the default value (specified by + * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, ResourceKey)}). Generally, specific helpers from + * concrete + * builders should be used instead. + * + * @param langKeyProvider + * A function to get the translation key from the entry + * @return this {@link Builder} + */ + public S lang(NonNullFunction langKeyProvider) { + return lang(langKeyProvider, (p, t) -> p.getAutomaticName(t, getRegistryKey())); + } + + /** + * Set the lang key for this entry to the specified name. Generally, specific helpers from concrete builders should + * be used instead. + * + * @param langKeyProvider + * A function to get the translation key from the entry + * @param name + * The name to use + * @return this {@link Builder} + */ + public S lang(NonNullFunction langKeyProvider, String name) { + return lang(langKeyProvider, (p, s) -> name); + } + + private S lang(NonNullFunction langKeyProvider, NonNullBiFunction, String> localizedNameProvider) { + return setData(ProviderType.LANG, (ctx, prov) -> prov.add(langKeyProvider.apply(ctx.getEntry()), localizedNameProvider.apply(prov, ctx::getEntry))); + } + + public ResourceKey getResourceKey() { + return ResourceKey.create(getRegistryKey(), Identifier.fromNamespaceAndPath(getOwner().getModid(), getName())); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/Builder.java b/src/main/java/com/modularmc/registrate/builders/base/Builder.java new file mode 100644 index 0000000..2d79248 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/Builder.java @@ -0,0 +1,282 @@ +package com.modularmc.registrate.builders.base; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.DataGenContext; +import com.modularmc.registrate.providers.core.GeneratorType; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.*; + +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; +import net.neoforged.neoforge.registries.datamaps.DataMapType; + +import java.util.function.Function; + +/** + * A Builder creates registry entries. A Builder instance has a constant name which will be used for the resultant + * object, they cannot be reused for different names. It holds a parent object that will + * be returned from some final methods. + *

+ * When a builder is completed via {@link #register()} or {@link #build()}, the object will be lazily registered + * (through the owning {@link AbstractRegistrate} object). + * + * @param + * Type of the registry for the current object. This is the concrete base class that all registry entries + * must extend, and the type used for the forge registry itself. + * @param + * Actual type of the object being built. + * @param

+ * Type of the parent object, this is returned from {@link #build()} and {@link #getParent()}. + * @param + * Self type + */ +public interface Builder> extends NonNullSupplier> { + + /** + * Complete the current entry, and return the {@link RegistryEntry} that will supply the built entry once it is + * available. The builder can be used afterwards, and changes made will reflect the + * output, as long as it is before registration takes place (before forge registry events). + * + * @return The {@link RegistryEntry} supplying the built entry. + */ + RegistryEntry register(); + + /** + * The owning {@link AbstractRegistrate} that created this builder. + * + * @return the owner {@link AbstractRegistrate} + */ + AbstractRegistrate getOwner(); + + /** + * The parent object. + * + * @return the parent object of this builder + */ + P getParent(); + + /** + * The name of the entry being created, and combined with the mod ID of the parent {@link AbstractRegistrate}, the + * registry name. + * + * @return the name of the current entry + */ + String getName(); + + ResourceKey> getRegistryKey(); + + /** + * Get the {@link RegistryEntry} representing the entry built by this builder. Cannot be called before the builder + * is built. + * + * @return An {@link RegistryEntry} for this builder's entry + * @throws IllegalArgumentException + * If this builder has not been built yet + */ + @Override + default RegistryEntry get() { + return getOwner().get(getName(), getRegistryKey()); + } + + /** + * Get the actual entry built by this builder. Cannot be called before registration. + * + * @return This builder's entry + * @throws IllegalArgumentException + * If this builder has not been built yet + * @throws NullPointerException + * If the entry from this builder has not been registered yet + */ + default T getEntry() { + return get().get(); + } + + /** + * Get a supplier for the entry created by this builder, which will not reference the builder after it has been + * resolved. + * + * @return A supplier for the entry + */ + NonNullSupplier asSupplier(); + + /** + * Set the data provider callback for this entry for the given provider type, which will be invoked when the + * provider of the given type executes. + *

+ * If called multiple times for the same type, the existing callback will be overwritten. + *

+ * This is mostly unneeded, and instead helper methods for specific data types should be used when possible. + * + * @param + * The type of provider + * @param type + * The {@link GeneratorType} for the desired provider + * @param cons + * The callback to execute when the provider is run + * @return this builder + */ + @SuppressWarnings("unchecked") + default S setData(GeneratorType type, NonNullBiConsumer, D> cons) { + getOwner().setDataGenerator(this, type, prov -> cons.accept(DataGenContext.from(this), prov)); + return (S) this; + } + + /** + * Remove the data provider callback for this entry for the given provider type, if one was previously configured. + * + * @param + * The type of provider + * @param type + * The {@link GeneratorType} for the desired provider + * @return this builder + */ + @SuppressWarnings("unchecked") + default S removeData(GeneratorType type) { + getOwner().removeDataGenerator(this, type); + return (S) this; + } + + /** + * Add a data provider callback which will be invoked when the provider of the given type executes. + *

+ * Calling this multiple times for the same type will not overwrite an existing callback. + * + * @param + * The type of provider + * @param type + * The {@link GeneratorType} for the desired provider + * @param cons + * The callback to execute when the provider is run + * @return this builder + */ + @SuppressWarnings("unchecked") + default S addMiscData(GeneratorType type, NonNullConsumer cons) { + getOwner().addDataGenerator(type, cons); + return (S) this; + } + + /** + * Add data map associated with this builder + */ + @SuppressWarnings("unchecked") + default S dataMap(DataMapType type, D val) { + getOwner().addDataGenerator(ProviderType.DATA_MAP, e -> e.builder(type) + .add(DataGenContext.from(this).getId(), val, false)); + return (S) this; + } + + /** + * Add data map associated with this builder, with context + */ + @SuppressWarnings("unchecked") + default S dataMap(DataMapType type, NonNullFunction, D> factory) { + getOwner().addDataGenerator(ProviderType.DATA_MAP, e -> { + var ctx = DataGenContext.from(this); + e.builder(type).add(ctx.getId(), factory.apply(ctx), false); + }); + return (S) this; + } + + /** + * Add data map associated with this builder, with context + */ + @SuppressWarnings("unchecked") + default S dataMap(DataMapType type, NonNullBiFunction, HolderLookup.Provider, D> factory) { + getOwner().addDataGenerator(ProviderType.DATA_MAP, e -> { + var ctx = DataGenContext.from(this); + e.builder(type).add(ctx.getId(), factory.apply(ctx, e.getProvider()), false); + }); + return (S) this; + } + + /** + * Add a callback to be invoked when this entry is registered. Can be called multiple times to add multiple + * callbacks. + *

+ * Builders which have had this method used on them (or another method which calls this one), must + * be registered, via + * {@link #register()}, or errors will be thrown when these "dangling" register callbacks are discovered at register + * time. + * + * @param callback + * the callback to invoke + * @return this {@link Builder} + */ + @SuppressWarnings("unchecked") + default S onRegister(NonNullConsumer callback) { + getOwner().addRegisterCallback(getName(), getRegistryKey(), callback); + return (S) this; + } + + /** + * Add a callback to be invoked when this entry is registered, but only after some other registry type has been + * registered as well. Can be called multiple times to add multiple callbacks. + *

+ * Builders which have had this method used on them (or another method which calls this one), must + * be registered, via + * {@link #register()}, or errors will be thrown when these "dangling" register callbacks are discovered at register + * time. + * + * @param + * The dependency registry type + * @param dependencyType + * the base class for objects of the dependency registry. The callback will be invoked only + * after this registry has fired its registry events. + * @param callback + * the callback to invoke + * @return this {@link Builder} + */ + default S onRegisterAfter(ResourceKey> dependencyType, NonNullConsumer callback) { + return onRegister(e -> { + if (getOwner().isRegistered(dependencyType)) { + callback.accept(e); + } else { + getOwner().addRegisterCallback(dependencyType, () -> callback.accept(e)); + } + }); + } + + /** + * Apply a transformation to this {@link Builder}. Useful to apply helper methods within a fluent chain, e.g. + * + *

+     * {@code
+     *
+     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
+     *         .block(MyBlock::new)
+     *         .transform(Utils::defaultBlockProperties)
+     *         .register();
+     * }
+     * 
+ * + * @param + * Registry type + * @param + * Entry type + * @param + * Parent type + * @param + * Self type + * @param func + * The {@link Function function} to apply + * @return the {@link Builder} returned by the given function + */ + @SuppressWarnings("unchecked") + default > S2 transform(NonNullFunction func) { + return func.apply((S) this); + } + + /** + * Register the entry and return the parent object. The {@link net.neoforged.neoforge.registries.DeferredHolder} + * will be created but not returned. It can be retrieved later with {@link AbstractRegistrate#get(ResourceKey)} or + * {@link AbstractRegistrate#get(String, ResourceKey)}. + * + * @return the parent object + */ + default P build() { + register(); // Ignore return value + return getParent(); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java new file mode 100644 index 0000000..ff40121 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java @@ -0,0 +1,62 @@ +package com.modularmc.registrate.builders.base; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullFunction; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; +import net.neoforged.neoforge.registries.DeferredHolder; + +/** + * A callback passed to {@link Builder builders} from the owning {@link AbstractRegistrate} which will add a + * registration for the built entry that lazily creates and registers it. + */ +@FunctionalInterface +public interface BuilderCallback { + + /** + * Accept a built entry, to later be constructed and registered. + * + * @param + * The registry type to which the entry will be registered + * @param + * The type of the entry + * @param name + * The name of the entry + * @param type + * A {@link ResourceKey} representing the registry type + * @param builder + * The builder performing this callback + * @param factory + * A {@link NonNullSupplier} that will create the entry + * @param entryFactory + * A {@link NonNullFunction} which accepts the entry delegate and returns a + * {@link RegistryEntry} wrapper + * @return A {@link RegistryEntry} that will supply the registered entry + */ + RegistryEntry accept(String name, ResourceKey> type, Builder builder, NonNullSupplier factory, NonNullFunction, ? extends RegistryEntry> entryFactory); + + /** + * Accept a built entry, to later be constructed and registered. Uses the default + * {@link RegistryEntry#RegistryEntry(AbstractRegistrate, DeferredHolder) RegistryEntry factory}. + * + * @param + * The registry type to which the entry will be registered + * @param + * The type of the entry + * @param name + * The name of the entry + * @param type + * A {@link Class} representing the registry type + * @param builder + * The builder performing this callback + * @param factory + * A {@link NonNullSupplier} that will create the entry + * @return A {@link RegistryEntry} that will supply the registered entry + */ + default RegistryEntry accept(String name, ResourceKey> type, Builder builder, NonNullSupplier factory) { + return accept(name, type, builder, factory, delegate -> new RegistryEntry<>(builder.getOwner(), delegate)); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java new file mode 100644 index 0000000..7645feb --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java @@ -0,0 +1,22 @@ +package com.modularmc.registrate.builders.base; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; + +public class NoConfigBuilder extends AbstractBuilder> { + + private final NonNullSupplier factory; + + public NoConfigBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, ResourceKey> registryType, NonNullSupplier factory) { + super(owner, parent, name, callback, registryType); + this.factory = factory; + } + + @Override + protected T createEntry() { + return factory.get(); + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/package-info.java b/src/main/java/com/modularmc/registrate/builders/base/package-info.java new file mode 100644 index 0000000..3240767 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/package-info.java @@ -0,0 +1,5 @@ +/** + * Base builder contracts and shared builder implementation scaffolding. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.builders.base; diff --git a/src/main/java/com/modularmc/registrate/builders/package-info.java b/src/main/java/com/modularmc/registrate/builders/package-info.java new file mode 100644 index 0000000..fde0603 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/package-info.java @@ -0,0 +1,10 @@ +/** + * Fluent concrete builder APIs for registering content. + * + *

+ * These classes form the primary downstream-facing DSL. Shared builder + * contracts and scaffolding live in {@code com.modularmc.registrate.builders.base}, + * while this package focuses on content-specific registration behavior. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.builders; diff --git a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java new file mode 100644 index 0000000..e43afe9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java @@ -0,0 +1,243 @@ +package com.modularmc.registrate.internal; + +import com.modularmc.registrate.internal.util.DebugMarkers; +import com.modularmc.registrate.internal.util.RegistrateLogger; +import com.modularmc.registrate.util.entry.RegistryEntry; +import com.modularmc.registrate.util.nullness.NonNullConsumer; +import com.modularmc.registrate.util.nullness.NonNullFunction; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.Registry; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.RegisterEvent; + +import com.google.common.base.Preconditions; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimap; +import com.google.common.collect.Table; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public final class RegistrationTracker { + + private static final Logger LOGGER = RegistrateLogger.registration(); + + private static final class Registration { + + private final Identifier identifier; + private final ResourceKey> registryKey; + private final NonNullSupplier creator; + private final RegistryEntry delegate; + private final List> callbacks = new ArrayList<>(); + + private Registration( + Identifier identifier, + ResourceKey> registryKey, + NonNullSupplier creator, + NonNullFunction, ? extends RegistryEntry> entryFactory) { + this.identifier = identifier; + this.registryKey = registryKey; + this.creator = creator.lazy(); + this.delegate = entryFactory.apply(DeferredHolder.create(registryKey, identifier)); + } + + private Identifier getIdentifier() { + return identifier; + } + + private RegistryEntry getDelegate() { + return delegate; + } + + private void register(RegisterEvent event) { + T entry = creator.get(); + event.register(registryKey, helper -> helper.register(identifier, entry)); + callbacks.forEach(callback -> callback.accept(entry)); + callbacks.clear(); + } + + private void addRegisterCallback(NonNullConsumer callback) { + Preconditions.checkNotNull(callback, "Callback must not be null"); + callbacks.add(callback); + } + } + + private final String modId; + private final Table>, String, Registration> registrations = HashBasedTable.create(); + private final Multimap>>, NonNullConsumer> pendingEntryCallbacks = HashMultimap.create(); + private final Multimap>, Runnable> afterRegisterCallbacks = HashMultimap.create(); + private final Set>> completedRegistrations = new HashSet<>(); + + public RegistrationTracker(String modId) { + this.modId = modId; + } + + public void onRegister(RegisterEvent event, boolean skipErrors, boolean devEnvironment) { + ResourceKey> registryKey = event.getRegistryKey(); + if (registryKey == null) { + LOGGER.debug( + DebugMarkers.REGISTER, + RegistrateLogger.modMessage("Skipping registry event without a registry key"), + modId); + return; + } + + if (!pendingEntryCallbacks.isEmpty()) { + pendingEntryCallbacks.asMap().forEach((entryKey, callbacks) -> LOGGER.warn( + RegistrateLogger.modMessage("Found {} unused register callback(s) for entry {} [{}]. Was the entry ever registered?"), + modId, + callbacks.size(), + entryKey.getLeft(), + entryKey.getRight().identifier())); + pendingEntryCallbacks.clear(); + if (devEnvironment) { + throw new IllegalStateException("Found unused register callbacks, see logs"); + } + } + + Map> registrationsForType = registrations.row(registryKey); + if (registrationsForType.isEmpty()) { + return; + } + + LOGGER.trace( + DebugMarkers.REGISTER, + RegistrateLogger.modMessage("Registering {} captured object(s) in {}"), + modId, + registrationsForType.size(), + registryKey.identifier()); + for (var entry : registrationsForType.entrySet()) { + Registration registration = entry.getValue(); + try { + registration.register(event); + LOGGER.trace( + DebugMarkers.REGISTER, + RegistrateLogger.modMessage("Registered {} in {}"), + modId, + registration.getIdentifier(), + registryKey.identifier()); + } catch (Exception exception) { + if (skipErrors) { + LOGGER.error( + DebugMarkers.REGISTER, + RegistrateLogger.modMessage("Unexpected error while registering entry {} in {}"), + modId, + registration.getIdentifier(), + registryKey.identifier(), + exception); + } else { + throw new RuntimeException( + "[%s] Unexpected error while registering entry %s in %s" + .formatted(modId, registration.getIdentifier(), registryKey.identifier()), + exception); + } + } + } + } + + public void onRegisterLate(RegisterEvent event) { + ResourceKey> registryKey = event.getRegistryKey(); + if (registryKey == null) { + return; + } + + Collection callbacks = afterRegisterCallbacks.get(registryKey); + callbacks.forEach(Runnable::run); + callbacks.clear(); + completedRegistrations.add(registryKey); + } + + public RegistryEntry track( + String name, + ResourceKey> registryKey, + NonNullSupplier creator, + NonNullFunction, ? extends RegistryEntry> entryFactory) { + Registration registration = new Registration<>( + Identifier.fromNamespaceAndPath(modId, name), + registryKey, + creator, + entryFactory); + LOGGER.trace( + DebugMarkers.REGISTER, + RegistrateLogger.modMessage("Captured registration {} for registry {}"), + modId, + registration.getIdentifier(), + registryKey.identifier()); + pendingEntryCallbacks.removeAll(Pair.of(name, registryKey)).forEach(callback -> { + @SuppressWarnings("unchecked") + NonNullConsumer unsafeCallback = (NonNullConsumer) callback; + registration.addRegisterCallback(unsafeCallback); + }); + registrations.put(registryKey, name, registration); + return registration.getDelegate(); + } + + public void addRegisterCallback( + String name, + ResourceKey> registryKey, + NonNullConsumer callback) { + Registration registration = getRegistrationUnchecked(name, registryKey); + if (registration == null) { + pendingEntryCallbacks.put(Pair.of(name, registryKey), callback); + return; + } + registration.addRegisterCallback(callback); + } + + public void addAfterRegisterCallback(ResourceKey> registryKey, Runnable callback) { + afterRegisterCallbacks.put((ResourceKey>) registryKey, callback); + } + + public boolean isRegistered(ResourceKey> registryKey) { + return completedRegistrations.contains(registryKey); + } + + @SuppressWarnings("unchecked") + public RegistryEntry get(String name, ResourceKey> registryKey) { + return (RegistryEntry) getRegistration(name, registryKey).getDelegate(); + } + + public Optional> getOptional( + String name, + ResourceKey> registryKey) { + Registration registration = getRegistrationUnchecked(name, registryKey); + return registration == null ? Optional.empty() : Optional.of(registration.getDelegate()); + } + + @SuppressWarnings("unchecked") + public Collection> getAll(ResourceKey> registryKey) { + return registrations.row(registryKey) + .values() + .stream() + .map(registration -> (RegistryEntry) registration.getDelegate()) + .collect(Collectors.toList()); + } + + @SuppressWarnings("unchecked") + private Registration getRegistration(String name, ResourceKey> registryKey) { + Registration registration = (Registration) registrations.get(registryKey, name); + if (registration != null) { + return registration; + } + throw new IllegalArgumentException("Unknown registration " + name + " for type " + registryKey.identifier()); + } + + @SuppressWarnings("unchecked") + private Registration getRegistrationUnchecked( + String name, + ResourceKey> registryKey) { + return (Registration) registrations.get(registryKey, name); + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java b/src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java new file mode 100644 index 0000000..a23ed28 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java @@ -0,0 +1,22 @@ +package com.modularmc.registrate.internal.datagen; + +import net.minecraft.client.ClientBootstrap; + +/** + * Bridges the gap between NeoForge's server-side datagen entrypoints and + * Minecraft's client-side model codec bootstrap. + * + *

+ * In 26.1, item model serialization depends on client bootstrap state even when + * data generation is launched through the server datagen path. Triggering the + * vanilla bootstrap here keeps Registrate's client-facing generators usable in + * headless datagen runs. + */ +public final class RegistrateDatagenBootstrap { + + private RegistrateDatagenBootstrap() {} + + public static void bootstrapClientCodecs() { + ClientBootstrap.bootstrap(); + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java new file mode 100644 index 0000000..9c3d1b0 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java @@ -0,0 +1,111 @@ +package com.modularmc.registrate.internal.event; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.neoforged.bus.api.Event; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.IModBusEvent; +import net.neoforged.fml.event.lifecycle.FMLLoadCompleteEvent; + +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +@RequiredArgsConstructor +public final class OneTimeEventReceiver implements Consumer { + + public static void addModListener( + AbstractRegistrate owner, + Class evtClass, + Consumer listener) { + addModListener(owner, EventPriority.NORMAL, evtClass, listener); + } + + public static void addModListener( + AbstractRegistrate owner, + EventPriority priority, + Class evtClass, + Consumer listener) { + if (owner.getModEventBus() == null) { + if (!waitingModListeners.contains(owner, evtClass)) { + waitingModListeners.put(owner, evtClass, new ArrayList<>()); + } + waitingModListeners.get(owner, evtClass).add(Pair.of(priority, listener)); + return; + } + + if (initializedOwners.add(owner)) { + flushWaitingModListeners(owner); + addModListener(owner, FMLLoadCompleteEvent.class, OneTimeEventReceiver::onLoadComplete); + } + + addListener(owner.getModEventBus(), priority, evtClass, listener); + } + + private static final Set> initializedOwners = Collections.newSetFromMap(new IdentityHashMap<>()); + private static final Table, Class, List>>> waitingModListeners = HashBasedTable.create(); + + private final IEventBus bus; + private final Consumer listener; + private final AtomicBoolean consumed = new AtomicBoolean(); + + @Override + public void accept(T event) { + if (consumed.compareAndSet(false, true)) { + listener.accept(event); + unregister(bus, this, event); + } + } + + private static final List>> toUnregister = new ArrayList<>(); + + private static synchronized void unregister(IEventBus bus, Object listener, Event event) { + unregister(bus, listener, event.getClass()); + } + + public static synchronized void unregister(AbstractRegistrate owner, Object listener, Class event) { + unregister(owner.getModEventBus(), listener, event); + } + + private static synchronized void unregister(IEventBus bus, Object listener, Class event) { + toUnregister.add(Triple.of(bus, listener, event)); + } + + private static void onLoadComplete(FMLLoadCompleteEvent event) { + event.enqueueWork(() -> { + toUnregister.forEach(t -> t.getLeft().unregister(t.getMiddle())); + toUnregister.clear(); + }); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static void flushWaitingModListeners(AbstractRegistrate owner) { + var waitingListeners = new ArrayList<>(waitingModListeners.row(owner).entrySet()); + waitingModListeners.row(owner).clear(); + for (var waitingListener : waitingListeners) { + for (var pair : waitingListener.getValue()) { + addListener(owner.getModEventBus(), pair.getKey(), (Class) waitingListener.getKey(), (Consumer) pair.getValue()); + } + } + } + + @SuppressWarnings("unchecked") + private static void addListener( + IEventBus bus, + EventPriority priority, + Class evtClass, + Consumer listener) { + bus.addListener(priority, false, (Class) evtClass, new OneTimeEventReceiver<>(bus, listener)); + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/event/package-info.java b/src/main/java/com/modularmc/registrate/internal/event/package-info.java new file mode 100644 index 0000000..be778bf --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/event/package-info.java @@ -0,0 +1,6 @@ +/** + * Event-bus plumbing that supports one-shot registration hooks for the public + * Registrate DSL. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.internal.event; diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java new file mode 100644 index 0000000..7f175a6 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java @@ -0,0 +1,86 @@ +package com.modularmc.registrate.internal.lifecycle; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.internal.event.OneTimeEventReceiver; + +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.neoforge.data.event.GatherDataEvent; +import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; +import net.neoforged.neoforge.registries.RegisterEvent; + +import org.jspecify.annotations.Nullable; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +/** + * Centralizes the per-instance NeoForge lifecycle wiring for a Registrate + * owner. + * + *

+ * This keeps lifecycle listener registration easy to discover without + * collapsing multiple mod instances into a shared global runtime. + */ +public final class RegistrateLifecycle { + + public interface Hooks { + + @Nullable + IEventBus modEventBus(); + + void setModEventBus(IEventBus bus); + + boolean doDatagen(); + + void onRegister(RegisterEvent event); + + void onRegisterLate(RegisterEvent event); + + void onBuildCreativeModeTabContents(BuildCreativeModeTabContentsEvent event); + + void onData(GatherDataEvent event); + } + + private final AbstractRegistrate owner; + private final Hooks hooks; + + public RegistrateLifecycle(AbstractRegistrate owner, Hooks hooks) { + this.owner = owner; + this.hooks = hooks; + } + + public void register(IEventBus bus) { + if (hooks.modEventBus() == null) { + hooks.setModEventBus(bus); + } + + Consumer onRegister = hooks::onRegister; + Consumer onRegisterLate = hooks::onRegisterLate; + bus.addListener(onRegister); + bus.addListener(EventPriority.LOWEST, onRegisterLate); + bus.addListener(hooks::onBuildCreativeModeTabContents); + + // Register events fire multiple times, so clean them up on common setup. + OneTimeEventReceiver.addModListener(owner, FMLCommonSetupEvent.class, event -> { + event.getClass(); + OneTimeEventReceiver.unregister(owner, onRegister, RegisterEvent.class); + OneTimeEventReceiver.unregister(owner, onRegisterLate, RegisterEvent.class); + }); + + if (hooks.doDatagen()) { + AtomicBoolean dataHooked = new AtomicBoolean(); + Consumer onData = event -> { + if (dataHooked.compareAndSet(false, true)) { + hooks.onData(event); + } + }; + + // Different moddev run types dispatch different concrete gather events. + // Register both and guard the callback so data providers are only attached once. + OneTimeEventReceiver.addModListener(owner, GatherDataEvent.Client.class, onData); + OneTimeEventReceiver.addModListener(owner, GatherDataEvent.Server.class, onData); + } + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java b/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java new file mode 100644 index 0000000..6a752dd --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/package-info.java @@ -0,0 +1,6 @@ +/** + * Per-instance lifecycle bridges that attach Registrate owners to the NeoForge + * mod bus. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.internal.lifecycle; diff --git a/src/main/java/com/modularmc/registrate/internal/package-info.java b/src/main/java/com/modularmc/registrate/internal/package-info.java new file mode 100644 index 0000000..97ad00b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/package-info.java @@ -0,0 +1,9 @@ +/** + * Internal implementation details that back the public Registrate API. + * + *

+ * Types in this package are free to change during development and should not + * be treated as stable extension points for downstream mods. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.internal; diff --git a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java new file mode 100644 index 0000000..f02d9f6 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java @@ -0,0 +1,19 @@ +package com.modularmc.registrate.internal.util; + +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; + +@SuppressWarnings("null") +public final class DebugMarkers { + + private static final String PREFIX = "REGISTRATE."; + + public static final Marker REGISTER = marker("REGISTER"); + public static final Marker DATA = marker("DATA"); + + private DebugMarkers() {} + + private static Marker marker(String name) { + return MarkerManager.getMarker(PREFIX + name); + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java new file mode 100644 index 0000000..e9c46d1 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java @@ -0,0 +1,17 @@ +package com.modularmc.registrate.internal.util; + +import net.neoforged.api.distmarker.Dist; +import net.neoforged.fml.loading.FMLEnvironment; + +import java.util.function.Supplier; + +public final class RegistrateDistExecutor { + + private RegistrateDistExecutor() {} + + public static void unsafeRunWhenOn(Dist dist, Supplier toRun) { + if (dist == FMLEnvironment.getDist()) { + toRun.get().run(); + } + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java new file mode 100644 index 0000000..7a896b3 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java @@ -0,0 +1,40 @@ +package com.modularmc.registrate.internal.util; + +import com.modularmc.registrate.RegistrateLib; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public final class RegistrateLogger { + + private static final Logger ROOT = RegistrateLib.LOGGER; + private static final Logger CORE = child("Core"); + private static final Logger DATAGEN = child("Datagen"); + private static final Logger REGISTRATION = child("Registration"); + + private RegistrateLogger() {} + + public static Logger root() { + return ROOT; + } + + public static Logger core() { + return CORE; + } + + public static Logger datagen() { + return DATAGEN; + } + + public static Logger registration() { + return REGISTRATION; + } + + public static String modMessage(String message) { + return "[{}] " + message; + } + + private static Logger child(String name) { + return LogManager.getLogger(ROOT.getName() + "." + name); + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/util/package-info.java b/src/main/java/com/modularmc/registrate/internal/util/package-info.java new file mode 100644 index 0000000..9def3cb --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/util/package-info.java @@ -0,0 +1,5 @@ +/** + * Small implementation-only helpers used by runtime internals. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.internal.util; diff --git a/src/main/java/com/modularmc/registrate/package-info.java b/src/main/java/com/modularmc/registrate/package-info.java new file mode 100644 index 0000000..d75e1cf --- /dev/null +++ b/src/main/java/com/modularmc/registrate/package-info.java @@ -0,0 +1,10 @@ +/** + * Root package for the public Registrate entrypoints. + * + *

+ * This layer contains the main orchestration types used by downstream mods: + * the abstract registration coordinator, the default {@code Registrate} + * implementation, and the NeoForge library entrypoint used by this fork. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate; diff --git a/src/main/java/com/modularmc/registrate/providers/DataGenContext.java b/src/main/java/com/modularmc/registrate/providers/DataGenContext.java new file mode 100644 index 0000000..a3733e4 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/DataGenContext.java @@ -0,0 +1,47 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.builders.base.Builder; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.Registry; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Value; +import lombok.experimental.Delegate; + +/** + * A context bean passed to data generator callbacks. Contains the entry that data is being created for, and some + * metadata about the entry. + * + * @param + * Type of the registry to which the entry belongs + * @param + * Type of the object for which data is being generated + */ +@Value +public class DataGenContext implements NonNullSupplier { + + @Getter(AccessLevel.NONE) + @Delegate + NonNullSupplier entry; + String name; + Identifier id; + + @SuppressWarnings("null") + public E getEntry() { + return entry.get(); + } + + @Deprecated + public static DataGenContext from(Builder builder, ResourceKey> type) { + return from(builder); + } + + public static DataGenContext from(Builder builder) { + return new DataGenContext<>(NonNullSupplier.of(builder.getOwner().get(builder.getName(), builder.getRegistryKey())), builder.getName(), + Identifier.fromNamespaceAndPath(builder.getOwner().getModid(), builder.getName())); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java new file mode 100644 index 0000000..8019de5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java @@ -0,0 +1,122 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.core.RegistrateProvider; + +import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.data.CachedOutput; +import net.minecraft.data.DataProvider; +import net.minecraft.data.PackOutput; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.common.conditions.ICondition; +import net.neoforged.neoforge.common.conditions.WithConditions; + +import com.google.common.collect.Lists; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import lombok.Getter; +import org.jspecify.annotations.Nullable; + +import java.nio.file.Path; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; + +public class RegistrateAdvancementProvider implements RegistrateProvider, Consumer { + + private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().create(); + + private final AbstractRegistrate owner; + private final PackOutput packOutput; + private final CompletableFuture registriesLookup; + private final List> advancementsToSave = Lists.newArrayList(); + @Getter + private HolderLookup.Provider provider; + + public RegistrateAdvancementProvider(AbstractRegistrate owner, PackOutput packOutputIn, CompletableFuture registriesLookupIn) { + this.owner = owner; + this.packOutput = packOutputIn; + this.registriesLookup = registriesLookupIn; + } + + public Holder resolve(ResourceKey key) { + return provider.lookupOrThrow(key.registryKey()).getOrThrow(key); + } + + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; + } + + public MutableComponent title(String category, String name, String title) { + return owner.addLang("advancements", Identifier.fromNamespaceAndPath(category, name), "title", title); + } + + public MutableComponent desc(String category, String name, String desc) { + return owner.addLang("advancements", Identifier.fromNamespaceAndPath(category, name), "description", desc); + } + + private @Nullable CachedOutput cache; + private Set seenAdvancements = new HashSet<>(); + + @Override + public CompletableFuture run(CachedOutput cache) { + return registriesLookup.thenCompose(lookup -> { + this.provider = lookup; + advancementsToSave.clear(); + + try { + this.cache = cache; + this.seenAdvancements.clear(); + owner.genData(ProviderType.ADVANCEMENT, this); + } finally { + this.cache = null; + } + + return CompletableFuture.allOf(advancementsToSave.toArray(CompletableFuture[]::new)); + }); + } + + @Override + public void accept(@Nullable AdvancementHolder holder) { + withConditions(holder, List.of()); + } + + public void withConditions(@Nullable AdvancementHolder holder, List conditions) { + this.registriesLookup.thenAccept(lookup -> { + CachedOutput cache = this.cache; + if (cache == null) { + throw new IllegalStateException("Cannot accept advancements outside of act"); + } + Objects.requireNonNull(holder, "Cannot accept a null advancement"); + Path path = getPath(this.packOutput.getOutputFolder(), holder); + if (!seenAdvancements.add(holder.id())) { + throw new IllegalStateException("Duplicate advancement " + holder.id()); + } else if (conditions.isEmpty()) { + advancementsToSave.add(DataProvider.saveStable(cache, lookup, Advancement.CODEC, holder.value(), path)); + } else { + advancementsToSave.add(DataProvider.saveStable(cache, lookup, Advancement.CONDITIONAL_CODEC, + Optional.of(new WithConditions<>(conditions, holder.value())), path)); + } + }); + } + + private static Path getPath(Path pathIn, AdvancementHolder advancementIn) { + return pathIn.resolve("data/" + advancementIn.id().getNamespace() + "/advancement/" + advancementIn.id().getPath() + ".json"); + } + + public String getName() { + return "Advancements"; + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java new file mode 100644 index 0000000..27d66bf --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java @@ -0,0 +1,48 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.core.RegistrateProvider; + +import net.minecraft.core.HolderLookup; +import net.minecraft.data.PackOutput; +import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.common.data.DataMapProvider; + +import org.jetbrains.annotations.Nullable; + +import java.util.concurrent.CompletableFuture; + +public class RegistrateDataMapProvider extends DataMapProvider implements RegistrateProvider { + + private final AbstractRegistrate parent; + + private HolderLookup.@Nullable Provider provider; + + public RegistrateDataMapProvider(AbstractRegistrate parent, PackOutput output, CompletableFuture pvd) { + super(output, pvd); + this.parent = parent; + } + + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; + } + + /** + * Generate data map entries. + * + * @param provider + */ + @Override + protected void gather(HolderLookup.Provider provider) { + this.provider = provider; + parent.genData(ProviderType.DATA_MAP, this); + this.provider = null; + } + + public HolderLookup.Provider getProvider() { + if (provider == null) throw new IllegalStateException("Holder Lookup Provider is not available now"); + return provider; + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java new file mode 100644 index 0000000..a385011 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java @@ -0,0 +1,30 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.RegistrateLookupFillerProvider; + +import net.minecraft.core.HolderLookup; +import net.minecraft.data.PackOutput; +import net.minecraft.data.registries.RegistryPatchGenerator; +import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.common.data.DatapackBuiltinEntriesProvider; + +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +public class RegistrateDatapackProvider extends DatapackBuiltinEntriesProvider implements RegistrateLookupFillerProvider { + + public RegistrateDatapackProvider(AbstractRegistrate parent, PackOutput output, CompletableFuture provider) { + super(output, RegistryPatchGenerator.createLookup(provider, parent.getDataGenInitializer().getDatapackRegistryProviders()), Set.of(parent.getModid())); + } + + @Override + public CompletableFuture getFilledProvider() { + return getRegistryProvider(); + } + + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java new file mode 100644 index 0000000..cfb49a5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java @@ -0,0 +1,72 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.core.RegistrateProvider; + +import net.minecraft.core.HolderLookup; +import net.minecraft.data.CachedOutput; +import net.minecraft.data.DataProvider; +import net.minecraft.data.PackOutput; +import net.neoforged.fml.LogicalSide; + +import org.apache.commons.compress.utils.Lists; +import org.jetbrains.annotations.ApiStatus; + +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; + +public final class RegistrateGenericProvider implements RegistrateProvider { + + private final AbstractRegistrate registrate; + private final PackOutput output; + private final CompletableFuture registries; + private final LogicalSide side; + private final ProviderType providerType; + private final List generators = Lists.newArrayList(); + + @ApiStatus.Internal + public RegistrateGenericProvider(AbstractRegistrate registrate, PackOutput output, CompletableFuture registries, LogicalSide side, ProviderType providerType) { + this.registrate = registrate; + this.output = output; + this.registries = registries; + this.side = side; + this.providerType = providerType; + } + + public RegistrateGenericProvider add(Generator generator) { + generators.add(generator); + return this; + } + + @Override + public LogicalSide getSide() { + return side; + } + + @Override + public CompletableFuture run(CachedOutput cache) { + generators.clear(); + var data = new GeneratorData(output, registries); + registrate.genData(providerType, this); + return CompletableFuture.allOf(generators + .stream() + .map(generator -> generator.generate(data)) + .map(provider -> provider.run(cache)) + .toArray(CompletableFuture[]::new)); + } + + @Override + public String getName() { + return "generic_%s_provider".formatted(side.name().toLowerCase(Locale.ROOT)); + } + + public record GeneratorData(PackOutput output, CompletableFuture registries) {} + + @FunctionalInterface + public interface Generator { + + DataProvider generate(GeneratorData data); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java new file mode 100644 index 0000000..1b77d6e --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java @@ -0,0 +1,50 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; + +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.PackOutput; +import net.minecraft.data.tags.TagsProvider; +import net.minecraft.tags.TagBuilder; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +public class RegistrateItemTagsProvider extends RegistrateTagsProvider.IntrinsicImpl { + + private final CompletableFuture> blockTags; + private final Map, TagKey> tagsToCopy = new HashMap<>(); + + public RegistrateItemTagsProvider(AbstractRegistrate owner, ProviderType type, String name, PackOutput output, CompletableFuture registriesLookup, CompletableFuture> blockTags) { + super(owner, type, name, output, Registries.ITEM, registriesLookup, item -> BuiltInRegistries.ITEM.getResourceKey(item) + .orElseThrow(() -> new IllegalStateException("Cannot generate tags for unregistered item: " + item))); + this.blockTags = blockTags; + } + + public void copy(TagKey sourceTag, TagKey targetTag) { + tagsToCopy.put(sourceTag, targetTag); + } + + @Override + protected CompletableFuture createContentsProvider() { + return super.createContentsProvider().thenCombineAsync(blockTags, (lookupProvider, blockTagLookup) -> { + tagsToCopy.forEach((sourceTag, targetTag) -> { + TagBuilder tagBuilder = getOrCreateRawBuilder(targetTag); + Optional sourceBuilder = blockTagLookup.apply(sourceTag); + sourceBuilder + .orElseThrow(() -> new IllegalStateException("Missing block tag " + sourceTag.location())) + .build() + .forEach(tagBuilder::add); + }); + return lookupProvider; + }); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java new file mode 100644 index 0000000..ac14ff5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java @@ -0,0 +1,204 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.core.RegistrateProvider; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.CachedOutput; +import net.minecraft.data.PackOutput; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; +import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.common.data.LanguageProvider; + +import org.apache.commons.lang3.StringUtils; +import org.jspecify.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +public class RegistrateLangProvider extends LanguageProvider implements RegistrateProvider { + + private static class AccessibleLanguageProvider extends LanguageProvider { + + public AccessibleLanguageProvider(PackOutput packOutput, String modid, String locale) { + super(packOutput, modid, locale); + } + + @Override + public void add(@Nullable String key, @Nullable String value) { + super.add(key, value); + } + + @Override + protected void addTranslations() {} + } + + private final AbstractRegistrate owner; + + private final AccessibleLanguageProvider upsideDown; + + public RegistrateLangProvider(AbstractRegistrate owner, PackOutput packOutput) { + super(packOutput, owner.getModid(), "en_us"); + this.owner = owner; + this.upsideDown = new AccessibleLanguageProvider(packOutput, owner.getModid(), "en_ud"); + } + + @Override + public LogicalSide getSide() { + return LogicalSide.CLIENT; + } + + @Override + public String getName() { + return "Lang (en_us/en_ud)"; + } + + @Override + protected void addTranslations() { + owner.genData(ProviderType.LANG, this); + } + + public static final String toEnglishName(String internalName) { + return Arrays.stream(internalName.toLowerCase(Locale.ROOT).split("_")) + .map(StringUtils::capitalize) + .collect(Collectors.joining(" ")); + } + + @SuppressWarnings({ "unchecked", "ConstantConditions" }) + public String getAutomaticName(NonNullSupplier sup, ResourceKey> registry) { + return toEnglishName(((Registry>) BuiltInRegistries.REGISTRY).getValue(registry.identifier()).getKey(sup.get()).getPath()); + } + + public void addBlock(NonNullSupplier block) { + addBlock(block, getAutomaticName(block, Registries.BLOCK)); + } + + public void addBlockWithTooltip(NonNullSupplier block, String tooltip) { + addBlock(block); + addTooltip(block, tooltip); + } + + public void addBlockWithTooltip(NonNullSupplier block, String name, String tooltip) { + addBlock(block, name); + addTooltip(block, tooltip); + } + + public void addItem(NonNullSupplier item) { + addItem(item, getAutomaticName(item, Registries.ITEM)); + } + + public void addItemWithTooltip(NonNullSupplier block, String name, List tooltip) { + addItem(block, name); + addTooltip(block, tooltip); + } + + public void addTooltip(NonNullSupplier item, String tooltip) { + add(item.get().asItem().getDescriptionId() + ".desc", tooltip); + } + + public void addTooltip(NonNullSupplier item, List tooltip) { + for (int i = 0; i < tooltip.size(); i++) { + add(item.get().asItem().getDescriptionId() + ".desc." + i, tooltip.get(i)); + } + } + + public void add(CreativeModeTab tab, String name) { + var contents = tab.getDisplayName().getContents(); + if (contents instanceof TranslatableContents lang) { + add(lang.getKey(), name); + } else { + throw new IllegalArgumentException("Creative tab does not have a translatable name: " + tab.getDisplayName()); + } + } + + public void addEntityType(NonNullSupplier> entity) { + addEntityType(entity, getAutomaticName(entity, Registries.ENTITY_TYPE)); + } + + // Automatic en_ud generation + + private static final String NORMAL_CHARS = + /* lowercase */ "abcdefghijklmn\u00F1opqrstuvwxyz" + + /* uppercase */ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + /* numbers */ "0123456789" + + /* special */ "()[]{}<>\u25C1\u25B7_,;.?!/\\'"; + private static final String UPSIDE_DOWN_CHARS = + /* lowercase */ "\u0250q\u0254p\u01DD\u025Fb\u0265\u0131\u0638\u029E\u05DF\u026Fuuodb\u0279s\u0287n\u028C\u028Dx\u028Ez" + + /* uppercase */ "\u2C6F\u15FA\u0186\u15E1\u018E\u2132\u2141HI\u017F\u029E\uA780WNO\u0500\u1F49\u1D1AS\u27D8\u2229\u039BMX\u028EZ" + + /* numbers */ "0\u0196\u1105\u0190\u3123\u03DB9\u312586" + + /* special */ ")(][}{><\u25B7\u25C1\u203E'\u061B\u02D9\u00BF\u00A1\\/,"; + + static { + if (NORMAL_CHARS.length() != UPSIDE_DOWN_CHARS.length()) { + throw new AssertionError("Char maps do not match in length!"); + } + } + + private static boolean isFormatTokenChar(char c) { + return Character.isDigit(c) || c == '%' || c == '$' || c == 's' || c == 'd'; + } + + private String toUpsideDown(String normal) { + int formatIndex = 1; + ArrayList ud = new ArrayList<>(); + for (int i = 0; i < normal.length(); i++) { + char c = normal.charAt(i); + if (c == '%') { + String fmtArg = ""; + while (isFormatTokenChar(c)) { + if (fmtArg.equals("%") && c == 's') { + fmtArg = "%" + formatIndex + "$s"; + formatIndex++; + i++; + break; + } else if (c == '$') { + formatIndex++; + } + fmtArg += c; + i++; + c = i == normal.length() ? 0 : normal.charAt(i); + } + i--; + for (int j = fmtArg.length() - 1; j >= 0; j--) { + ud.addFirst(fmtArg.charAt(j)); + } + continue; + } + int lookup = NORMAL_CHARS.indexOf(c); + if (lookup >= 0) { + c = UPSIDE_DOWN_CHARS.charAt(lookup); + } + ud.addFirst(c); + } + StringBuilder builder = new StringBuilder(ud.size()); + for (Character ch : ud) { + builder.append(ch); + } + return builder.toString(); + } + + @Override + public void add(String key, String value) { + super.add(key, value); + upsideDown.add(key, toUpsideDown(value)); + } + + @Override + public CompletableFuture run(CachedOutput cache) { + return CompletableFuture.allOf(super.run(cache), upsideDown.run(cache)); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java new file mode 100644 index 0000000..cd3b8f0 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java @@ -0,0 +1,139 @@ +package com.modularmc.registrate.providers; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.core.RegistrateLookupFillerProvider; + +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; +import net.minecraft.data.PackOutput; +import net.minecraft.data.tags.IntrinsicHolderTagsProvider; +import net.minecraft.data.tags.KeyTagProvider; +import net.minecraft.data.tags.TagAppender; +import net.minecraft.data.tags.TagsProvider; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagBuilder; +import net.minecraft.tags.TagKey; +import net.neoforged.fml.LogicalSide; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; + +public interface RegistrateTagsProvider extends RegistrateLookupFillerProvider { + + CompletableFuture> contentsGetter(); + + ResourceKey> registry(); + + TagBuilder rawBuilder(TagKey key); + + interface Key extends RegistrateTagsProvider { + + TagAppender, T> tag(TagKey key); + } + + interface Intrinsic extends RegistrateTagsProvider { + + TagAppender tag(TagKey key); + } + + class Impl extends KeyTagProvider implements RegistrateTagsProvider.Key { + + private final AbstractRegistrate owner; + private final ProviderType> type; + private final String name; + + public Impl(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup) { + super(packOutput, registryIn, registriesLookup, owner.getModid()); + + this.owner = owner; + this.type = type; + this.name = name; + } + + @Override + public String getName() { + return "Tags (%s)".formatted(name); + } + + @Override + protected void addTags(HolderLookup.Provider provider) { + owner.genData(type, this); + } + + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; + } + + @Override + public TagBuilder rawBuilder(final TagKey key) { + return super.getOrCreateRawBuilder(key); + } + + @Override + public TagAppender, T> tag(TagKey key) { + return super.tag(key); + } + + @Override + public CompletableFuture getFilledProvider() { + return createContentsProvider(); + } + + @Override + public ResourceKey> registry() { + return registryKey; + } + } + + class IntrinsicImpl extends IntrinsicHolderTagsProvider implements RegistrateTagsProvider.Intrinsic { + + private final AbstractRegistrate owner; + private final ProviderType> type; + private final String name; + + public IntrinsicImpl(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup, Function> keyExtractor) { + super(packOutput, registryIn, registriesLookup, keyExtractor, owner.getModid()); + + this.owner = owner; + this.type = type; + this.name = name; + } + + @Override + public String getName() { + return "Tags (%s)".formatted(name); + } + + @Override + protected void addTags(HolderLookup.Provider provider) { + owner.genData(type, this); + } + + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; + } + + @Override + public TagBuilder rawBuilder(TagKey key) { + return super.getOrCreateRawBuilder(key); + } + + @Override + public TagAppender tag(final TagKey key) { + return super.tag(key); + } + + @Override + public CompletableFuture getFilledProvider() { + return createContentsProvider(); + } + + @Override + public ResourceKey> registry() { + return registryKey; + } + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java b/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java new file mode 100644 index 0000000..2113cbd --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java @@ -0,0 +1,57 @@ +package com.modularmc.registrate.providers.core; + +import net.minecraft.core.Registry; +import net.minecraft.core.RegistrySetBuilder; +import net.minecraft.resources.ResourceKey; + +import org.jspecify.annotations.Nullable; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class DataProviderInitializer { + + private final RegistrySetBuilder datapackEntryProvider = new RegistrySetBuilder(); + + private final Map, ProviderType> providerDependencies = new ConcurrentHashMap<>(); + + public DataProviderInitializer() { + addDependency(ProviderType.ITEM_TAGS, ProviderType.BLOCK_TAGS); + } + + public RegistrySetBuilder getDatapackRegistryProviders() { + return datapackEntryProvider; + } + + protected List getSortedProviders() { + List ans = new ArrayList<>(); + Set> added = new HashSet<>(); + List>> remain = new ArrayList<>(RegistrateDataProvider.TYPES.entrySet()); + while (!remain.isEmpty()) { + if (!remain.removeIf(e -> { + ProviderType type = e.getValue(); + var parent = providerDependencies.get(type); + if (parent == null || added.contains(parent)) { + ans.add(new Sorted(e.getKey(), type, parent)); + added.add(type); + return true; + } + return false; + })) throw new IllegalStateException("Looping dependency detected: " + remain); + } + return ans; + } + + public void add(ResourceKey> registry, RegistrySetBuilder.RegistryBootstrap provider) { + datapackEntryProvider.add(registry, provider); + } + + public void addDependency(ProviderType dependent, ProviderType parent) { + var old = providerDependencies.put(dependent, parent); + if (old != null) throw new IllegalStateException("Providers can have only 1 prerequisite"); + } + + public record Sorted( + String id, ProviderType type, + @Nullable ProviderType parent) {} +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java b/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java new file mode 100644 index 0000000..9c156c0 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java @@ -0,0 +1,3 @@ +package com.modularmc.registrate.providers.core; + +public interface GeneratorType {} diff --git a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java new file mode 100644 index 0000000..c6ae126 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java @@ -0,0 +1,153 @@ +package com.modularmc.registrate.providers.core; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.RegistrateAdvancementProvider; +import com.modularmc.registrate.providers.RegistrateDataMapProvider; +import com.modularmc.registrate.providers.RegistrateDatapackProvider; +import com.modularmc.registrate.providers.RegistrateGenericProvider; +import com.modularmc.registrate.providers.RegistrateItemTagsProvider; +import com.modularmc.registrate.providers.RegistrateLangProvider; +import com.modularmc.registrate.providers.RegistrateTagsProvider; +import com.modularmc.registrate.providers.generators.*; +import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.material.Fluid; +import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.data.loading.DatagenModLoader; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; + +/** + * Represents a type of data that can be generated, and specifies a factory for the provider. + *

+ * Used as a key for data generator callbacks. + *

+ * This file also defines the built-in provider types, but third-party types can be created with + * {@link #registerProvider(String, ProviderType)}. + * + * @param The type of the provider + */ +@FunctionalInterface +public interface ProviderType extends GeneratorType { + + // SERVER DATA + ProviderType DYNAMIC = registerServerData("dynamic", RegistrateDatapackProvider::new); + ProviderType DATA_MAP = registerServerData("data_map", RegistrateDataMapProvider::new); + ProviderType RECIPE_RUNNER = registerServerData("recipe_runner", RegistrateRecipeRunner::new); + ProviderType ADVANCEMENT = registerServerData("advancement", RegistrateAdvancementProvider::new); + ProviderType LOOT = registerServerData("loot", RegistrateLootTableProvider::new); + ProviderType> BLOCK_TAGS = registerIntrinsicTag("tags/block", "blocks", Registries.BLOCK, BuiltInRegistries.BLOCK); + ProviderType> ENCHANTMENT_TAGS = registerDynamicTag("tags/enchantment", "enchantments", Registries.ENCHANTMENT); + ProviderType ITEM_TAGS = registerTag("tags/item", Registries.ITEM, c -> new RegistrateItemTagsProvider(c.parent(), c.type(), "items", c.output(), c.provider(), c.require(BLOCK_TAGS).contentsGetter())); + ProviderType> FLUID_TAGS = registerIntrinsicTag("tags/fluid", "fluids", Registries.FLUID, BuiltInRegistries.FLUID); + ProviderType>> ENTITY_TAGS = registerIntrinsicTag("tags/entity", "entity_types", Registries.ENTITY_TYPE, BuiltInRegistries.ENTITY_TYPE); + ProviderType GENERIC_SERVER = registerProvider("registrate_generic_server_provider", c -> new RegistrateGenericProvider(c.parent(), c.output(), c.provider(), LogicalSide.SERVER, c.type())); + + // CLIENT DATA + ProviderType MODEL = registerClientProvider("model", () -> c -> new RegistrateModelProvider(c.parent(), c.output())); + ProviderType LANG = registerClientProvider("lang", () -> c -> new RegistrateLangProvider(c.parent(), c.output())); + ProviderType GENERIC_CLIENT = registerClientProvider("registrate_generic_client_provider", () -> c -> new RegistrateGenericProvider(c.parent(), c.output(), c.provider(), LogicalSide.CLIENT, c.type())); + + GeneratorType RECIPE = RECIPE_RUNNER.createGenerator("recipe"); + GeneratorType BLOCKSTATE = MODEL.createGenerator("blockstate"); + GeneratorType ITEM_MODEL = MODEL.createGenerator("item_model"); + + record Context(ProviderType type, AbstractRegistrate parent, + Map, RegistrateProvider> existing, + PackOutput output, + CompletableFuture provider) { + + public R require(ProviderType other) { + return other.cast(Objects.requireNonNull( + existing().get(other), + () -> "Missing provider dependency for " + RegistrateDataProvider.getTypeName(other))); + } + } + + T create(Context context); + + @SuppressWarnings("unchecked") + default T cast(RegistrateProvider provider) { + return (T) provider; + } + + default GeneratorType createGenerator(String type) { + return new GeneratorType<>() { + + public String toString() { + return type; + } + }; + } + + interface SimpleServerDataFactory extends ProviderType { + + T create(AbstractRegistrate parent, PackOutput output, CompletableFuture provider); + + @Override + default T create(Context context) { + return create(context.parent(), context.output(), context.provider()); + } + + default ProviderType asProvider() { + return this; + } + } + + static ProviderType registerServerData(String name, SimpleServerDataFactory factory) { + return registerProvider(name, factory.asProvider()); + } + + static ProviderType registerProvider(String name, ProviderType type) { + RegistrateDataProvider.TYPES.put(name, type); + return type; + } + + static ProviderType registerClientProvider(String name, NonNullSupplier> supplier) { + ProviderType type = DatagenModLoader.isRunningDataGen() ? supplier.get() : context -> { + throw new IllegalStateException("Client datagen provider '" + name + "' is unavailable outside datagen"); + }; + RegistrateDataProvider.TYPES.put(name, type); + return type; + } + + @SuppressWarnings("unchecked") + static > ProviderType registerTag(String name, ResourceKey> key, ProviderType type) { + if (RegistrateDataProvider.TAG_TYPES.containsKey(key)) { + return (ProviderType) RegistrateDataProvider.TAG_TYPES.get(key); + } + RegistrateDataProvider.TAG_TYPES.put(key, type); + RegistrateDataProvider.TYPES.put(name, type); + return type; + } + + static ProviderType> registerIntrinsicTag(String providerName, String typeName, ResourceKey> registryKey, Registry registry) { + return registerTag(providerName, registryKey, c -> new RegistrateTagsProvider.IntrinsicImpl<>(c.parent(), c.type(), typeName, c.output(), registryKey, c.provider(), keyExtractor(registry, typeName))); + } + + static ProviderType> registerDynamicTag(String providerName, String typeName, ResourceKey> registry) { + return registerTag(providerName, registry, c -> new RegistrateTagsProvider.Impl<>(c.parent(), c.type(), typeName, c.output(), registry, c.provider())); + } + + static T create(ProviderType type, AbstractRegistrate parent, Map, RegistrateProvider> existing, PackOutput output, CompletableFuture provider) { + return type.create(new Context<>(type, parent, existing, output, provider)); + } + + private static Function> keyExtractor(Registry registry, String typeName) { + return value -> registry.getResourceKey(value) + .orElseThrow(() -> new IllegalStateException("Cannot generate tags for unregistered " + typeName + " entry: " + value)); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java new file mode 100644 index 0000000..6698a79 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java @@ -0,0 +1,121 @@ +package com.modularmc.registrate.providers.core; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.internal.datagen.RegistrateDatagenBootstrap; +import com.modularmc.registrate.internal.util.DebugMarkers; +import com.modularmc.registrate.internal.util.RegistrateLogger; +import com.modularmc.registrate.providers.RegistrateTagsProvider; + +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; +import net.minecraft.data.CachedOutput; +import net.minecraft.data.DataProvider; +import net.minecraft.resources.ResourceKey; +import net.neoforged.neoforge.data.event.GatherDataEvent; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.Lists; +import org.apache.logging.log4j.Logger; +import org.jspecify.annotations.Nullable; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +public class RegistrateDataProvider implements DataProvider { + + private static final Logger LOGGER = RegistrateLogger.datagen(); + + @SuppressWarnings("null") + static final BiMap> TYPES = HashBiMap.create(); + + static final Map>, ProviderType> TAG_TYPES = new ConcurrentHashMap<>(); + + public static @Nullable String getTypeName(GeneratorType type) { + if (type instanceof ProviderType prov) + return TYPES.inverse().get(prov); + return type.toString(); + } + + private final String mod; + private final Map, RegistrateProvider> subProviders = new LinkedHashMap<>(); + private final Map, Object> subGenerators = new LinkedHashMap<>(); + private final CompletableFuture registriesLookup; + + public RegistrateDataProvider(AbstractRegistrate parent, String modid, GatherDataEvent event) { + this.mod = modid; + this.registriesLookup = event.getLookupProvider(); + + // For now, generate everything together + /* + * EnumSet sides = EnumSet.noneOf(LogicalSide.class); + * if (event.includeServer()) { + * sides.add(LogicalSide.SERVER); + * } + * if (event.includeClient()) { + * sides.add(LogicalSide.CLIENT); + * } + */ + + LOGGER.debug(DebugMarkers.DATA, RegistrateLogger.modMessage("Collecting datagen providers"), mod); + Map, RegistrateProvider> known = new HashMap<>(); + for (DataProviderInitializer.Sorted sorted : parent.getDataGenInitializer().getSortedProviders()) { + ProviderType type = sorted.type(); + var lookup = registriesLookup; + if (sorted.parent() != null) lookup = ((RegistrateLookupFillerProvider) known.get(sorted.parent())).getFilledProvider(); + RegistrateProvider prov = ProviderType.create(type, parent, known, event.getGenerator().getPackOutput(), lookup); + if (prov instanceof RegistrateTagsProvider tagsProvider && TAG_TYPES.get(tagsProvider.registry()) != type) { + throw new IllegalStateException("Tag providers must be registered through ProviderType::registerTag"); + } + known.put(type, prov); + // if (sides.contains(prov.getSide())) { + LOGGER.debug( + DebugMarkers.DATA, + RegistrateLogger.modMessage("Added datagen provider {}"), + mod, + sorted.id()); + subProviders.put(type, prov); + // } + } + } + + @Override + public CompletableFuture run(CachedOutput cache) { + RegistrateDatagenBootstrap.bootstrapClientCodecs(); + return registriesLookup.thenCompose(provider -> { + var list = Lists.>newArrayList(); + + for (Map.Entry, RegistrateProvider> e : subProviders.entrySet()) { + LOGGER.debug( + DebugMarkers.DATA, + RegistrateLogger.modMessage("Running datagen provider {}"), + mod, + getTypeName(e.getKey())); + list.add(e.getValue().run(cache)); + } ; + + return CompletableFuture.allOf(list.toArray(CompletableFuture[]::new)); + }); + } + + @Override + public String getName() { + return "Registrate Provider for " + mod + " [" + subProviders.values().stream().map(DataProvider::getName).collect(Collectors.joining(", ")) + "]"; + } + + @SuppressWarnings("unchecked") + public

Optional

getSubProvider(GeneratorType

type) { + if (type instanceof ProviderType prov) + return Optional.ofNullable((P) subProviders.get(prov)); + return Optional.ofNullable((P) subGenerators.get(type)); + } + + public void putSubProvider(GeneratorType type, T gen) { + subGenerators.put(type, gen); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java new file mode 100644 index 0000000..84a7a40 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java @@ -0,0 +1,10 @@ +package com.modularmc.registrate.providers.core; + +import net.minecraft.core.HolderLookup; + +import java.util.concurrent.CompletableFuture; + +public interface RegistrateLookupFillerProvider extends RegistrateProvider { + + CompletableFuture getFilledProvider(); +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java new file mode 100644 index 0000000..46c9d06 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java @@ -0,0 +1,9 @@ +package com.modularmc.registrate.providers.core; + +import net.minecraft.data.DataProvider; +import net.neoforged.fml.LogicalSide; + +public interface RegistrateProvider extends DataProvider { + + LogicalSide getSide(); +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java new file mode 100644 index 0000000..0a939b5 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java @@ -0,0 +1,13 @@ +package com.modularmc.registrate.providers.core; + +import net.minecraft.data.DataProvider; +import net.minecraft.resources.Identifier; + +public interface RegistrateProviderDelegate extends DataProvider { + + String getName(); + + Identifier getId(); + + T getEntry(); +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/package-info.java b/src/main/java/com/modularmc/registrate/providers/core/package-info.java new file mode 100644 index 0000000..922e156 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/package-info.java @@ -0,0 +1,6 @@ +/** + * Core provider contracts, registries, and orchestration infrastructure used + * by built-in data generators. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.providers.core; diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java new file mode 100644 index 0000000..5101007 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java @@ -0,0 +1,526 @@ +package com.modularmc.registrate.providers.generators; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; + +import net.minecraft.client.data.models.BlockModelGenerators; +import net.minecraft.client.data.models.ItemModelOutput; +import net.minecraft.client.data.models.MultiVariant; +import net.minecraft.client.data.models.blockstates.BlockModelDefinitionGenerator; +import net.minecraft.client.data.models.blockstates.MultiPartGenerator; +import net.minecraft.client.data.models.blockstates.MultiVariantGenerator; +import net.minecraft.client.data.models.blockstates.PropertyDispatch; +import net.minecraft.client.data.models.model.ModelInstance; +import net.minecraft.client.data.models.model.ModelTemplate; +import net.minecraft.client.data.models.model.ModelTemplates; +import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.client.data.models.model.TextureSlot; +import net.minecraft.client.data.models.model.TexturedModel; +import net.minecraft.client.renderer.block.dispatch.BlockStateModelDispatcher; +import net.minecraft.client.renderer.block.dispatch.VariantMutator; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.core.Direction; +import net.minecraft.resources.Identifier; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.ButtonBlock; +import net.minecraft.world.level.block.CeilingHangingSignBlock; +import net.minecraft.world.level.block.CrossCollisionBlock; +import net.minecraft.world.level.block.DoorBlock; +import net.minecraft.world.level.block.FenceBlock; +import net.minecraft.world.level.block.FenceGateBlock; +import net.minecraft.world.level.block.IronBarsBlock; +import net.minecraft.world.level.block.PipeBlock; +import net.minecraft.world.level.block.PressurePlateBlock; +import net.minecraft.world.level.block.RotatedPillarBlock; +import net.minecraft.world.level.block.SlabBlock; +import net.minecraft.world.level.block.StairBlock; +import net.minecraft.world.level.block.StandingSignBlock; +import net.minecraft.world.level.block.TrapDoorBlock; +import net.minecraft.world.level.block.WallBlock; +import net.minecraft.world.level.block.WallHangingSignBlock; +import net.minecraft.world.level.block.WallSignBlock; +import net.minecraft.world.level.block.state.properties.AttachFace; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.neoforged.fml.util.ObfuscationReflectionHelper; +import net.neoforged.neoforge.client.model.generators.template.ExtendedModelTemplateBuilder; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +public class RegistrateBlockModelGenerator extends BlockModelGenerators { + + private final AbstractRegistrate parent; + public final Map seenBlockstates = new HashMap<>(); + + public RegistrateBlockModelGenerator(AbstractRegistrate parent, Consumer known, ItemModelOutput item, BiConsumer model) { + super(known, item, model); + ObfuscationReflectionHelper.>setPrivateValue(BlockModelGenerators.class, this, g -> { + this.seenBlockstates.put(g.block(), g.create()); + known.accept(g); + }, "blockStateOutput"); + this.parent = parent; + } + + @Override + public void run() { + parent.genData(ProviderType.BLOCKSTATE, this); + } + + public void create(Block block, Identifier model) { + this.blockStateOutput.accept(createSimpleBlock(block, plainVariant(model))); + } + + public Identifier mcLoc(String id) { + return Identifier.withDefaultNamespace(id); + } + + public Identifier modLoc(String id) { + return Identifier.fromNamespaceAndPath(parent.getModid(), id); + } + + public Material mcBlockTexture(String path) { + return new Material(mcLoc("block/" + path)); + } + + public Material modBlockTexture(String path) { + return new Material(modLoc("block/" + path)); + } + + public RegistrateLegacyBlockModelBuilder withBuilder(ExtendedModelTemplateBuilder template, TextureMapping texture) { + return new RegistrateLegacyBlockModelBuilder(modelOutput, template, texture); + } + + public RegistrateLegacyBlockModelBuilder withBuilder(ExtendedModelTemplateBuilder template) { + return withBuilder(template, new TextureMapping()); + } + + public RegistrateLegacyBlockModelBuilder getBuilder() { + return withBuilder(new ExtendedModelTemplateBuilder()); + } + + public RegistrateLegacyBlockModelBuilder withParent(ModelTemplate template) { + return withBuilder(ExtendedModelTemplateBuilder.of(template)); + } + + public RegistrateLegacyBlockModelBuilder withParent(ModelTemplate template, TextureMapping texture) { + return withBuilder(ExtendedModelTemplateBuilder.of(template), texture); + } + + public RegistrateLegacyBlockModelBuilder withParent(TexturedModel model) { + return withBuilder(ExtendedModelTemplateBuilder.of(model.getTemplate()), model.getMapping()); + } + + private static TextureMapping sideBottomTopTextures(Material side, Material bottom, Material top) { + return new TextureMapping() + .put(TextureSlot.SIDE, side) + .put(TextureSlot.BOTTOM, bottom) + .put(TextureSlot.TOP, top); + } + + public Material blockTexture(Block block) { + return TextureMapping.getBlockTexture(block); + } + + public Material blockTexture(Block block, String suffix) { + return TextureMapping.getBlockTexture(block, suffix); + } + + public void generateWithTemplate(Block block, ModelTemplate template, TextureMapping textures) { + create(block, template.create(block, textures, modelOutput)); + } + + public void generate(Block block, TexturedModel.Provider texture) { + blockStateOutput.accept(createSimpleBlock(block, plainVariant(texture.create(block, modelOutput)))); + } + + public void generateAxisBlock(RotatedPillarBlock block) { + generateAxisBlock(block, blockTexture(block, "_side"), blockTexture(block, "_end")); + } + + public void generateLogBlock(RotatedPillarBlock block) { + generateAxisBlock(block, blockTexture(block), blockTexture(block, "_top")); + } + + public void generateAxisBlock(RotatedPillarBlock block, Material side, Material end) { + generateAxisBlockInternal(block, side, end, ModelTemplates.CUBE_COLUMN, ModelTemplates.CUBE_COLUMN_HORIZONTAL); + } + + private void generateAxisBlockInternal(RotatedPillarBlock block, Material side, Material end, ModelTemplate cubeColumn, ModelTemplate cubeColumnHorizontal) { + generateAxisBlock(block, + plainVariant(cubeColumn.create(block, TextureMapping.column(side, end), modelOutput)), + plainVariant(cubeColumnHorizontal.create(block, TextureMapping.column(side, end), modelOutput))); + } + + public void generateAxisBlock(RotatedPillarBlock block, MultiVariant vertical, MultiVariant horizontal) { + blockStateOutput.accept(createRotatedPillarWithHorizontalVariant(block, vertical, horizontal)); + } + + private static final int DEFAULT_ANGLE_OFFSET = 180; + + public void generateHorizontalBlock(Block block, Material side, Material front, Material top) { + TextureMapping mapping = new TextureMapping().put(TextureSlot.SIDE, side).put(TextureSlot.FRONT, front).put(TextureSlot.TOP, top); + generateHorizontalBlock(block, plainVariant(ModelTemplates.CUBE_ORIENTABLE.create(block, mapping, modelOutput))); + } + + private static VariantMutator yRot(Direction direction, int angleOffset) { + return switch ((direction.get2DDataValue() + angleOffset / 90) % 4) { + case 0 -> NOP; + case 1 -> Y_ROT_90; + case 2 -> Y_ROT_180; + case 3 -> Y_ROT_270; + default -> throw new IllegalStateException(); + }; + } + + public static PropertyDispatch rotationHorizontalFacing(int angleOffset) { + return PropertyDispatch.modify(BlockStateProperties.HORIZONTAL_FACING) + .generate(direction -> yRot(direction, angleOffset)); + } + + public static PropertyDispatch rotationFacing(int angleOffsetY) { + return PropertyDispatch.modify(BlockStateProperties.FACING).generate(direction -> { + VariantMutator xRot = switch (direction) { + case DOWN -> X_ROT_180; + case UP -> NOP; + case NORTH, EAST, SOUTH, WEST -> X_ROT_90; + }; + VariantMutator yRot = direction.getAxis().isVertical() ? NOP : yRot(direction, angleOffsetY); + return xRot.then(yRot); + }); + } + + public static PropertyDispatch rotationAttachFaceAndHorizontalFacing(int angleOffsetY) { + return PropertyDispatch.modify(BlockStateProperties.ATTACH_FACE, BlockStateProperties.HORIZONTAL_FACING).generate((attachFace, direction) -> { + VariantMutator xRot = switch (attachFace) { + case FLOOR -> NOP; + case WALL -> X_ROT_90; + case CEILING -> X_ROT_180; + }; + VariantMutator yRot = yRot(direction, attachFace == AttachFace.CEILING ? angleOffsetY + 180 : angleOffsetY); + return xRot.then(yRot); + }); + } + + public void generateHorizontalBlock(Block block, MultiVariant model) { + blockStateOutput.accept(MultiVariantGenerator.dispatch(block, model).with(ROTATION_HORIZONTAL_FACING)); + } + + public void generateHorizontalBlock(Block block, MultiVariant multiVariant, int angleOffset) { + blockStateOutput.accept(MultiVariantGenerator.dispatch(block, multiVariant).with(rotationHorizontalFacing(angleOffset))); + } + + public void generateHorizontalFaceBlock(Block block, MultiVariant model) { + generateHorizontalFaceBlock(block, model, DEFAULT_ANGLE_OFFSET); + } + + public void generateHorizontalFaceBlock(Block block, MultiVariant variant, int angleOffset) { + blockStateOutput.accept(MultiVariantGenerator.dispatch(block, variant).with(rotationAttachFaceAndHorizontalFacing(angleOffset))); + } + + public void generateDirectionalBlock(Block block, MultiVariant model) { + generateDirectionalBlock(block, model, DEFAULT_ANGLE_OFFSET); + } + + public void generateDirectionalBlock(Block block, MultiVariant model, int angleOffsetY) { + blockStateOutput.accept(MultiVariantGenerator.dispatch(block, model).with(rotationFacing(angleOffsetY))); + } + + public void generateStairsBlock(StairBlock block, Material texture) { + generateStairsBlock(block, texture, texture, texture); + } + + public void generateStairsBlock(StairBlock block, String name, Material texture) { + generateStairsBlock(block, name, texture, texture, texture); + } + + public void generateStairsBlock(StairBlock block, Material side, Material bottom, Material top) { + TextureMapping textures = sideBottomTopTextures(side, bottom, top); + blockStateOutput.accept(createStairs(block, + plainVariant(ModelTemplates.STAIRS_INNER.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.STAIRS_STRAIGHT.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.STAIRS_OUTER.create(block, textures, modelOutput)))); + } + + public void generateStairsBlock(StairBlock block, String name, Material side, Material bottom, Material top) { + generateStairsBlockInternal(block, modLoc(name + "_stairs"), side, bottom, top, ModelTemplates.STAIRS_STRAIGHT, ModelTemplates.STAIRS_INNER, ModelTemplates.STAIRS_OUTER); + } + + private void generateStairsBlockInternal(StairBlock block, Identifier baseName, Material side, Material bottom, Material top, ModelTemplate straightTemplate, ModelTemplate innerTemplate, ModelTemplate outerTemplate) { + Identifier modelLocation = baseName.withPrefix("block/"); + TextureMapping textures = sideBottomTopTextures(side, bottom, top); + MultiVariant straightVariant = plainVariant(straightTemplate.create(modelLocation, textures, modelOutput)); + MultiVariant innerVariant = plainVariant(innerTemplate.create(modelLocation.withSuffix("_inner"), textures, modelOutput)); + MultiVariant outerVariant = plainVariant(outerTemplate.create(modelLocation.withSuffix("_outer"), textures, modelOutput)); + blockStateOutput.accept(createStairs(block, innerVariant, straightVariant, outerVariant)); + } + + public void generateStairsBlock(StairBlock block, MultiVariant stairs, MultiVariant stairsInner, MultiVariant stairsOuter) { + blockStateOutput.accept(createStairs(block, stairsInner, stairs, stairsOuter)); + } + + public void generateSlabBlock(SlabBlock block, MultiVariant doubleSlab, Material texture) { + generateSlabBlock(block, doubleSlab, texture, texture, texture); + } + + public void generateSlabBlock(SlabBlock block, MultiVariant doubleSlab, Material side, Material bottom, Material top) { + TextureMapping textures = sideBottomTopTextures(side, bottom, top); + MultiVariant slabTop = plainVariant(ModelTemplates.SLAB_TOP.create(block, textures, modelOutput)); + MultiVariant slabBottom = plainVariant(ModelTemplates.SLAB_BOTTOM.create(block, textures, modelOutput)); + generateSlabBlock(block, slabBottom, slabTop, doubleSlab); + } + + public void generateSlabBlock(SlabBlock block, MultiVariant bottom, MultiVariant top, MultiVariant doubleslab) { + blockStateOutput.accept(createSlab(block, bottom, top, doubleslab)); + } + + public void generateButtonBlock(ButtonBlock block, Material texture) { + TextureMapping textures = TextureMapping.defaultTexture(texture); + MultiVariant button = plainVariant(ModelTemplates.BUTTON.create(block, textures, modelOutput)); + MultiVariant buttonPressed = plainVariant(ModelTemplates.BUTTON_PRESSED.create(block, textures, modelOutput)); + generateButtonBlock(block, button, buttonPressed); + } + + public void generateButtonBlock(ButtonBlock block, MultiVariant button, MultiVariant buttonPressed) { + blockStateOutput.accept(createButton(block, button, buttonPressed)); + } + + public void generatePressurePlateBlock(PressurePlateBlock block, Material texture) { + TextureMapping textures = TextureMapping.defaultTexture(texture); + MultiVariant pressurePlate = plainVariant(ModelTemplates.PRESSURE_PLATE_UP.create(block, textures, modelOutput)); + MultiVariant pressurePlateDown = plainVariant(ModelTemplates.PRESSURE_PLATE_DOWN.create(block, textures, modelOutput)); + generatePressurePlateBlock(block, pressurePlate, pressurePlateDown); + } + + public void generatePressurePlateBlock(PressurePlateBlock block, MultiVariant pressurePlate, MultiVariant pressurePlateDown) { + blockStateOutput.accept(createPressurePlate(block, pressurePlate, pressurePlateDown)); + } + + public void generateSignBlock(StandingSignBlock signBlock, WallSignBlock wallSignBlock, Material texture) { + MultiVariant sign = plainVariant(ModelTemplates.PARTICLE_ONLY.create(signBlock, TextureMapping.particle(texture), modelOutput)); + generateSignBlock(signBlock, wallSignBlock, sign); + } + + public void generateSignBlock(StandingSignBlock signBlock, WallSignBlock wallSignBlock, MultiVariant sign) { + blockStateOutput.accept(createSimpleBlock(signBlock, sign)); + blockStateOutput.accept(createSimpleBlock(wallSignBlock, sign)); + } + + public void generateHangingSignBlock(CeilingHangingSignBlock hangingSignBlock, WallHangingSignBlock wallHangingSignBlock, Material texture) { + MultiVariant hangingSign = plainVariant(ModelTemplates.PARTICLE_ONLY.create(hangingSignBlock, TextureMapping.particle(texture), modelOutput)); + generateHangingSignBlock(hangingSignBlock, wallHangingSignBlock, hangingSign); + } + + public void generateHangingSignBlock(CeilingHangingSignBlock hangingSignBlock, WallHangingSignBlock wallHangingSignBlock, MultiVariant hangingSign) { + blockStateOutput.accept(createSimpleBlock(hangingSignBlock, hangingSign)); + blockStateOutput.accept(createSimpleBlock(wallHangingSignBlock, hangingSign)); + } + + public void generateFourWayBlock(CrossCollisionBlock block, MultiVariant post, MultiVariant side) { + MultiPartGenerator builder = MultiPartGenerator.multiPart(block).with(post); + generateFourWayMultipart(builder, side); + } + + public void generateFourWayMultipart(MultiPartGenerator builder, MultiVariant side) { + PipeBlock.PROPERTY_BY_DIRECTION.forEach((direction, property) -> { + if (direction.getAxis().isHorizontal()) { + VariantMutator yRot = switch (direction) { + case NORTH -> NOP; + case EAST -> Y_ROT_90; + case SOUTH -> Y_ROT_180; + case WEST -> Y_ROT_270; + default -> throw new IllegalStateException(); + }; + builder.with(condition().term(property, true), side.with(UV_LOCK.then(yRot))); + } + }); + blockStateOutput.accept(builder); + } + + public void generateFenceBlock(FenceBlock block, Material texture) { + generateFenceBlockInternal(block, texture, ModelTemplates.FENCE_POST, ModelTemplates.FENCE_SIDE); + } + + public void generateFenceBlock(FenceBlock block, String name, Material texture) { + generateFenceBlockInternal(block, name, texture, ModelTemplates.FENCE_POST, ModelTemplates.FENCE_SIDE); + } + + private void generateFenceBlockInternal(FenceBlock block, Material texture, ModelTemplate fencePostTemplate, ModelTemplate fenceSideTemplate) { + TextureMapping textures = TextureMapping.defaultTexture(texture); + generateFourWayBlock(block, + plainVariant(fencePostTemplate.create(block, textures, modelOutput)), + plainVariant(fenceSideTemplate.create(block, textures, modelOutput))); + } + + private void generateFenceBlockInternal(FenceBlock block, String name, Material texture, ModelTemplate fencePostTemplate, ModelTemplate fenceSideTemplate) { + TextureMapping textures = TextureMapping.defaultTexture(texture); + generateFourWayBlock(block, + plainVariant(fencePostTemplate.create(modLoc("block/" + name + "_fence_post"), textures, modelOutput)), + plainVariant(fenceSideTemplate.create(modLoc("block/" + name + "_fence_side"), textures, modelOutput))); + } + + public void generateFenceGateBlock(FenceGateBlock block, Material texture) { + TextureMapping textures = TextureMapping.defaultTexture(texture); + generateFenceGateBlock(block, + plainVariant(ModelTemplates.FENCE_GATE_CLOSED.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.FENCE_GATE_OPEN.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.FENCE_GATE_WALL_CLOSED.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.FENCE_GATE_WALL_OPEN.create(block, textures, modelOutput))); + } + + public void generateFenceGateBlock(FenceGateBlock block, String name, Material texture) { + generateFenceGateBlockInternal(block, modLoc(name + "_fence_gate"), texture, ModelTemplates.FENCE_GATE_CLOSED, ModelTemplates.FENCE_GATE_OPEN, ModelTemplates.FENCE_GATE_WALL_CLOSED, ModelTemplates.FENCE_GATE_WALL_OPEN); + } + + private void generateFenceGateBlockInternal(FenceGateBlock block, Identifier baseName, Material texture, ModelTemplate closedTemplate, ModelTemplate openTemplate, ModelTemplate wallClosedTemplate, ModelTemplate wallOpenTemplate) { + Identifier baseModel = baseName.withPrefix("block/"); + TextureMapping textures = TextureMapping.defaultTexture(texture); + MultiVariant gate = plainVariant(closedTemplate.create(baseModel, textures, modelOutput)); + MultiVariant gateOpen = plainVariant(openTemplate.create(baseModel.withSuffix("_open"), textures, modelOutput)); + MultiVariant gateWall = plainVariant(wallClosedTemplate.create(baseModel.withSuffix("_wall"), textures, modelOutput)); + MultiVariant gateWallOpen = plainVariant(wallOpenTemplate.create(baseModel.withSuffix("_wall_open"), textures, modelOutput)); + generateFenceGateBlock(block, gate, gateOpen, gateWall, gateWallOpen); + } + + public void generateFenceGateBlock(FenceGateBlock block, MultiVariant gate, MultiVariant gateOpen, MultiVariant gateWall, MultiVariant gateWallOpen) { + blockStateOutput.accept(createFenceGate(block, gateOpen, gate, gateWallOpen, gateWall, true)); + } + + public void generateWallBlock(WallBlock block, Material texture) { + TextureMapping textures = TextureMapping.singleSlot(TextureSlot.WALL, texture); + blockStateOutput.accept(createWall(block, + plainVariant(ModelTemplates.WALL_POST.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.WALL_LOW_SIDE.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.WALL_TALL_SIDE.create(block, textures, modelOutput)))); + } + + public void generateWallBlock(WallBlock block, String name, Material texture) { + Identifier baseName = modLoc(name + "_wall"); + generateWallBlockInternal(block, baseName, texture, ModelTemplates.WALL_POST, ModelTemplates.WALL_LOW_SIDE, ModelTemplates.WALL_TALL_SIDE); + } + + private void generateWallBlockInternal(WallBlock block, Identifier baseName, Material texture, ModelTemplate postTemplate, ModelTemplate sideTemplate, ModelTemplate tallSideTemplate) { + TextureMapping textures = TextureMapping.singleSlot(TextureSlot.WALL, texture); + Identifier baseModel = baseName.withPrefix("block/"); + generateWallBlock(block, + plainVariant(postTemplate.create(baseModel.withSuffix("_post"), textures, modelOutput)), + plainVariant(sideTemplate.create(baseModel.withSuffix("_side"), textures, modelOutput)), + plainVariant(tallSideTemplate.create(baseModel.withSuffix("_side_tall"), textures, modelOutput))); + } + + public void generateWallBlock(WallBlock block, MultiVariant post, MultiVariant side, MultiVariant sideTall) { + blockStateOutput.accept(createWall(block, post, side, sideTall)); + } + + public void generatePaneBlock(IronBarsBlock block, Material pane, Material edge) { + TextureMapping textures = new TextureMapping().put(TextureSlot.PANE, pane).put(TextureSlot.EDGE, edge); + generatePaneBlock(block, + plainVariant(ModelTemplates.STAINED_GLASS_PANE_POST.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.STAINED_GLASS_PANE_SIDE.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.STAINED_GLASS_PANE_SIDE_ALT.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.STAINED_GLASS_PANE_NOSIDE.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.STAINED_GLASS_PANE_NOSIDE_ALT.create(block, textures, modelOutput))); + } + + public void generatePaneBlock(IronBarsBlock block, String name, Material pane, Material edge) { + Identifier baseName = modLoc(name + "_pane"); + generatePaneBlockInternal(block, baseName, pane, edge, ModelTemplates.STAINED_GLASS_PANE_POST, ModelTemplates.STAINED_GLASS_PANE_SIDE, ModelTemplates.STAINED_GLASS_PANE_SIDE_ALT, ModelTemplates.STAINED_GLASS_PANE_NOSIDE, ModelTemplates.STAINED_GLASS_PANE_NOSIDE_ALT); + } + + private void generatePaneBlockInternal(IronBarsBlock block, Identifier baseName, Material pane, Material edge, ModelTemplate postTemplate, ModelTemplate sideTemplate, ModelTemplate sideAltTemplate, ModelTemplate noSideTemplate, ModelTemplate noSideAltTemplate) { + Identifier baseModel = baseName.withPrefix("block/"); + TextureMapping textures = new TextureMapping().put(TextureSlot.PANE, pane).put(TextureSlot.EDGE, edge); + generatePaneBlock(block, + plainVariant(postTemplate.create(baseModel.withSuffix("_post"), textures, modelOutput)), + plainVariant(sideTemplate.create(baseModel.withSuffix("_side"), textures, modelOutput)), + plainVariant(sideAltTemplate.create(baseModel.withSuffix("_side_alt"), textures, modelOutput)), + plainVariant(noSideTemplate.create(baseModel.withSuffix("_noside"), textures, modelOutput)), + plainVariant(noSideAltTemplate.create(baseModel.withSuffix("_noside_alt"), textures, modelOutput))); + } + + public void generatePaneBlock(IronBarsBlock block, MultiVariant post, MultiVariant side, MultiVariant sideAlt, MultiVariant noSide, MultiVariant noSideAlt) { + blockStateOutput.accept(MultiPartGenerator.multiPart(block) + .with(post) + .with(condition().term(BlockStateProperties.NORTH, true), side) + .with(condition().term(BlockStateProperties.EAST, true), side.with(Y_ROT_90)) + .with(condition().term(BlockStateProperties.SOUTH, true), sideAlt) + .with(condition().term(BlockStateProperties.WEST, true), sideAlt.with(Y_ROT_90)) + .with(condition().term(BlockStateProperties.NORTH, false), noSide) + .with(condition().term(BlockStateProperties.EAST, false), noSideAlt) + .with(condition().term(BlockStateProperties.SOUTH, false), noSideAlt.with(Y_ROT_90)) + .with(condition().term(BlockStateProperties.WEST, false), noSide.with(Y_ROT_270))); + } + + public void generateDoorBlock(DoorBlock block, Material bottom, Material top) { + TextureMapping textures = TextureMapping.door(top, bottom); + generateDoorBlock(block, + plainVariant(ModelTemplates.DOOR_BOTTOM_LEFT.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.DOOR_BOTTOM_LEFT_OPEN.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.DOOR_BOTTOM_RIGHT.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.DOOR_BOTTOM_RIGHT_OPEN.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.DOOR_TOP_LEFT.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.DOOR_TOP_LEFT_OPEN.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.DOOR_TOP_RIGHT.create(block, textures, modelOutput)), + plainVariant(ModelTemplates.DOOR_TOP_RIGHT_OPEN.create(block, textures, modelOutput))); + } + + public void generateDoorBlock(DoorBlock block, String name, Material bottom, Material top) { + generateDoorBlockInternal(block, modLoc(name + "_door"), bottom, top); + } + + private void generateDoorBlockInternal(DoorBlock block, Identifier baseName, Material bottom, Material top) { + generateDoorBlockInternal(block, baseName, bottom, top, ModelTemplates.DOOR_BOTTOM_LEFT, ModelTemplates.DOOR_BOTTOM_LEFT_OPEN, ModelTemplates.DOOR_BOTTOM_RIGHT, ModelTemplates.DOOR_BOTTOM_RIGHT_OPEN, ModelTemplates.DOOR_TOP_LEFT, ModelTemplates.DOOR_TOP_LEFT_OPEN, ModelTemplates.DOOR_TOP_RIGHT, ModelTemplates.DOOR_TOP_RIGHT_OPEN); + } + + private void generateDoorBlockInternal(DoorBlock block, Identifier baseName, Material bottom, Material top, ModelTemplate bottomLeftTemplate, ModelTemplate bottomLeftOpenTemplate, ModelTemplate bottomRightTemplate, ModelTemplate bottomRightOpenTemplate, ModelTemplate topLeftTemplate, ModelTemplate topLeftOpenTemplate, ModelTemplate topRightTemplate, ModelTemplate topRightOpenTemplate) { + Identifier baseModel = baseName.withPrefix("block/"); + TextureMapping textures = TextureMapping.door(top, bottom); + MultiVariant bottomLeft = plainVariant(bottomLeftTemplate.create(baseModel.withSuffix("_bottom_left"), textures, modelOutput)); + MultiVariant bottomLeftOpen = plainVariant(bottomLeftOpenTemplate.create(baseModel.withSuffix("_bottom_left_open"), textures, modelOutput)); + MultiVariant bottomRight = plainVariant(bottomRightTemplate.create(baseModel.withSuffix("_bottom_right"), textures, modelOutput)); + MultiVariant bottomRightOpen = plainVariant(bottomRightOpenTemplate.create(baseModel.withSuffix("_bottom_right_open"), textures, modelOutput)); + MultiVariant topLeft = plainVariant(topLeftTemplate.create(baseModel.withSuffix("_top_left"), textures, modelOutput)); + MultiVariant topLeftOpen = plainVariant(topLeftOpenTemplate.create(baseModel.withSuffix("_top_left_open"), textures, modelOutput)); + MultiVariant topRight = plainVariant(topRightTemplate.create(baseModel.withSuffix("_top_right"), textures, modelOutput)); + MultiVariant topRightOpen = plainVariant(topRightOpenTemplate.create(baseModel.withSuffix("_top_right_open"), textures, modelOutput)); + generateDoorBlock(block, bottomLeft, bottomLeftOpen, bottomRight, bottomRightOpen, topLeft, topLeftOpen, topRight, topRightOpen); + } + + public void generateDoorBlock(DoorBlock block, MultiVariant bottomLeft, MultiVariant bottomLeftOpen, MultiVariant bottomRight, MultiVariant bottomRightOpen, MultiVariant topLeft, MultiVariant topLeftOpen, MultiVariant topRight, MultiVariant topRightOpen) { + blockStateOutput.accept(createDoor(block, bottomLeft, bottomLeftOpen, bottomRight, bottomRightOpen, topLeft, topLeftOpen, topRight, topRightOpen)); + } + + public void generateTrapdoorBlock(TrapDoorBlock block, Material texture, boolean orientable) { + TextureMapping textures = TextureMapping.defaultTexture(texture); + generateTrapdoorBlock(block, + plainVariant((orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_BOTTOM : ModelTemplates.TRAPDOOR_BOTTOM).create(block, textures, modelOutput)), + plainVariant((orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_TOP : ModelTemplates.TRAPDOOR_TOP).create(block, textures, modelOutput)), + plainVariant((orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_OPEN : ModelTemplates.TRAPDOOR_OPEN).create(block, textures, modelOutput)), + orientable); + } + + public void generateTrapdoorBlock(TrapDoorBlock block, String name, Material texture, boolean orientable) { + generateTrapdoorBlockInternal(block, modLoc(name + "_trapdoor"), texture, orientable); + } + + private void generateTrapdoorBlockInternal(TrapDoorBlock block, Identifier baseName, Material texture, boolean orientable) { + generateTrapdoorBlockInternal(block, baseName, texture, orientable, + orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_BOTTOM : ModelTemplates.TRAPDOOR_BOTTOM, + orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_TOP : ModelTemplates.TRAPDOOR_TOP, + orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_OPEN : ModelTemplates.TRAPDOOR_OPEN); + } + + private void generateTrapdoorBlockInternal(TrapDoorBlock block, Identifier baseName, Material texture, boolean orientable, ModelTemplate bottomTemplate, ModelTemplate topTemplate, ModelTemplate openTemplate) { + Identifier baseModel = baseName.withPrefix("block/"); + TextureMapping textures = TextureMapping.defaultTexture(texture); + MultiVariant bottom = plainVariant(bottomTemplate.create(baseModel.withSuffix("_bottom"), textures, modelOutput)); + MultiVariant top = plainVariant(topTemplate.create(baseModel.withSuffix("_top"), textures, modelOutput)); + MultiVariant open = plainVariant(openTemplate.create(baseModel.withSuffix("_open"), textures, modelOutput)); + generateTrapdoorBlock(block, bottom, top, open, orientable); + } + + public void generateTrapdoorBlock(TrapDoorBlock block, MultiVariant bottom, MultiVariant top, MultiVariant open, boolean orientable) { + blockStateOutput.accept(orientable ? createOrientableTrapdoor(block, top, bottom, open) : createTrapdoor(block, top, bottom, open)); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java new file mode 100644 index 0000000..56eaa19 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java @@ -0,0 +1,128 @@ +package com.modularmc.registrate.providers.generators; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.client.color.item.ItemTintSource; +import net.minecraft.client.data.models.ItemModelGenerators; +import net.minecraft.client.data.models.ItemModelOutput; +import net.minecraft.client.data.models.model.ItemModelUtils; +import net.minecraft.client.data.models.model.ModelInstance; +import net.minecraft.client.data.models.model.ModelLocationUtils; +import net.minecraft.client.data.models.model.ModelTemplate; +import net.minecraft.client.data.models.model.ModelTemplates; +import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.material.Fluid; +import net.neoforged.neoforge.client.model.item.DynamicFluidContainerModel; + +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.UnaryOperator; + +public class RegistrateItemModelGenerator extends ItemModelGenerators { + + private final AbstractRegistrate parent; + + public RegistrateItemModelGenerator(AbstractRegistrate parent, ItemModelOutput output, BiConsumer model) { + super(output, model); + this.parent = parent; + } + + @Override + public void run() { + parent.genData(ProviderType.ITEM_MODEL, this); + } + + public void createWithExistingModel(Item item, Identifier id) { + itemModelOutput.accept(item, ItemModelUtils.plainModel(id)); + } + + public void generateWithTemplate(Item item, ModelTemplate template, TextureMapping textures) { + itemModelOutput.accept(item, ItemModelUtils.plainModel(template.create(item, textures, modelOutput))); + } + + public void generateFlatItem(Item item, Material layer0) { + generateFlatItem(item, ModelTemplates.FLAT_ITEM, layer0); + } + + public void generateFlatItem(Item item, ModelTemplate template, Material layer0) { + itemModelOutput.accept(item, ItemModelUtils.plainModel(template.create(item, TextureMapping.layer0(layer0), modelOutput))); + } + + public void generateFlatItem(Item item, ModelTemplate template, TextureMapping textures, ItemTintSource... tints) { + Identifier model = template.create(item, textures, modelOutput); + itemModelOutput.accept(item, tints.length == 0 ? ItemModelUtils.plainModel(model) : ItemModelUtils.tintedModel(model, tints)); + } + + public void generateFlatBlockItem(BlockItem item) { + generateFlatItem(item, TextureMapping.getBlockTexture(item.getBlock())); + } + + public void generateFlatBlockItem(BlockItem item, String suffix) { + generateFlatItem(item, TextureMapping.getBlockTexture(item.getBlock(), suffix)); + } + + public void generateBlockItem(BlockItem item, UnaryOperator modelMapper) { + itemModelOutput.accept(item, ItemModelUtils.plainModel(modelMapper.apply(ModelLocationUtils.getModelLocation(item.getBlock())))); + } + + public void generateBlockItem(BlockItem item, String suffix) { + generateBlockItem(item, model -> model.withSuffix(suffix)); + } + + public Identifier mcLoc(String id) { + return Identifier.withDefaultNamespace(id); + } + + public Identifier modLoc(String id) { + return Identifier.fromNamespaceAndPath(parent.getModid(), id); + } + + public Material mcBlockTexture(String path) { + return new Material(mcLoc("block/" + path)); + } + + public Material modBlockTexture(String path) { + return new Material(modLoc("block/" + path)); + } + + public Material mcItemTexture(String path) { + return new Material(mcLoc("item/" + path)); + } + + public Material modItemTexture(String path) { + return new Material(modLoc("item/" + path)); + } + + public String modid(NonNullSupplier item) { + return BuiltInRegistries.ITEM.getKey(item.get().asItem()).getNamespace(); + } + + public String name(NonNullSupplier item) { + return BuiltInRegistries.ITEM.getKey(item.get().asItem()).getPath(); + } + + public void generateTintedModel(Item entry, Identifier model, ItemTintSource tint) { + this.itemModelOutput.accept(entry, ItemModelUtils.tintedModel(model, tint)); + } + + public void generateFluidBucket(Item item, Fluid fluid) { + itemModelOutput.accept(item, new DynamicFluidContainerModel.Unbaked( + new DynamicFluidContainerModel.Textures( + Optional.of(mcItemTexture("bucket")), + Optional.of(mcItemTexture("bucket")), + Optional.of(new Material(Identifier.fromNamespaceAndPath("neoforge", "item/mask/bucket_fluid"))), + Optional.empty()), + fluid, + true, + true, + true)); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java new file mode 100644 index 0000000..8e85469 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java @@ -0,0 +1,126 @@ +package com.modularmc.registrate.providers.generators; + +import net.minecraft.client.data.models.model.ModelInstance; +import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.client.data.models.model.TextureSlot; +import net.minecraft.client.resources.model.UnbakedModel; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.level.block.Block; +import net.neoforged.neoforge.client.model.generators.template.CustomLoaderBuilder; +import net.neoforged.neoforge.client.model.generators.template.ExtendedModelTemplateBuilder; +import net.neoforged.neoforge.client.model.generators.template.RootTransformsBuilder; +import net.neoforged.neoforge.client.model.generators.template.TransformVecBuilder; + +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class RegistrateLegacyBlockModelBuilder { + + private final ExtendedModelTemplateBuilder template; + private final TextureMapping texture; + private final BiConsumer output; + + RegistrateLegacyBlockModelBuilder(BiConsumer output, ExtendedModelTemplateBuilder template, TextureMapping texture) { + this.output = output; + this.template = template; + this.texture = texture.copy(); + } + + public RegistrateLegacyBlockModelBuilder texture(TextureSlot slot, Material texture) { + this.template.requiredTextureSlot(slot); + this.texture.put(slot, texture); + return this; + } + + public RegistrateLegacyBlockModelBuilder transformTemplate(Consumer action) { + action.accept(template); + return this; + } + + public RegistrateLegacyBlockModelBuilder transformTexture(Consumer action) { + action.accept(texture); + return this; + } + + public Identifier build(Block block) { + return template.build().create(block, texture, output); + } + + public Identifier build(Identifier loc) { + return template.build().create(loc, texture, output); + } + + // Delegated methods from Template Builder + + /** + * Parent model which this template will inherit its properties from. + */ + public RegistrateLegacyBlockModelBuilder parent(Identifier parent) { + template.parent(parent); + return this; + } + + /** + * Suffix appended onto the models file path. + */ + public RegistrateLegacyBlockModelBuilder suffix(String suffix) { + template.suffix(suffix); + return this; + } + + /** + * Begin building a new transform for the given perspective. + * + * @param type the perspective to create or return the builder for + * @return the builder for the given perspective + * @throws NullPointerException if {@code type} is {@code null} + */ + public RegistrateLegacyBlockModelBuilder transform(ItemDisplayContext type, Consumer action) { + template.transform(type, action); + return this; + } + + /** + * Sets whether or not this model should apply ambient occlusion. + */ + public RegistrateLegacyBlockModelBuilder ambientOcclusion(boolean ambientOcclusion) { + template.ambientOcclusion(ambientOcclusion); + return this; + } + + /** + * Sets the gui light style for this model. + * + *

    + *
  • {@link UnbakedModel.GuiLight#FRONT} for head on light, commonly used for items.
  • + *
  • {@link UnbakedModel.GuiLight#SIDE} for the model to be side lit, commonly used for blocks.
  • + *
+ */ + public RegistrateLegacyBlockModelBuilder guiLight(UnbakedModel.GuiLight light) { + template.guiLight(light); + return this; + } + + /** + * Use a custom loader instead of the vanilla elements. + * + * @param customLoaderFactory function that returns the custom loader to set, given this + * @return the custom loader builder + */ + public RegistrateLegacyBlockModelBuilder customLoader(Supplier customLoaderFactory, Consumer action) { + template.customLoader(customLoaderFactory, action); + return this; + } + + /** + * Modifies the transformation applied right before item display transformations and rotations specified in block + * states. + */ + public RegistrateLegacyBlockModelBuilder rootTransforms(Consumer action) { + template.rootTransforms(action); + return this; + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java new file mode 100644 index 0000000..4b19029 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java @@ -0,0 +1,44 @@ +package com.modularmc.registrate.providers.generators; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.RegistrateProvider; + +import net.minecraft.client.data.models.BlockModelGenerators; +import net.minecraft.client.data.models.ItemModelGenerators; +import net.minecraft.client.data.models.ModelProvider; +import net.minecraft.client.renderer.block.dispatch.BlockStateModelDispatcher; +import net.minecraft.data.PackOutput; +import net.neoforged.fml.LogicalSide; + +import com.mojang.serialization.JsonOps; + +public class RegistrateModelProvider extends ModelProvider implements RegistrateProvider { + + private final AbstractRegistrate parent; + + public RegistrateModelProvider(AbstractRegistrate parent, PackOutput p_388260_) { + super(p_388260_, parent.getModid()); + this.parent = parent; + } + + @Override + protected void registerModels(BlockModelGenerators blockModels, ItemModelGenerators itemModels) { + var registrateBlockModels = new RegistrateBlockModelGenerator(parent, blockModels.blockStateOutput, blockModels.itemModelOutput, blockModels.modelOutput); + registrateBlockModels.run(); + registrateBlockModels.seenBlockstates.forEach((block, dispatcher) -> validateBlockStateEncoding(block, dispatcher)); + new RegistrateItemModelGenerator(parent, itemModels.itemModelOutput, itemModels.modelOutput).run(); + } + + private static void validateBlockStateEncoding(net.minecraft.world.level.block.Block block, BlockStateModelDispatcher dispatcher) { + try { + BlockStateModelDispatcher.CODEC.encodeStart(JsonOps.INSTANCE, dispatcher); + } catch (RuntimeException ex) { + throw new IllegalStateException("Failed to encode blockstate definition for " + block.builtInRegistryHolder().key().identifier(), ex); + } + } + + @Override + public LogicalSide getSide() { + return LogicalSide.CLIENT; + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java new file mode 100644 index 0000000..6dcada7 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java @@ -0,0 +1,714 @@ +package com.modularmc.registrate.providers.generators; + +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.util.DataIngredient; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.advancements.Criterion; +import net.minecraft.advancements.criterion.EnterBlockTrigger; +import net.minecraft.advancements.criterion.InventoryChangeTrigger; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.advancements.criterion.MinMaxBounds; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.BlockFamily; +import net.minecraft.data.recipes.*; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStackTemplate; +import net.minecraft.world.item.crafting.*; +import net.minecraft.world.item.equipment.trim.TrimPattern; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.SuspiciousEffectHolder; +import net.neoforged.neoforge.common.Tags; + +import lombok.experimental.Delegate; +import org.jspecify.annotations.Nullable; + +import java.util.List; +import java.util.function.Supplier; + +import javax.annotation.CheckReturnValue; +import javax.annotation.processing.Generated; + +public class RegistrateRecipeProvider extends RecipeProvider implements RecipeOutput { + + private final RegistrateRecipeRunner runner; + + @Delegate + private final RecipeOutput outputDelegated; + + private final HolderLookup itemLookup; + private final HolderLookup blockLookup; + private final HolderLookup> entityLookup; + + public RegistrateRecipeProvider(RegistrateRecipeRunner runner, HolderLookup.Provider registries, RecipeOutput output) { + super(registries, output); + this.runner = runner; + this.outputDelegated = output; + itemLookup = registries.lookupOrThrow(Registries.ITEM); + blockLookup = registries.lookupOrThrow(Registries.BLOCK); + entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE); + } + + @Override + public void buildRecipes() { + runner.provider = this; + runner.owner.genData(ProviderType.RECIPE, this); + runner.provider = null; + } + + public HolderLookup.Provider registries() { + return registries; + } + + public HolderLookup itemLookup() { + return itemLookup; + } + + public HolderLookup blockLookup() { + return blockLookup; + } + + public HolderLookup> entityLookup() { + return entityLookup; + } + + public Holder resolve(ResourceKey key) { + return registries.lookupOrThrow(key.registryKey()).getOrThrow(key); + } + + public Identifier safeId(Identifier id) { + return Identifier.fromNamespaceAndPath(runner.owner.getModid(), safeName(id)); + } + + public Identifier safeId(DataIngredient source) { + return safeId(source.getId()); + } + + public Identifier safeId(ItemLike registryEntry) { + return safeId(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); + } + + public ResourceKey> safeKey(Identifier id) { + return ResourceKey.create(Registries.RECIPE, Identifier.fromNamespaceAndPath(runner.owner.getModid(), safeName(id))); + } + + public ResourceKey> safeKey(DataIngredient source) { + return safeKey(source.getId()); + } + + public ResourceKey> safeKey(ItemLike registryEntry) { + return safeKey(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); + } + + public String safeName(Identifier id) { + return id.getPath().replace('/', '_'); + } + + public String safeName(DataIngredient source) { + return safeName(source.getId()); + } + + public String safeName(ItemLike registryEntry) { + return safeName(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); + } + + public static final int DEFAULT_SMELT_TIME = 200; + public static final int DEFAULT_BLAST_TIME = DEFAULT_SMELT_TIME / 2; + public static final int DEFAULT_SMOKE_TIME = DEFAULT_BLAST_TIME; + public static final int DEFAULT_CAMPFIRE_TIME = DEFAULT_SMELT_TIME * 3; + + public void cooking(DataIngredient source, RecipeCategory craftingCategory, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime, String typeName, AbstractCookingRecipe.Factory factory) { + SimpleCookingRecipeBuilder.generic(source.toVanilla(), craftingCategory, cookingCategory, result.get(), experience, cookingTime, factory) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get()) + "_from_" + safeName(source) + "_" + typeName); + } + + public void smelting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { + smelting(source, category, cookingCategory, result, experience, DEFAULT_SMELT_TIME); + } + + public void smelting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { + cooking(source, category, cookingCategory, result, experience, cookingTime, "smelting", SmeltingRecipe::new); + } + + public void blasting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { + blasting(source, category, cookingCategory, result, experience, DEFAULT_BLAST_TIME); + } + + public void blasting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { + cooking(source, category, cookingCategory, result, experience, cookingTime, "blasting", BlastingRecipe::new); + } + + public void smoking(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { + smoking(source, category, cookingCategory, result, experience, DEFAULT_SMOKE_TIME); + } + + public void smoking(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { + cooking(source, category, cookingCategory, result, experience, cookingTime, "smoking", SmokingRecipe::new); + } + + public void campfire(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { + campfire(source, category, cookingCategory, result, experience, DEFAULT_CAMPFIRE_TIME); + } + + public void campfire(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { + cooking(source, category, cookingCategory, result, experience, cookingTime, "campfire", CampfireCookingRecipe::new); + } + + public void stonecutting(DataIngredient source, RecipeCategory category, Supplier result) { + stonecutting(source, category, result, 1); + } + + public void stonecutting(DataIngredient source, RecipeCategory category, Supplier result, int resultAmount) { + SingleItemRecipeBuilder.stonecutting(source.toVanilla(), category, result.get(), resultAmount) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get()) + "_from_" + safeName(source) + "_stonecutting"); + } + + public void smeltingAndBlasting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float xp) { + smelting(source, category, cookingCategory, result, xp); + blasting(source, category, cookingCategory, result, xp); + } + + public void food(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float xp) { + smelting(source, category, cookingCategory, result, xp); + smoking(source, category, cookingCategory, result, xp); + campfire(source, category, cookingCategory, result, xp); + } + + public void square(DataIngredient source, RecipeCategory category, Supplier output, boolean small) { + ShapedRecipeBuilder builder = shaped(category, output.get()) + .define('X', source.toVanilla()); + if (small) { + builder.pattern("XX").pattern("XX"); + } else { + builder.pattern("XXX").pattern("XXX").pattern("XXX"); + } + builder.unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(output.get())); + } + + /** + * @param + * @param source + * @param output + * @deprecated Broken, use {@link #storage(NonNullSupplier, RecipeCategory, NonNullSupplier)} or + * {@link #storage(DataIngredient, RecipeCategory, NonNullSupplier, DataIngredient, NonNullSupplier)}. + */ + @Deprecated + public void storage(DataIngredient source, RecipeCategory category, NonNullSupplier output) { + square(source, category, output, false); + // This is backwards, but leaving in for binary compat + singleItemUnfinished(source, category, output, 1, 9) + .save(this, safeId(source) + "_from_" + safeName(output.get())); + } + + public void storage(NonNullSupplier source, RecipeCategory category, NonNullSupplier output) { + storage(DataIngredient.items(source), category, source, DataIngredient.items(output), output); + } + + public void storage(DataIngredient sourceIngredient, RecipeCategory category, NonNullSupplier source, DataIngredient outputIngredient, NonNullSupplier output) { + square(sourceIngredient, category, output, false); + singleItemUnfinished(outputIngredient, category, source, 1, 9) + .save(this, safeId(sourceIngredient) + "_from_" + safeName(output.get())); + } + + @CheckReturnValue + public ShapelessRecipeBuilder singleItemUnfinished(DataIngredient source, RecipeCategory category, Supplier result, int required, int amount) { + return shapeless(category, result.get(), amount) + .requires(source.toVanilla(), required) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)); + } + + public void singleItem(DataIngredient source, RecipeCategory category, Supplier result, int required, int amount) { + singleItemUnfinished(source, category, result, required, amount).save(this, safeKey(result.get())); + } + + public void planks(DataIngredient source, RecipeCategory category, Supplier result) { + singleItemUnfinished(source, category, result, 1, 4) + .group("planks") + .save(this, safeKey(result.get())); + } + + public void stairs(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group, boolean stone) { + shaped(category, result.get(), 4) + .pattern("X ").pattern("XX ").pattern("XXX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(result.get())); + if (stone) { + stonecutting(source, category, result); + } + } + + public void slab(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group, boolean stone) { + shaped(category, result.get(), 6) + .pattern("XXX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(result.get())); + if (stone) { + stonecutting(source, category, result, 2); + } + } + + public void fence(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { + shaped(category, result.get(), 3) + .pattern("W#W").pattern("W#W") + .define('W', source.toVanilla()) + .define('#', Tags.Items.RODS_WOODEN) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(result.get())); + } + + public void fenceGate(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { + shaped(category, result.get()) + .pattern("#W#").pattern("#W#") + .define('W', source.toVanilla()) + .define('#', Tags.Items.RODS_WOODEN) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(result.get())); + } + + public void wall(DataIngredient source, RecipeCategory category, Supplier result) { + shaped(category, result.get(), 6) + .pattern("XXX").pattern("XXX") + .define('X', source.toVanilla()) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(result.get())); + stonecutting(source, category, result); + } + + public void door(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { + shaped(category, result.get(), 3) + .pattern("XX").pattern("XX").pattern("XX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(result.get())); + } + + public void trapDoor(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { + shaped(category, result.get(), 2) + .pattern("XXX").pattern("XXX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeKey(result.get())); + } + + // @formatter:off + // GENERATED START - DO NOT EDIT BELOW THIS LINE + + /** Generated override to expose protected method: {@link RecipeProvider#generateForEnabledBlockFamilies} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void generateForEnabledBlockFamilies(FeatureFlagSet flagSet) { super.generateForEnabledBlockFamilies(flagSet); } + + /** Generated override to expose protected method: {@link RecipeProvider#netheriteSmithing} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void netheriteSmithing(Item base, RecipeCategory category, Item result) { super.netheriteSmithing(base, category, result); } + + /** Generated override to expose protected method: {@link RecipeProvider#trimSmithing} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void trimSmithing(Item trimTemplate, ResourceKey patternId, ResourceKey> id) { super.trimSmithing(trimTemplate, patternId, id); } + + /** Generated override to expose protected method: {@link RecipeProvider#twoByTwoPacker} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void twoByTwoPacker(RecipeCategory category, ItemLike result, ItemLike ingredient) { super.twoByTwoPacker(category, result, ingredient); } + + /** Generated override to expose protected method: {@link RecipeProvider#threeByThreePacker} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void threeByThreePacker(RecipeCategory category, ItemLike result, ItemLike ingredient, String unlockedBy) { super.threeByThreePacker(category, result, ingredient, unlockedBy); } + + /** Generated override to expose protected method: {@link RecipeProvider#threeByThreePacker} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void threeByThreePacker(RecipeCategory category, ItemLike result, ItemLike ingredient) { super.threeByThreePacker(category, result, ingredient); } + + /** Generated override to expose protected method: {@link RecipeProvider#planksFromLog} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void planksFromLog(ItemLike result, TagKey logs, int count) { super.planksFromLog(result, logs, count); } + + /** Generated override to expose protected method: {@link RecipeProvider#planksFromLogs} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void planksFromLogs(ItemLike result, TagKey logs, int count) { super.planksFromLogs(result, logs, count); } + + /** Generated override to expose protected method: {@link RecipeProvider#woodFromLogs} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void woodFromLogs(ItemLike result, ItemLike log) { super.woodFromLogs(result, log); } + + /** Generated override to expose protected method: {@link RecipeProvider#woodenBoat} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void woodenBoat(ItemLike result, ItemLike planks) { super.woodenBoat(result, planks); } + + /** Generated override to expose protected method: {@link RecipeProvider#chestBoat} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void chestBoat(ItemLike chestBoat, ItemLike boat) { super.chestBoat(chestBoat, boat); } + + /** Generated override to expose protected method: {@link RecipeProvider#buttonBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder buttonBuilder(ItemLike result, Ingredient base) { return super.buttonBuilder(result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#doorBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder doorBuilder(ItemLike result, Ingredient base) { return super.doorBuilder(result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#fenceBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder fenceBuilder(ItemLike result, Ingredient base) { return super.fenceBuilder(result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#fenceGateBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder fenceGateBuilder(ItemLike result, Ingredient planks) { return super.fenceGateBuilder(result, planks); } + + /** Generated override to expose protected method: {@link RecipeProvider#pressurePlate} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void pressurePlate(ItemLike result, ItemLike base) { super.pressurePlate(result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#pressurePlateBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder pressurePlateBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.pressurePlateBuilder(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#slab} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void slab(RecipeCategory category, ItemLike result, ItemLike base) { super.slab(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#shelf} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void shelf(ItemLike result, ItemLike strippedLogs) { super.shelf(result, strippedLogs); } + + /** Generated override to expose protected method: {@link RecipeProvider#slabBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder slabBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.slabBuilder(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#stairBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder stairBuilder(ItemLike result, Ingredient base) { return super.stairBuilder(result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#trapdoorBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder trapdoorBuilder(ItemLike result, Ingredient base) { return super.trapdoorBuilder(result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#signBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder signBuilder(ItemLike result, Ingredient planks) { return super.signBuilder(result, planks); } + + /** Generated override to expose protected method: {@link RecipeProvider#hangingSign} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void hangingSign(ItemLike result, ItemLike ingredient) { super.hangingSign(result, ingredient); } + + /** Generated override to expose protected method: {@link RecipeProvider#colorItemWithDye} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void colorItemWithDye(List dyes, List items, String groupName, RecipeCategory category) { super.colorItemWithDye(dyes, items, groupName, category); } + + /** Generated override to expose protected method: {@link RecipeProvider#carpet} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void carpet(ItemLike result, ItemLike sourceItem) { super.carpet(result, sourceItem); } + + /** Generated override to expose protected method: {@link RecipeProvider#bedFromPlanksAndWool} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void bedFromPlanksAndWool(ItemLike result, ItemLike wool) { super.bedFromPlanksAndWool(result, wool); } + + /** Generated override to expose protected method: {@link RecipeProvider#banner} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void banner(ItemLike result, ItemLike wool) { super.banner(result, wool); } + + /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassFromGlassAndDye} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void stainedGlassFromGlassAndDye(ItemLike result, ItemLike dye) { super.stainedGlassFromGlassAndDye(result, dye); } + + /** Generated override to expose protected method: {@link RecipeProvider#dryGhast} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void dryGhast(ItemLike result) { super.dryGhast(result); } + + /** Generated override to expose protected method: {@link RecipeProvider#harness} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void harness(ItemLike result, ItemLike wool) { super.harness(result, wool); } + + /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassPaneFromStainedGlass} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void stainedGlassPaneFromStainedGlass(ItemLike result, ItemLike stainedGlass) { super.stainedGlassPaneFromStainedGlass(result, stainedGlass); } + + /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassPaneFromGlassPaneAndDye} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void stainedGlassPaneFromGlassPaneAndDye(ItemLike result, ItemLike dye) { super.stainedGlassPaneFromGlassPaneAndDye(result, dye); } + + /** Generated override to expose protected method: {@link RecipeProvider#coloredTerracottaFromTerracottaAndDye} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void coloredTerracottaFromTerracottaAndDye(ItemLike result, ItemLike dye) { super.coloredTerracottaFromTerracottaAndDye(result, dye); } + + /** Generated override to expose protected method: {@link RecipeProvider#concretePowder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void concretePowder(ItemLike result, ItemLike dye) { super.concretePowder(result, dye); } + + /** Generated override to expose protected method: {@link RecipeProvider#candle} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void candle(ItemLike result, ItemLike dye) { super.candle(result, dye); } + + /** Generated override to expose protected method: {@link RecipeProvider#wall} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void wall(RecipeCategory category, ItemLike result, ItemLike base) { super.wall(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#wallBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder wallBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.wallBuilder(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#polished} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void polished(RecipeCategory category, ItemLike result, ItemLike base) { super.polished(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#polishedBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public RecipeBuilder polishedBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.polishedBuilder(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#cut} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void cut(RecipeCategory category, ItemLike result, ItemLike base) { super.cut(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#cutBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapedRecipeBuilder cutBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.cutBuilder(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#chiseled} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void chiseled(RecipeCategory category, ItemLike result, ItemLike base) { super.chiseled(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#mosaicBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void mosaicBuilder(RecipeCategory category, ItemLike result, ItemLike base) { super.mosaicBuilder(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#chiseledBuilder} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapedRecipeBuilder chiseledBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.chiseledBuilder(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#stonecutterResultFromBase} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void stonecutterResultFromBase(RecipeCategory category, ItemLike result, ItemLike base) { super.stonecutterResultFromBase(category, result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#stonecutterResultFromBase} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void stonecutterResultFromBase(RecipeCategory category, ItemLike result, ItemLike base, int count) { super.stonecutterResultFromBase(category, result, base, count); } + + /** Generated override to expose protected method: {@link RecipeProvider#smeltingResultFromBase} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void smeltingResultFromBase(ItemLike result, ItemLike base) { super.smeltingResultFromBase(result, base); } + + /** Generated override to expose protected method: {@link RecipeProvider#nineBlockStorageRecipes} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void nineBlockStorageRecipes(RecipeCategory unpackedFormCategory, ItemLike unpackedForm, RecipeCategory packedFormCategory, ItemLike packedForm) { super.nineBlockStorageRecipes(unpackedFormCategory, unpackedForm, packedFormCategory, packedForm); } + + /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void copySmithingTemplate(ItemLike smithingTemplate, ItemLike baseMaterial) { super.copySmithingTemplate(smithingTemplate, baseMaterial); } + + /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void copySmithingTemplate(ItemLike smithingTemplate, Ingredient baseMaterials) { super.copySmithingTemplate(smithingTemplate, baseMaterials); } + + /** Generated override to expose protected method: {@link RecipeProvider#cookRecipes} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void cookRecipes(String source, AbstractCookingRecipe.Factory factory, int cookingTime) { super.cookRecipes(source, factory, cookingTime); } + + /** Generated override to expose protected method: {@link RecipeProvider#waxRecipes} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void waxRecipes(FeatureFlagSet flagSet) { super.waxRecipes(flagSet); } + + /** Generated override to expose protected method: {@link RecipeProvider#grate} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void grate(Block grateBlock, Block material) { super.grate(grateBlock, material); } + + /** Generated override to expose protected method: {@link RecipeProvider#copperBulb} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void copperBulb(Block copperBulb, Block copperMaterial) { super.copperBulb(copperBulb, copperMaterial); } + + /** Generated override to expose protected method: {@link RecipeProvider#waxedChiseled} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void waxedChiseled(Block result, Block material) { super.waxedChiseled(result, material); } + + /** Generated override to expose protected method: {@link RecipeProvider#suspiciousStew} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void suspiciousStew(Item item, SuspiciousEffectHolder effectHolder) { super.suspiciousStew(item, effectHolder); } + + /** Generated override to expose protected method: {@link RecipeProvider#dyedItem} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void dyedItem(Item target, String group) { super.dyedItem(target, group); } + + /** Generated override to expose protected method: {@link RecipeProvider#dyedShulkerBoxRecipe} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void dyedShulkerBoxRecipe(Item dye, Item dyedResult) { super.dyedShulkerBoxRecipe(dye, dyedResult); } + + /** Generated override to expose protected method: {@link RecipeProvider#dyedBundleRecipe} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void dyedBundleRecipe(Item dye, Item dyedResult) { super.dyedBundleRecipe(dye, dyedResult); } + + /** Generated override to expose protected method: {@link RecipeProvider#generateRecipes} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public void generateRecipes(BlockFamily family, FeatureFlagSet flagSet) { super.generateRecipes(family, flagSet); } + + /** Generated override to expose protected method: {@link RecipeProvider#getBaseBlockForCrafting} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public Block getBaseBlockForCrafting(BlockFamily family, BlockFamily.Variant variant) { return super.getBaseBlockForCrafting(family, variant); } + + /** Generated override to expose protected method: {@link RecipeProvider#insideOf} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static Criterion insideOf(Block block) { return RecipeProvider.insideOf(block); } + + /** Generated override to expose protected method: {@link RecipeProvider#has} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public Criterion has(MinMaxBounds.Ints count, ItemLike item) { return super.has(count, item); } + + /** Generated override to expose protected method: {@link RecipeProvider#has} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public Criterion has(ItemLike item) { return super.has(item); } + + /** Generated override to expose protected method: {@link RecipeProvider#has} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public Criterion has(TagKey tag) { return super.has(tag); } + + /** Generated override to expose protected method: {@link RecipeProvider#inventoryTrigger} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static Criterion inventoryTrigger(ItemPredicate.Builder... predicates) { return RecipeProvider.inventoryTrigger(predicates); } + + /** Generated override to expose protected method: {@link RecipeProvider#inventoryTrigger} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static Criterion inventoryTrigger(ItemPredicate... predicates) { return RecipeProvider.inventoryTrigger(predicates); } + + /** Generated override to expose protected method: {@link RecipeProvider#getHasName} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static String getHasName(ItemLike baseBlock) { return RecipeProvider.getHasName(baseBlock); } + + /** Generated override to expose protected method: {@link RecipeProvider#getItemName} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static String getItemName(ItemLike itemLike) { return RecipeProvider.getItemName(itemLike); } + + /** Generated override to expose protected method: {@link RecipeProvider#getSimpleRecipeName} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static String getSimpleRecipeName(ItemLike itemLike) { return RecipeProvider.getSimpleRecipeName(itemLike); } + + /** Generated override to expose protected method: {@link RecipeProvider#getConversionRecipeName} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static String getConversionRecipeName(ItemLike product, ItemLike material) { return RecipeProvider.getConversionRecipeName(product, material); } + + /** Generated override to expose protected method: {@link RecipeProvider#getSmeltingRecipeName} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static String getSmeltingRecipeName(ItemLike product) { return RecipeProvider.getSmeltingRecipeName(product); } + + /** Generated override to expose protected method: {@link RecipeProvider#getBlastingRecipeName} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public static String getBlastingRecipeName(ItemLike product) { return RecipeProvider.getBlastingRecipeName(product); } + + /** Generated override to expose protected method: {@link RecipeProvider#tag} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public Ingredient tag(TagKey id) { return super.tag(id); } + + /** Generated override to expose protected method: {@link RecipeProvider#shaped} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapedRecipeBuilder shaped(RecipeCategory category, ItemStackTemplate stack) { return super.shaped(category, stack); } + + /** Generated override to expose protected method: {@link RecipeProvider#shaped} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike item) { return super.shaped(category, item); } + + /** Generated override to expose protected method: {@link RecipeProvider#shaped} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike item, int count) { return super.shaped(category, item, count); } + + /** Generated override to expose protected method: {@link RecipeProvider#shapeless} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemStackTemplate result) { return super.shapeless(category, result); } + + /** Generated override to expose protected method: {@link RecipeProvider#shapeless} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike item) { return super.shapeless(category, item); } + + /** Generated override to expose protected method: {@link RecipeProvider#shapeless} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike item, int count) { return super.shapeless(category, item, count); } + + // GENERATED END + +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java new file mode 100644 index 0000000..3f68dfb --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java @@ -0,0 +1,45 @@ +package com.modularmc.registrate.providers.generators; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.RegistrateProvider; + +import net.minecraft.core.HolderLookup; +import net.minecraft.data.PackOutput; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.data.recipes.RecipeProvider; +import net.neoforged.fml.LogicalSide; + +import java.util.concurrent.CompletableFuture; + +public class RegistrateRecipeRunner extends RecipeProvider.Runner implements RegistrateProvider { + + final AbstractRegistrate owner; + + @org.jetbrains.annotations.Nullable + RegistrateRecipeProvider provider; + + public RegistrateRecipeRunner(AbstractRegistrate owner, PackOutput p_365369_, CompletableFuture p_361563_) { + super(p_365369_, p_361563_); + this.owner = owner; + } + + @Override + protected RecipeProvider createRecipeProvider(HolderLookup.Provider p_362946_, RecipeOutput p_365274_) { + return new RegistrateRecipeProvider(this, p_362946_, p_365274_); + } + + @Override + public String getName() { + return ""; + } + + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; + } + + public RegistrateRecipeProvider getRecipeProvider() { + if (provider == null) throw new IllegalStateException("Recipe Provider is not available now"); + return provider; + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/package-info.java b/src/main/java/com/modularmc/registrate/providers/generators/package-info.java new file mode 100644 index 0000000..868b078 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/package-info.java @@ -0,0 +1,9 @@ +/** + * Specialized generator adapters for models, recipes, and blockstates. + * + *

+ * These classes sit beneath the higher-level provider layer and expose the + * concrete helpers used by builder datagen callbacks. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.providers.generators; diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java new file mode 100644 index 0000000..1a2ee60 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java @@ -0,0 +1,303 @@ +package com.modularmc.registrate.providers.loot; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.loot.BlockLootSubProvider; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.storage.loot.LootTable; +import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; +import net.minecraft.world.level.storage.loot.functions.FunctionUserBuilder; +import net.minecraft.world.level.storage.loot.predicates.ConditionUserBuilder; +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; +import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; + +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import javax.annotation.processing.Generated; + +public class RegistrateBlockLootTables extends BlockLootSubProvider implements RegistrateLootTables { + + private final AbstractRegistrate parent; + private final Consumer callback; + + private final HolderLookup itemLookup; + private final HolderLookup blockLookup; + private final HolderLookup> entityLookup; + + public RegistrateBlockLootTables(HolderLookup.Provider provider, AbstractRegistrate parent, Consumer callback) { + super(Set.of(), FeatureFlags.REGISTRY.allFlags(), provider); + this.parent = parent; + this.callback = callback; + itemLookup = registries.lookupOrThrow(Registries.ITEM); + blockLookup = registries.lookupOrThrow(Registries.BLOCK); + entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE); + } + + @Override + protected void generate() { + callback.accept(this); + } + + @Override + protected Iterable getKnownBlocks() { + return parent.getAll(Registries.BLOCK).stream().map(Supplier::get).collect(Collectors.toList()); + } + + public HolderLookup.Provider getRegistries() { + return this.registries; + } + + public HolderLookup itemLookup() { + return itemLookup; + } + + public HolderLookup blockLookup() { + return blockLookup; + } + + public HolderLookup> entityLookup() { + return entityLookup; + } + + // @formatter:off + // GENERATED START - DO NOT EDIT BELOW THIS LINE + + /** Generated override to expose protected method: {@link BlockLootSubProvider#applyExplosionDecay} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public > T applyExplosionDecay(ItemLike type, FunctionUserBuilder builder) { return super.applyExplosionDecay(type, builder); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#applyExplosionCondition} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public > T applyExplosionCondition(ItemLike type, ConditionUserBuilder builder) { return super.applyExplosionCondition(type, builder); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSelfDropDispatchTable} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public static LootTable.Builder createSelfDropDispatchTable(Block original, LootItemCondition.Builder condition, LootPoolEntryContainer.Builder entry) { return BlockLootSubProvider.createSelfDropDispatchTable(original, condition, entry); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchDispatchTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createSilkTouchDispatchTable(Block original, LootPoolEntryContainer.Builder entry) { return super.createSilkTouchDispatchTable(original, entry); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsDispatchTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createShearsDispatchTable(Block original, LootPoolEntryContainer.Builder entry) { return super.createShearsDispatchTable(original, entry); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchOrShearsDispatchTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createSilkTouchOrShearsDispatchTable(Block original, LootPoolEntryContainer.Builder entry) { return super.createSilkTouchOrShearsDispatchTable(original, entry); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTableWithSilkTouch} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createSingleItemTableWithSilkTouch(Block original, ItemLike drop) { return super.createSingleItemTableWithSilkTouch(original, drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createSingleItemTable(ItemLike drop, NumberProvider count) { return super.createSingleItemTable(drop, count); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTableWithSilkTouch} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createSingleItemTableWithSilkTouch(Block original, ItemLike drop, NumberProvider count) { return super.createSingleItemTableWithSilkTouch(original, drop, count); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchOnlyTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createSilkTouchOnlyTable(ItemLike drop) { return super.createSilkTouchOnlyTable(drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createPotFlowerItemTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createPotFlowerItemTable(ItemLike flower) { return super.createPotFlowerItemTable(flower); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createSlabItemTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createSlabItemTable(Block slab) { return super.createSlabItemTable(slab); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createNameableBlockEntityTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createNameableBlockEntityTable(Block drop) { return super.createNameableBlockEntityTable(drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createShulkerBoxDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createShulkerBoxDrop(Block shulkerBox) { return super.createShulkerBoxDrop(shulkerBox); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createCopperOreDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createCopperOreDrops(Block block) { return super.createCopperOreDrops(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createLapisOreDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createLapisOreDrops(Block block) { return super.createLapisOreDrops(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createRedstoneOreDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createRedstoneOreDrops(Block block) { return super.createRedstoneOreDrops(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createBannerDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createBannerDrop(Block original) { return super.createBannerDrop(original); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createBeeNestDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createBeeNestDrop(Block original) { return super.createBeeNestDrop(original); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createBeeHiveDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createBeeHiveDrop(Block original) { return super.createBeeHiveDrop(original); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createCaveVinesDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createCaveVinesDrop(Block original) { return super.createCaveVinesDrop(original); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createCopperGolemStatueBlock} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createCopperGolemStatueBlock(Block block) { return super.createCopperGolemStatueBlock(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createOreDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createOreDrop(Block original, Item drop) { return super.createOreDrop(original, drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createMushroomBlockDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createMushroomBlockDrop(Block original, ItemLike drop) { return super.createMushroomBlockDrop(original, drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createGrassDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createGrassDrops(Block original) { return super.createGrassDrops(original); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsOnlyDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createShearsOnlyDrop(ItemLike drop) { return super.createShearsOnlyDrop(drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsOrSilkTouchOnlyDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createShearsOrSilkTouchOnlyDrop(ItemLike drop) { return super.createShearsOrSilkTouchOnlyDrop(drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createMultifaceBlockDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createMultifaceBlockDrops(Block block, LootItemCondition.Builder condition) { return super.createMultifaceBlockDrops(block, condition); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createMultifaceBlockDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createMultifaceBlockDrops(Block block) { return super.createMultifaceBlockDrops(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createMossyCarpetBlockDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createMossyCarpetBlockDrops(Block block) { return super.createMossyCarpetBlockDrops(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createLeavesDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createLeavesDrops(Block original, Block sapling, float... saplingChances) { return super.createLeavesDrops(original, sapling, saplingChances); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createOakLeavesDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createOakLeavesDrops(Block original, Block sapling, float... saplingChances) { return super.createOakLeavesDrops(original, sapling, saplingChances); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createMangroveLeavesDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createMangroveLeavesDrops(Block block) { return super.createMangroveLeavesDrops(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createCropDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createCropDrops(Block original, Item cropDrop, Item seedDrop, LootItemCondition.Builder isMaxAge) { return super.createCropDrops(original, cropDrop, seedDrop, isMaxAge); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoublePlantShearsDrop} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createDoublePlantShearsDrop(Block block) { return super.createDoublePlantShearsDrop(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoublePlantWithSeedDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createDoublePlantWithSeedDrops(Block block, Block drop) { return super.createDoublePlantWithSeedDrops(block, drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createCandleDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createCandleDrops(Block block) { return super.createCandleDrops(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createCandleCakeDrops} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public static LootTable.Builder createCandleCakeDrops(Block candle) { return BlockLootSubProvider.createCandleCakeDrops(candle); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#addNetherVinesDropTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public void addNetherVinesDropTable(Block vineBlock, Block plantBlock) { super.addNetherVinesDropTable(vineBlock, plantBlock); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoorTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public LootTable.Builder createDoorTable(Block block) { return super.createDoorTable(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#dropPottedContents} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public void dropPottedContents(Block potted) { super.dropPottedContents(potted); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#otherWhenSilkTouch} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public void otherWhenSilkTouch(Block block, Block other) { super.otherWhenSilkTouch(block, other); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#dropOther} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public void dropOther(Block block, ItemLike drop) { super.dropOther(block, drop); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#dropWhenSilkTouch} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public void dropWhenSilkTouch(Block block) { super.dropWhenSilkTouch(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#dropSelf} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public void dropSelf(Block block) { super.dropSelf(block); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#add} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + public void add(Block block, LootTable.Builder builder) { super.add(block, builder); } + + // GENERATED END +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java new file mode 100644 index 0000000..2c64de1 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java @@ -0,0 +1,86 @@ +package com.modularmc.registrate.providers.loot; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.loot.EntityLootSubProvider; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.storage.loot.LootTable; +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; + +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import javax.annotation.processing.Generated; + +public class RegistrateEntityLootTables extends EntityLootSubProvider implements RegistrateLootTables { + + private final AbstractRegistrate parent; + private final Consumer callback; + + private final HolderLookup itemLookup; + private final HolderLookup blockLookup; + private final HolderLookup> entityLookup; + + public RegistrateEntityLootTables(HolderLookup.Provider p_346214_, AbstractRegistrate parent, Consumer callback) { + super(FeatureFlags.REGISTRY.allFlags(), p_346214_); + this.parent = parent; + this.callback = callback; + itemLookup = registries.lookupOrThrow(Registries.ITEM); + blockLookup = registries.lookupOrThrow(Registries.BLOCK); + entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE); + } + + @Override + public void generate() { + callback.accept(this); + } + + @Override + protected Stream> getKnownEntityTypes() { + return parent.getAll(Registries.ENTITY_TYPE).stream().map(Supplier::get); + } + + public HolderLookup.Provider getRegistries() { + return this.registries; + } + + public HolderLookup itemLookup() { + return itemLookup; + } + + public HolderLookup blockLookup() { + return blockLookup; + } + + public HolderLookup> entityLookup() { + return entityLookup; + } + + // @formatter:off + // GENERATED START - DO NOT EDIT BELOW THIS LINE + + /** Generated override to expose protected method: {@link EntityLootSubProvider#killedByFrog} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Sun, 19 Apr 2026 10:15:16 GMT") + public LootItemCondition.Builder killedByFrog(HolderGetter> entityTypes) { return super.killedByFrog(entityTypes); } + + /** Generated override to expose protected method: {@link EntityLootSubProvider#add} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Sun, 19 Apr 2026 10:15:16 GMT") + public void add(EntityType type, LootTable.Builder builder) { super.add(type, builder); } + + /** Generated override to expose protected method: {@link EntityLootSubProvider#add} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Sun, 19 Apr 2026 10:15:16 GMT") + public void add(EntityType type, ResourceKey lootTable, LootTable.Builder builder) { super.add(type, lootTable, builder); } + + // GENERATED END +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java new file mode 100644 index 0000000..a966df8 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java @@ -0,0 +1,129 @@ +package com.modularmc.registrate.providers.loot; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.core.RegistrateProvider; +import com.modularmc.registrate.util.nullness.NonNullConsumer; + +import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.WritableRegistry; +import net.minecraft.data.PackOutput; +import net.minecraft.data.loot.LootTableProvider; +import net.minecraft.data.loot.LootTableSubProvider; +import net.minecraft.data.loot.packs.VanillaLootTableProvider; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.util.ProblemReporter; +import net.minecraft.util.context.ContextKeySet; +import net.minecraft.world.level.storage.loot.LootTable; +import net.minecraft.world.level.storage.loot.ValidationContextSource; +import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; +import net.neoforged.fml.LogicalSide; +import net.neoforged.fml.util.ObfuscationReflectionHelper; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Multimap; +import org.apache.commons.lang3.function.TriFunction; + +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +public class RegistrateLootTableProvider extends LootTableProvider implements RegistrateProvider { + + public interface LootType { + + static LootType BLOCK = register("block", LootContextParamSets.BLOCK, RegistrateBlockLootTables::new); + static LootType ENTITY = register("entity", LootContextParamSets.ENTITY, RegistrateEntityLootTables::new); + + T getLootCreator(HolderLookup.Provider provider, AbstractRegistrate parent, Consumer callback); + + ContextKeySet getLootSet(); + + static LootType register(String name, ContextKeySet set, TriFunction, Consumer, T> factory) { + LootType type = new LootType() { + + @Override + public T getLootCreator(HolderLookup.Provider provider, AbstractRegistrate parent, Consumer callback) { + return factory.apply(provider, parent, callback); + } + + @Override + public ContextKeySet getLootSet() { + return set; + } + }; + LOOT_TYPES.put(name, type); + return type; + } + } + + private static final Map> LOOT_TYPES = new HashMap<>(); + + private final AbstractRegistrate parent; + + private final Multimap, Consumer> specialLootActions = HashMultimap.create(); + private final Multimap, LootTable.Builder>>> lootActions = HashMultimap.create(); + private final Set currentLootCreators = new HashSet<>(); + + private CompletableFuture provider; + + public RegistrateLootTableProvider(AbstractRegistrate parent, PackOutput packOutput, CompletableFuture provider) { + super(packOutput, Set.of(), VanillaLootTableProvider.create(packOutput, provider).getTables(), provider); + this.parent = parent; + this.provider = provider; + } + + public HolderLookup.Provider getProvider() { + return provider.getNow(null); + } + + public Holder resolve(ResourceKey key) { + return getProvider().lookupOrThrow(key.registryKey()).getOrThrow(key); + } + + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; + } + + @Override + protected void validate(WritableRegistry tables, ValidationContextSource validationContext, ProblemReporter.Collector problems) { + currentLootCreators.forEach(c -> c.validate(tables, validationContext)); + } + + @SuppressWarnings("unchecked") + public void addLootAction(LootType type, NonNullConsumer action) { + this.specialLootActions.put(type, (Consumer) action); + } + + public void addLootAction(ContextKeySet set, Consumer, LootTable.Builder>> action) { + this.lootActions.put(set, action); + } + + private LootTableSubProvider getLootCreator(HolderLookup.Provider provider, AbstractRegistrate parent, LootType type) { + RegistrateLootTables creator = type.getLootCreator(provider, parent, cons -> specialLootActions.get(type).forEach(c -> c.accept(cons))); + currentLootCreators.add(creator); + return creator; + } + + private static final BiMap SET_REGISTRY = ObfuscationReflectionHelper.getPrivateValue(LootContextParamSets.class, null, "REGISTRY"); + + @Override + public List getTables() { + parent.genData(ProviderType.LOOT, this); + currentLootCreators.clear(); + ImmutableList.Builder builder = ImmutableList.builder(); + for (LootType type : LOOT_TYPES.values()) { + builder.add(new SubProviderEntry(provider -> getLootCreator(provider, parent, type), type.getLootSet())); + } + for (ContextKeySet set : SET_REGISTRY.values()) { + builder.add(new SubProviderEntry((provider) -> callback -> lootActions.get(set).forEach(a -> a.accept(callback)), set)); + } + return builder.build(); + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java new file mode 100644 index 0000000..dee7c21 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java @@ -0,0 +1,11 @@ +package com.modularmc.registrate.providers.loot; + +import net.minecraft.core.WritableRegistry; +import net.minecraft.data.loot.LootTableSubProvider; +import net.minecraft.world.level.storage.loot.LootTable; +import net.minecraft.world.level.storage.loot.ValidationContextSource; + +public interface RegistrateLootTables extends LootTableSubProvider { + + default void validate(WritableRegistry tables, ValidationContextSource validationContext) {} +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/package-info.java b/src/main/java/com/modularmc/registrate/providers/loot/package-info.java new file mode 100644 index 0000000..5620fe2 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/package-info.java @@ -0,0 +1,9 @@ +/** + * Loot-table focused provider wrappers. + * + *

+ * This layer isolates loot-specific generation concerns from the rest of the + * provider stack so block and entity loot behavior can evolve independently. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.providers.loot; diff --git a/src/main/java/com/modularmc/registrate/providers/package-info.java b/src/main/java/com/modularmc/registrate/providers/package-info.java new file mode 100644 index 0000000..4919a51 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/package-info.java @@ -0,0 +1,10 @@ +/** + * Built-in data provider implementations and data generation callback context. + * + *

+ * Shared provider contracts, type registries, and orchestration infrastructure + * live in {@code com.modularmc.registrate.providers.core}. This package keeps + * the concrete provider implementations closer to the data they generate. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.providers; diff --git a/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java b/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java new file mode 100644 index 0000000..58cb1cb --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java @@ -0,0 +1,53 @@ +package com.modularmc.registrate.util; + +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.ItemLike; + +import org.jetbrains.annotations.ApiStatus; + +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +public final class CreativeModeTabModifier implements CreativeModeTab.Output { + + private final Supplier flags; + private final BooleanSupplier hasPermissions; + private final BiConsumer acceptFunc; + private final Supplier parameters; + + @ApiStatus.Internal + public CreativeModeTabModifier(Supplier flags, BooleanSupplier hasPermissions, BiConsumer acceptFunc, Supplier parameters) { + this.flags = flags; + this.hasPermissions = hasPermissions; + this.acceptFunc = acceptFunc; + this.parameters = parameters; + } + + public FeatureFlagSet getFlags() { + return flags.get(); + } + + public CreativeModeTab.ItemDisplayParameters getParameters() { + return parameters.get(); + } + + public boolean hasPermissions() { + return hasPermissions.getAsBoolean(); + } + + @Override + public void accept(ItemStack stack, CreativeModeTab.TabVisibility visibility) { + acceptFunc.accept(stack, visibility); + } + + public void accept(Supplier item, CreativeModeTab.TabVisibility visibility) { + accept(item.get(), visibility); + } + + public void accept(Supplier item) { + accept(item.get()); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/DataIngredient.java b/src/main/java/com/modularmc/registrate/util/DataIngredient.java new file mode 100644 index 0000000..0829219 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/DataIngredient.java @@ -0,0 +1,93 @@ +package com.modularmc.registrate.util; + +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.advancements.Criterion; +import net.minecraft.advancements.criterion.InventoryChangeTrigger; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.core.HolderSet; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.level.ItemLike; + +import com.google.common.collect.ObjectArrays; +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * A helper for data generation when using ingredients as input(s) to recipes.
+ * It remembers the name of the primary ingredient for use in creating recipe names/criteria. + *

+ * Create an instance of this class with the various factory methods such as {@link #items(ItemLike, ItemLike...)} and + * {@link #tag(HolderSet.Named)} )}. + *

+ * This class should not be used for any purpose other than data generation, it will throw an exception + * if it is serialized to a packet buffer. + */ +public final class DataIngredient { + + private final Ingredient parent; + @Getter + private final Identifier id; + private final Function> criteriaFactory; + + private DataIngredient(Ingredient parent, ItemLike item) { + this.parent = parent; + this.id = BuiltInRegistries.ITEM.getKey(item.asItem()); + this.criteriaFactory = prov -> prov.has(item); + } + + private DataIngredient(Ingredient parent, TagKey tag) { + this.parent = parent; + this.id = tag.location(); + this.criteriaFactory = prov -> prov.has(tag); + } + + private DataIngredient(Ingredient parent, Identifier id, ItemPredicate... predicates) { + this.parent = parent; + this.id = id; + this.criteriaFactory = ignored -> RegistrateRecipeProvider.inventoryTrigger(predicates); + } + + public Criterion getCriterion(RegistrateRecipeProvider prov) { + return criteriaFactory.apply(prov); + } + + @SuppressWarnings("unchecked") + @SafeVarargs + public static DataIngredient items(NonNullSupplier first, NonNullSupplier... others) { + return items(first.get(), (T[]) Arrays.stream(others).map(Supplier::get).toArray(ItemLike[]::new)); + } + + @SafeVarargs + public static DataIngredient items(T first, T... others) { + return ingredient(Ingredient.of(ObjectArrays.concat(first, others)), first); + } + + public static DataIngredient tag(HolderSet.Named tag) { + return ingredient(Ingredient.of(tag), tag.key()); + } + + public static DataIngredient ingredient(Ingredient parent, ItemLike required) { + return new DataIngredient(parent, required); + } + + public static DataIngredient ingredient(Ingredient parent, TagKey required) { + return new DataIngredient(parent, required); + } + + public static DataIngredient ingredient(Ingredient parent, Identifier id, ItemPredicate... criteria) { + return new DataIngredient(parent, id, criteria); + } + + public Ingredient toVanilla() { + return parent; + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java b/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java new file mode 100644 index 0000000..269c64b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java @@ -0,0 +1,74 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.neoforge.registries.DeferredHolder; + +import org.jspecify.annotations.Nullable; + +import java.util.Optional; + +public class BlockEntityEntry extends RegistryEntry, BlockEntityType> { + + public BlockEntityEntry(AbstractRegistrate owner, DeferredHolder, BlockEntityType> delegate) { + super(owner, delegate); + } + + /** + * Create a "default" instance of this {@link BlockEntity} via the {@link BlockEntityType}. + * + * @return The instance + */ + public T create(BlockPos pos, BlockState state) { + return get().create(pos, state); + } + + /** + * Check that the given {@link BlockEntity} is an instance of this type. + * + * @param t + * The {@link BlockEntity} instance + * @return {@code true} if the type matches, {@code false} otherwise. + */ + public boolean is(@Nullable BlockEntity t) { + return t != null && t.getType() == get(); + } + + /** + * Get an instance of this {@link BlockEntity} from the world. + * + * @param world + * The world to look for the instance in + * @param pos + * The position of the instance + * @return An {@link Optional} containing the instance, if it exists and matches this type. Otherwise, + * {@link Optional#empty()}. + */ + public Optional get(BlockGetter world, BlockPos pos) { + return Optional.ofNullable(getNullable(world, pos)); + } + + /** + * Get an instance of this {@link BlockEntity} from the world. + * + * @param world + * The world to look for the instance in + * @param pos + * The position of the instance + * @return The instance, if it exists and matches this type. Otherwise, {@code null}. + */ + @SuppressWarnings("unchecked") + public @Nullable T getNullable(BlockGetter world, BlockPos pos) { + BlockEntity be = world.getBlockEntity(pos); + return is(be) ? (T) be : null; + } + + public static BlockEntityEntry cast(RegistryEntry, BlockEntityType> entry) { + return RegistryEntry.cast(BlockEntityEntry.class, entry); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java b/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java new file mode 100644 index 0000000..14623e3 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java @@ -0,0 +1,26 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.neoforged.neoforge.registries.DeferredHolder; + +public class BlockEntry extends ItemProviderEntry { + + public BlockEntry(AbstractRegistrate owner, DeferredHolder delegate) { + super(owner, delegate); + } + + public BlockState getDefaultState() { + return get().defaultBlockState(); + } + + public boolean has(BlockState state) { + return is(state.getBlock()); + } + + public static BlockEntry cast(RegistryEntry entry) { + return RegistryEntry.cast(BlockEntry.class, entry); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java b/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java new file mode 100644 index 0000000..cab5ebd --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java @@ -0,0 +1,30 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.Level; +import net.neoforged.neoforge.registries.DeferredHolder; + +import org.jspecify.annotations.Nullable; + +public class EntityEntry extends RegistryEntry, EntityType> { + + public EntityEntry(AbstractRegistrate owner, DeferredHolder, EntityType> delegate) { + super(owner, delegate); + } + + public @Nullable T create(Level world, EntitySpawnReason reason) { + return get().create(world, reason); + } + + public boolean is(Entity t) { + return t != null && t.getType() == get(); + } + + public static EntityEntry cast(RegistryEntry, EntityType> entry) { + return RegistryEntry.cast(EntityEntry.class, entry); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java b/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java new file mode 100644 index 0000000..88111f7 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java @@ -0,0 +1,53 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.material.Fluid; +import net.neoforged.neoforge.fluids.BaseFlowingFluid; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.registries.DeferredHolder; + +import org.jspecify.annotations.Nullable; + +import java.util.Optional; + +public class FluidEntry extends RegistryEntry { + + private final @Nullable BlockEntry block; + + public FluidEntry(AbstractRegistrate owner, DeferredHolder delegate) { + super(owner, delegate); + this.block = getSiblingOptional(BuiltInRegistries.BLOCK) + .map(BlockEntry::cast) + .orElse(null); + } + + @Override + public boolean is(R entry) { + return get().isSame((Fluid) entry); + } + + @SuppressWarnings("unchecked") + public S getSource() { + return (S) get().getSource(); + } + + public FluidType getType() { + return get().getFluidType(); + } + + @SuppressWarnings({ "unchecked", "null" }) + public Optional getBlock() { + return (Optional) Optional.ofNullable(block).map(RegistryEntry::get); + } + + @SuppressWarnings({ "unchecked", "null" }) + public Optional getBucket() { + return Optional.of((I) get().getBucket()) + .filter(item -> item != Items.AIR); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java b/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java new file mode 100644 index 0000000..6aa577e --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java @@ -0,0 +1,17 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.world.item.Item; +import net.neoforged.neoforge.registries.DeferredHolder; + +public class ItemEntry extends ItemProviderEntry { + + public ItemEntry(AbstractRegistrate owner, DeferredHolder delegate) { + super(owner, delegate); + } + + public static ItemEntry cast(RegistryEntry entry) { + return RegistryEntry.cast(ItemEntry.class, entry); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java b/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java new file mode 100644 index 0000000..8aab3b4 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java @@ -0,0 +1,45 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.ItemStackTemplate; +import net.minecraft.world.level.ItemLike; +import net.neoforged.neoforge.registries.DeferredHolder; + +public class ItemProviderEntry extends RegistryEntry implements ItemLike { + + public ItemProviderEntry(AbstractRegistrate owner, DeferredHolder delegate) { + super(owner, delegate); + } + + public ItemStack asStack() { + return new ItemStack(this); + } + + public ItemStack asStack(int count) { + return new ItemStack(this, count); + } + + public ItemStackTemplate asStackTemplate() { + return new ItemStackTemplate(asItem(), 1); + } + + public ItemStackTemplate asStackTemplate(int count) { + return new ItemStackTemplate(asItem(), count); + } + + public boolean isIn(ItemStack stack) { + return is(stack.getItem()); + } + + public boolean is(Item item) { + return asItem() == item; + } + + @Override + public Item asItem() { + return get().asItem(); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java b/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java new file mode 100644 index 0000000..afce5e8 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java @@ -0,0 +1,25 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import org.jspecify.annotations.Nullable; + +public class LazyRegistryEntry implements NonNullSupplier { + + private @Nullable NonNullSupplier> supplier; + private @Nullable RegistryEntry value; + + public LazyRegistryEntry(NonNullSupplier> supplier) { + this.supplier = supplier; + } + + @Override + public T get() { + NonNullSupplier> supplier = this.supplier; + if (supplier != null) { + this.value = supplier.get(); + this.supplier = null; + } + return this.value.get(); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java b/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java new file mode 100644 index 0000000..de3ec28 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java @@ -0,0 +1,46 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.SimpleMenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuConstructor; +import net.minecraft.world.inventory.MenuType; +import net.neoforged.neoforge.registries.DeferredHolder; + +import java.util.function.Consumer; + +public class MenuEntry extends RegistryEntry, MenuType> { + + public MenuEntry(AbstractRegistrate owner, DeferredHolder, MenuType> delegate) { + super(owner, delegate); + } + + public T create(int windowId, Inventory playerInv) { + return get().create(windowId, playerInv); + } + + public MenuConstructor asProvider() { + return (window, playerinv, $) -> create(window, playerinv); + } + + public void open(ServerPlayer player, Component displayName) { + open(player, displayName, asProvider()); + } + + public void open(ServerPlayer player, Component displayName, Consumer extraData) { + open(player, displayName, asProvider(), extraData); + } + + public void open(ServerPlayer player, Component displayName, MenuConstructor provider) { + player.openMenu(new SimpleMenuProvider(provider, displayName)); + } + + public void open(ServerPlayer player, Component displayName, MenuConstructor provider, Consumer extraData) { + player.openMenu(new SimpleMenuProvider(provider, displayName), extraData); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java b/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java new file mode 100644 index 0000000..f9f44f3 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java @@ -0,0 +1,81 @@ +package com.modularmc.registrate.util.entry; + +import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.util.nullness.NonNullSupplier; + +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceKey; +import net.neoforged.neoforge.registries.DeferredHolder; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; + +/** + * Wraps a {@link net.neoforged.neoforge.registries.DeferredHolder}, providing a cleaner API with null-safe access, and + * registrate-specific extensions such as {@link #getSibling(ResourceKey)} and + * {@link #getSiblingOptional(ResourceKey)}. + * + * @param + * The type of the entry + */ +public class RegistryEntry extends DeferredHolder implements NonNullSupplier { + + private final AbstractRegistrate owner; + + @SuppressWarnings("unused") + public RegistryEntry(AbstractRegistrate owner, DeferredHolder key) { + super(key.getKey()); + + if (owner == null) + throw new NullPointerException("Owner must not be null"); + this.owner = owner; + } + + public RegistryEntry getSibling(ResourceKey> registryType) { + return owner.get(getId().getPath(), registryType); + } + + public Optional> getSiblingOptional(ResourceKey> registryType) { + return owner.getOptional(getId().getPath(), registryType); + } + + public RegistryEntry getSibling(Registry registry) { + return getSibling(registry.key()); + } + + public Optional> getSiblingOptional(Registry registry) { + return getSiblingOptional(registry.key()); + } + + /** + * If an entry is present, and the entry matches the given predicate, return an {@link Optional} + * describing the value, otherwise return an empty {@link Optional}. + * + * @param predicate + * a {@link Predicate predicate} to apply to the entry, if present + * @return an {@link RegistryEntry} describing the value of this {@link RegistryEntry} if the entry is present and + * matches the given predicate, otherwise an empty {@link RegistryEntry} + * @throws NullPointerException + * if the predicate is null + */ + public Optional> filter(Predicate predicate) { + Objects.requireNonNull(predicate); + if (predicate.test(get())) { + return Optional.of(this); + } + return Optional.empty(); + } + + public boolean is(X entry) { + return get() == entry; + } + + @SuppressWarnings("unchecked") + protected static > E cast(Class clazz, RegistryEntry entry) { + if (clazz.isInstance(entry)) { + return (E) entry; + } + throw new IllegalArgumentException("Could not convert RegistryEntry: expecting " + clazz + ", found " + entry.getClass()); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/package-info.java b/src/main/java/com/modularmc/registrate/util/entry/package-info.java new file mode 100644 index 0000000..ae489b8 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/package-info.java @@ -0,0 +1,9 @@ +/** + * Strongly-typed registry entry handles. + * + *

+ * These wrappers are the stable objects returned to downstream code after + * registration is declared through the builder layer. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.util.entry; diff --git a/src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java b/src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java new file mode 100644 index 0000000..cb23b90 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java @@ -0,0 +1,25 @@ +package com.modularmc.registrate.util.nullness; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.annotation.Nonnull; +import javax.annotation.meta.TypeQualifierDefault; + +/** + * This annotation can be applied to a package or class to indicate that the fields in that element are nonnull by + * default unless there is: + *

    + *
  • An explicit nullness annotation + *
  • there is a default parameter annotation applied to a more tightly nested element. + *
+ */ +@Documented +@Nonnull +@TypeQualifierDefault(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.PACKAGE, ElementType.TYPE }) +public @interface FieldsAreNonnullByDefault {} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java new file mode 100644 index 0000000..033697e --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java @@ -0,0 +1,14 @@ +package com.modularmc.registrate.util.nullness; + +import java.util.function.BiConsumer; + +@FunctionalInterface +public interface NonNullBiConsumer extends BiConsumer { + + @Override + void accept(T t, U u); + + static NonNullBiConsumer noop() { + return (t, u) -> {}; + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java new file mode 100644 index 0000000..eabc7d6 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java @@ -0,0 +1,10 @@ +package com.modularmc.registrate.util.nullness; + +import java.util.function.BiFunction; + +@FunctionalInterface +public interface NonNullBiFunction extends BiFunction { + + @Override + R apply(T t, U u); +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java new file mode 100644 index 0000000..8e23abf --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java @@ -0,0 +1,23 @@ +package com.modularmc.registrate.util.nullness; + +import java.util.Objects; +import java.util.function.Consumer; + +@FunctionalInterface +public interface NonNullConsumer extends Consumer { + + @Override + void accept(T t); + + default NonNullConsumer andThen(NonNullConsumer after) { + Objects.requireNonNull(after); + return (T t) -> { + accept(t); + after.accept(t); + }; + } + + static NonNullConsumer noop() { + return t -> {}; + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java new file mode 100644 index 0000000..bfbcbe2 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java @@ -0,0 +1,16 @@ +package com.modularmc.registrate.util.nullness; + +import java.util.Objects; +import java.util.function.Function; + +@FunctionalInterface +public interface NonNullFunction extends Function { + + @Override + R apply(T t); + + default NonNullFunction andThen(NonNullFunction after) { + Objects.requireNonNull(after); + return t -> after.apply(apply(t)); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java new file mode 100644 index 0000000..b6cad27 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java @@ -0,0 +1,33 @@ +package com.modularmc.registrate.util.nullness; + +import net.neoforged.neoforge.common.util.Lazy; + +import java.util.Objects; +import java.util.function.Supplier; + +@FunctionalInterface +public interface NonNullSupplier extends Supplier { + + @Override + T get(); + + static NonNullSupplier of(Supplier sup) { + return of(sup, () -> "Unexpected null value from supplier"); + } + + static NonNullSupplier of(Supplier sup, NonNullSupplier errorMsg) { + return () -> { + T res = sup.get(); + Objects.requireNonNull(res, errorMsg); + return res; + }; + } + + default NonNullSupplier lazy() { + return lazy(this); + } + + static NonNullSupplier lazy(Supplier sup) { + return Lazy.of(sup)::get; + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java new file mode 100644 index 0000000..b8cb544 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java @@ -0,0 +1,16 @@ +package com.modularmc.registrate.util.nullness; + +import java.util.Objects; + +@FunctionalInterface +public interface NonNullUnaryOperator extends NonNullFunction { + + static NonNullUnaryOperator identity() { + return t -> t; + } + + default NonNullUnaryOperator andThen(NonNullUnaryOperator after) { + Objects.requireNonNull(after); + return t -> after.apply(apply(t)); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java b/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java new file mode 100644 index 0000000..a592b2c --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java @@ -0,0 +1,18 @@ +package com.modularmc.registrate.util.nullness; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.annotation.Nonnull; + +/** + * An alternative to {@link javax.annotation.Nonnull} which works on type parameters (J8 feature). + */ +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_PARAMETER, ElementType.TYPE_USE }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Nonnull +public @interface NonnullType {} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java b/src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java new file mode 100644 index 0000000..351c051 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java @@ -0,0 +1,32 @@ +package com.modularmc.registrate.util.nullness; + +import org.jspecify.annotations.Nullable; + +import java.util.Objects; +import java.util.function.Supplier; + +@Deprecated +public interface NullableSupplier extends Supplier<@Nullable T> { + + @Override + @Nullable + T get(); + + default T getNonNull() { + return getNonNull(() -> "Unexpected null value from supplier"); + } + + default T getNonNull(NonNullSupplier errorMsg) { + T res = get(); + Objects.requireNonNull(res, errorMsg); + return res; + } + + default NonNullSupplier asNonNull() { + return () -> getNonNull(); + } + + default NonNullSupplier asNonNull(NonNullSupplier errorMsg) { + return () -> getNonNull(errorMsg); + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NullableType.java b/src/main/java/com/modularmc/registrate/util/nullness/NullableType.java new file mode 100644 index 0000000..e01dfa7 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NullableType.java @@ -0,0 +1,18 @@ +package com.modularmc.registrate.util.nullness; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.annotation.Nullable; + +/** + * An alternative to {@link javax.annotation.Nullable} which works on type parameters (J8 feature). + */ +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_PARAMETER, ElementType.TYPE_USE }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Nullable +public @interface NullableType {} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/package-info.java b/src/main/java/com/modularmc/registrate/util/nullness/package-info.java new file mode 100644 index 0000000..dda48a4 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/package-info.java @@ -0,0 +1,9 @@ +/** + * Nullness-oriented functional helpers and package conventions. + * + *

+ * This package centralizes the functional interfaces and annotations used to + * keep the fluent API ergonomic while remaining explicit about null contracts. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.util.nullness; diff --git a/src/main/java/com/modularmc/registrate/util/package-info.java b/src/main/java/com/modularmc/registrate/util/package-info.java new file mode 100644 index 0000000..8e1e3ce --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/package-info.java @@ -0,0 +1,11 @@ +/** + * Shared downstream-facing support utilities. + * + *

+ * Only helpers that are intentionally part of the reusable library surface and + * are not clearly builder- or provider-specific should live here. Internal + * event plumbing, dist-gated execution helpers, and debug markers belong under + * {@code com.modularmc.registrate.internal}. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.util; diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/META-INF/enum_extensions.json b/src/main/resources/META-INF/enum_extensions.json new file mode 100644 index 0000000..14aa6f5 --- /dev/null +++ b/src/main/resources/META-INF/enum_extensions.json @@ -0,0 +1,3 @@ +{ + "entries": [] +} diff --git a/src/main/templates/META-INF/neoforge.mods.toml b/src/main/templates/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..cdbb66c --- /dev/null +++ b/src/main/templates/META-INF/neoforge.mods.toml @@ -0,0 +1,35 @@ +modLoader = "javafml" +loaderVersion = "[${loader_version},)" +issueTrackerURL = "${mod_issue_tracker}" +license = "${mod_license}" + +[[mods]] +modId = "${mod_id}" +version = "${version}" +displayName = "${mod_name}" +authors = "QiuYe" +description = "${mod_description}" +#logoFile = "icon.png" +displayURL = "${mod_url}" +credits = "" + +#enumExtensions = "META-INF/enum_extensions.json" + +#[[mixins]] +# config = "${mod_id}.mixins.json" +[[accessTransformers]] + file = "META-INF/accesstransformer.cfg" + + +[[dependencies.${mod_id}]] + modId = "neoforge" + type = "required" + versionRange = "[${neo_version},)" + ordering = "NONE" + side = "BOTH" +[[dependencies.${mod_id}]] + modId = "minecraft" + type = "required" + versionRange = "${minecraft_version}" + ordering = "NONE" + side = "BOTH" diff --git a/src/test/generated/resources/assets/testmod/blockstates/magic_item_model.json b/src/test/generated/resources/assets/testmod/blockstates/magic_item_model.json new file mode 100644 index 0000000..0ad4a59 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/blockstates/magic_item_model.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "testmod:block/subfolder/magic_item_model" + } + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/blockstates/testblock.json b/src/test/generated/resources/assets/testmod/blockstates/testblock.json new file mode 100644 index 0000000..5f6ec4d --- /dev/null +++ b/src/test/generated/resources/assets/testmod/blockstates/testblock.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "minecraft:block/glass" + } + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/blockstates/testbucketfluid.json b/src/test/generated/resources/assets/testmod/blockstates/testbucketfluid.json new file mode 100644 index 0000000..d97bc1a --- /dev/null +++ b/src/test/generated/resources/assets/testmod/blockstates/testbucketfluid.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "testmod:block/testbucketfluid" + } + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/blockstates/testfluid.json b/src/test/generated/resources/assets/testmod/blockstates/testfluid.json new file mode 100644 index 0000000..791eb00 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/blockstates/testfluid.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "testmod:block/testfluid" + } + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/magic_item_model.json b/src/test/generated/resources/assets/testmod/items/magic_item_model.json new file mode 100644 index 0000000..8f0f7e8 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/items/magic_item_model.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "testmod:block/subfolder/magic_item_model" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testblock.json b/src/test/generated/resources/assets/testmod/items/testblock.json new file mode 100644 index 0000000..0f2f576 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/items/testblock.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "minecraft:model", + "model": "minecraft:item/egg", + "tints": [ + { + "type": "minecraft:constant", + "value": -65536 + } + ] + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json b/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json new file mode 100644 index 0000000..b48ce41 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json @@ -0,0 +1,12 @@ +{ + "model": { + "type": "neoforge:fluid_container", + "flip_gas": true, + "fluid": "testmod:testbucketfluid", + "textures": { + "base": "minecraft:item/bucket", + "fluid": "neoforge:item/mask/bucket_fluid", + "particle": "minecraft:item/bucket" + } + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json b/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json new file mode 100644 index 0000000..ec7ccbb --- /dev/null +++ b/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "testmod:item/testentity_spawn_egg" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testitem.json b/src/test/generated/resources/assets/testmod/items/testitem.json new file mode 100644 index 0000000..f5c9f2a --- /dev/null +++ b/src/test/generated/resources/assets/testmod/items/testitem.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "minecraft:block/stone" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/lang/en_ud.json b/src/test/generated/resources/assets/testmod/lang/en_ud.json new file mode 100644 index 0000000..a236878 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/lang/en_ud.json @@ -0,0 +1,23 @@ +{ + "advancements.testmod.root.description": "˙bbǝ uɐ ʇǝ⅁", + "advancements.testmod.root.title": "ʇuǝɯǝɔuɐʌpⱯ ʇsǝ⟘", + "block.testmod.magic_item_model": "ןǝpoW ɯǝʇI ɔıbɐW", + "block.testmod.testblock": "ʞɔoןqʇsǝ⟘", + "block.testmod.testbucketfluid": "pınןɟʇǝʞɔnqʇsǝ⟘", + "block.testmod.testfluid": "pınןɟʇsǝ⟘", + "entity.testmod.testentity": "ʎʇıʇuǝʇsǝ⟘", + "entity.testmod.testitem": "ɯǝʇıʇsǝ⟘", + "fluid.testmod.testbucketfluid": "pınןɟʇǝʞɔnqʇsǝ⟘", + "fluid.testmod.testfluid": "pınןɟʇsǝ⟘", + "item.testmod.testbucketfluid_bucket": "ʇǝʞɔnᗺ pınןɟʇǝʞɔnqʇsǝ⟘", + "item.testmod.testentity_spawn_egg": "bbƎ uʍɐdS ʎʇıʇuǝʇsǝ⟘", + "item.testmod.testitem": "ɯǝʇıʇsǝ⟘", + "item.testmod.testitem.testextra": "¡ɔıbɐW", + "itemGroup.testmod.test_creative_mode_tab": "qɐ⟘ ǝpoW ǝʌıʇɐǝɹƆ ʇsǝ⟘", + "testmod.custom.lang": "ʇsǝ⟘", + "testmod.custom.lang.brackets": "◁ϛ ʇǝʞɔɐɹᗺ▷ <ㄣ ʇǝʞɔɐɹᗺ> {Ɛ ʇǝʞɔɐɹᗺ} [ᄅ ʇǝʞɔɐɹᗺ] (Ɩ ʇǝʞɔɐɹᗺ)", + "testmod.custom.lang.slashes": "/ ɥsɐןsʞɔɐq ɐ sı ǝɹǝɥ puɐ poob ʞooן spuɐɯɯɯoɔ\\", + "testmod.custom.lang.with_placeholders1": "%2$s ᄅ ɹǝpןoɥǝɔɐןԀ %1$s Ɩ ɹǝpןoɥǝɔɐןԀ", + "testmod.custom.lang.with_placeholders2": "%3$s Ɛ ɹǝpןoɥǝɔɐןԀ %2$s ᄅ ɹǝpןoɥǝɔɐןԀ %1$s Ɩ ɹǝpןoɥǝɔɐןԀ", + "tooltip.testmod.testblock": "˙bbƎ" +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/lang/en_us.json b/src/test/generated/resources/assets/testmod/lang/en_us.json new file mode 100644 index 0000000..58f56c5 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/lang/en_us.json @@ -0,0 +1,23 @@ +{ + "advancements.testmod.root.description": "Get an egg.", + "advancements.testmod.root.title": "Test Advancement", + "block.testmod.magic_item_model": "Magic Item Model", + "block.testmod.testblock": "Testblock", + "block.testmod.testbucketfluid": "Testbucketfluid", + "block.testmod.testfluid": "Testfluid", + "entity.testmod.testentity": "Testentity", + "entity.testmod.testitem": "Testitem", + "fluid.testmod.testbucketfluid": "Testbucketfluid", + "fluid.testmod.testfluid": "Testfluid", + "item.testmod.testbucketfluid_bucket": "Testbucketfluid Bucket", + "item.testmod.testentity_spawn_egg": "Testentity Spawn Egg", + "item.testmod.testitem": "Testitem", + "item.testmod.testitem.testextra": "Magic!", + "itemGroup.testmod.test_creative_mode_tab": "Test Creative Mode Tab", + "testmod.custom.lang": "Test", + "testmod.custom.lang.brackets": "(Bracket 1) [Bracket 2] {Bracket 3} ◁Bracket 5▷", + "testmod.custom.lang.slashes": "/commmands look good and here is a backslash \\", + "testmod.custom.lang.with_placeholders1": "Placeholder 1 %s Placeholder 2 %s", + "testmod.custom.lang.with_placeholders2": "Placeholder 1 %s Placeholder 2 %2$s Placeholder 3 %s", + "tooltip.testmod.testblock": "Egg." +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/block/subfolder/magic_item_model.json b/src/test/generated/resources/assets/testmod/models/block/subfolder/magic_item_model.json new file mode 100644 index 0000000..e4cf5ec --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/block/subfolder/magic_item_model.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:block/cube_all", + "textures": { + "all": "minecraft:block/gold_block" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/block/testbucketfluid.json b/src/test/generated/resources/assets/testmod/models/block/testbucketfluid.json new file mode 100644 index 0000000..6703228 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/block/testbucketfluid.json @@ -0,0 +1,5 @@ +{ + "textures": { + "particle": "minecraft:block/water_still" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/block/testfluid.json b/src/test/generated/resources/assets/testmod/models/block/testfluid.json new file mode 100644 index 0000000..467346c --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/block/testfluid.json @@ -0,0 +1,5 @@ +{ + "textures": { + "particle": "minecraft:block/water_flow" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/item/testentity_spawn_egg.json b/src/test/generated/resources/assets/testmod/models/item/testentity_spawn_egg.json new file mode 100644 index 0000000..3730294 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/item/testentity_spawn_egg.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/generated", + "textures": { + "layer0": "testmod:item/testentity_spawn_egg" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/block/dragon_immune.json b/src/test/generated/resources/data/minecraft/tags/block/dragon_immune.json new file mode 100644 index 0000000..185287b --- /dev/null +++ b/src/test/generated/resources/data/minecraft/tags/block/dragon_immune.json @@ -0,0 +1,5 @@ +{ + "values": [ + "testmod:testblock" + ] +} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json b/src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json new file mode 100644 index 0000000..185287b --- /dev/null +++ b/src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json @@ -0,0 +1,5 @@ +{ + "values": [ + "testmod:testblock" + ] +} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/block/wither_immune.json b/src/test/generated/resources/data/minecraft/tags/block/wither_immune.json new file mode 100644 index 0000000..185287b --- /dev/null +++ b/src/test/generated/resources/data/minecraft/tags/block/wither_immune.json @@ -0,0 +1,5 @@ +{ + "values": [ + "testmod:testblock" + ] +} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/entity_type/raiders.json b/src/test/generated/resources/data/minecraft/tags/entity_type/raiders.json new file mode 100644 index 0000000..c064704 --- /dev/null +++ b/src/test/generated/resources/data/minecraft/tags/entity_type/raiders.json @@ -0,0 +1,5 @@ +{ + "values": [ + "testmod:testentity" + ] +} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/item/beds.json b/src/test/generated/resources/data/minecraft/tags/item/beds.json new file mode 100644 index 0000000..8f30064 --- /dev/null +++ b/src/test/generated/resources/data/minecraft/tags/item/beds.json @@ -0,0 +1,5 @@ +{ + "values": [ + "testmod:testitem" + ] +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_campfire.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_campfire.json new file mode 100644 index 0000000..7c8f4ee --- /dev/null +++ b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_campfire.json @@ -0,0 +1,32 @@ +{ + "parent": "minecraft:recipes/root", + "criteria": { + "has_testblock": { + "conditions": { + "items": [ + { + "items": "testmod:testblock" + } + ] + }, + "trigger": "minecraft:inventory_changed" + }, + "has_the_recipe": { + "conditions": { + "recipe": "testmod:diamond_block_from_testblock_campfire" + }, + "trigger": "minecraft:recipe_unlocked" + } + }, + "requirements": [ + [ + "has_the_recipe", + "has_testblock" + ] + ], + "rewards": { + "recipes": [ + "testmod:diamond_block_from_testblock_campfire" + ] + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smelting.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smelting.json new file mode 100644 index 0000000..bbbad68 --- /dev/null +++ b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smelting.json @@ -0,0 +1,32 @@ +{ + "parent": "minecraft:recipes/root", + "criteria": { + "has_testblock": { + "conditions": { + "items": [ + { + "items": "testmod:testblock" + } + ] + }, + "trigger": "minecraft:inventory_changed" + }, + "has_the_recipe": { + "conditions": { + "recipe": "testmod:diamond_block_from_testblock_smelting" + }, + "trigger": "minecraft:recipe_unlocked" + } + }, + "requirements": [ + [ + "has_the_recipe", + "has_testblock" + ] + ], + "rewards": { + "recipes": [ + "testmod:diamond_block_from_testblock_smelting" + ] + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smoking.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smoking.json new file mode 100644 index 0000000..0cd3a34 --- /dev/null +++ b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smoking.json @@ -0,0 +1,32 @@ +{ + "parent": "minecraft:recipes/root", + "criteria": { + "has_testblock": { + "conditions": { + "items": [ + { + "items": "testmod:testblock" + } + ] + }, + "trigger": "minecraft:inventory_changed" + }, + "has_the_recipe": { + "conditions": { + "recipe": "testmod:diamond_block_from_testblock_smoking" + }, + "trigger": "minecraft:recipe_unlocked" + } + }, + "requirements": [ + [ + "has_the_recipe", + "has_testblock" + ] + ], + "rewards": { + "recipes": [ + "testmod:diamond_block_from_testblock_smoking" + ] + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/testblock.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/testblock.json new file mode 100644 index 0000000..950b7cc --- /dev/null +++ b/src/test/generated/resources/data/testmod/advancement/recipes/misc/testblock.json @@ -0,0 +1,32 @@ +{ + "parent": "minecraft:recipes/root", + "criteria": { + "has_egg": { + "conditions": { + "items": [ + { + "items": "minecraft:egg" + } + ] + }, + "trigger": "minecraft:inventory_changed" + }, + "has_the_recipe": { + "conditions": { + "recipe": "testmod:testblock" + }, + "trigger": "minecraft:recipe_unlocked" + } + }, + "requirements": [ + [ + "has_the_recipe", + "has_egg" + ] + ], + "rewards": { + "recipes": [ + "testmod:testblock" + ] + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/root.json b/src/test/generated/resources/data/testmod/advancement/root.json new file mode 100644 index 0000000..28d1f62 --- /dev/null +++ b/src/test/generated/resources/data/testmod/advancement/root.json @@ -0,0 +1,32 @@ +{ + "criteria": { + "has_egg": { + "conditions": { + "items": [ + { + "items": "minecraft:egg" + } + ] + }, + "trigger": "minecraft:inventory_changed" + } + }, + "display": { + "background": "minecraft:textures/gui/advancements/backgrounds/stone.png", + "description": { + "translate": "advancements.testmod.root.description" + }, + "icon": { + "id": "minecraft:egg" + }, + "title": { + "translate": "advancements.testmod.root.title" + } + }, + "requirements": [ + [ + "has_egg" + ] + ], + "sends_telemetry_event": true +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/dimension/test_dimension.json b/src/test/generated/resources/data/testmod/dimension/test_dimension.json new file mode 100644 index 0000000..06f6aa9 --- /dev/null +++ b/src/test/generated/resources/data/testmod/dimension/test_dimension.json @@ -0,0 +1,11 @@ +{ + "type": "testmod:test_dimension_type", + "generator": { + "type": "minecraft:noise", + "biome_source": { + "type": "minecraft:fixed", + "biome": "minecraft:plains" + }, + "settings": "minecraft:overworld" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json b/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json new file mode 100644 index 0000000..ff1f490 --- /dev/null +++ b/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json @@ -0,0 +1,55 @@ +{ + "ambient_light": 0.0, + "attributes": { + "minecraft:audio/ambient_sounds": { + "mood": { + "block_search_extent": 8, + "offset": 2.0, + "sound": "minecraft:ambient.cave", + "tick_delay": 6000 + } + }, + "minecraft:audio/background_music": { + "creative": { + "max_delay": 24000, + "min_delay": 12000, + "sound": "minecraft:music.creative" + }, + "default": { + "max_delay": 24000, + "min_delay": 12000, + "sound": "minecraft:music.game" + } + }, + "minecraft:gameplay/bed_rule": { + "can_set_spawn": "always", + "can_sleep": "when_dark", + "error_message": { + "translate": "block.minecraft.bed.no_sleep" + } + }, + "minecraft:gameplay/nether_portal_spawns_piglin": true, + "minecraft:gameplay/respawn_anchor_works": false, + "minecraft:visual/ambient_light_color": "#0a0a0a", + "minecraft:visual/cloud_color": "#ccffffff", + "minecraft:visual/cloud_height": 192.33, + "minecraft:visual/fog_color": "#c0d8ff", + "minecraft:visual/sky_color": "#78a7ff" + }, + "coordinate_scale": 1.0, + "default_clock": "minecraft:overworld", + "has_ceiling": false, + "has_ender_dragon_fight": false, + "has_skylight": true, + "height": 384, + "infiniburn": "#minecraft:infiniburn_overworld", + "logical_height": 384, + "min_y": -64, + "monster_spawn_block_light_limit": 0, + "monster_spawn_light_level": { + "type": "minecraft:uniform", + "max_inclusive": 7, + "min_inclusive": 0 + }, + "timelines": "#minecraft:in_overworld" +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/blocks/magic_item_model.json b/src/test/generated/resources/data/testmod/loot_table/blocks/magic_item_model.json new file mode 100644 index 0000000..e94ddd4 --- /dev/null +++ b/src/test/generated/resources/data/testmod/loot_table/blocks/magic_item_model.json @@ -0,0 +1,21 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "bonus_rolls": 0.0, + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } + ], + "entries": [ + { + "type": "minecraft:item", + "name": "testmod:magic_item_model" + } + ], + "rolls": 1.0 + } + ], + "random_sequence": "testmod:blocks/magic_item_model" +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/blocks/testblock.json b/src/test/generated/resources/data/testmod/loot_table/blocks/testblock.json new file mode 100644 index 0000000..ef4f7fc --- /dev/null +++ b/src/test/generated/resources/data/testmod/loot_table/blocks/testblock.json @@ -0,0 +1,21 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "bonus_rolls": 0.0, + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } + ], + "entries": [ + { + "type": "minecraft:item", + "name": "minecraft:diamond" + } + ], + "rolls": 1.0 + } + ], + "random_sequence": "testmod:blocks/testblock" +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/entities/testentity.json b/src/test/generated/resources/data/testmod/loot_table/entities/testentity.json new file mode 100644 index 0000000..3e34c66 --- /dev/null +++ b/src/test/generated/resources/data/testmod/loot_table/entities/testentity.json @@ -0,0 +1,36 @@ +{ + "type": "minecraft:entity", + "pools": [ + { + "bonus_rolls": 0.0, + "entries": [ + { + "type": "minecraft:item", + "functions": [ + { + "add": false, + "count": { + "type": "minecraft:uniform", + "max": 3.0, + "min": 1.0 + }, + "function": "minecraft:set_count" + }, + { + "count": { + "type": "minecraft:uniform", + "max": 2.0, + "min": 0.0 + }, + "enchantment": "minecraft:looting", + "function": "minecraft:enchanted_count_increase" + } + ], + "name": "minecraft:diamond" + } + ], + "rolls": 1.0 + } + ], + "random_sequence": "testmod:entities/testentity" +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/entities/testitem.json b/src/test/generated/resources/data/testmod/loot_table/entities/testitem.json new file mode 100644 index 0000000..058a463 --- /dev/null +++ b/src/test/generated/resources/data/testmod/loot_table/entities/testitem.json @@ -0,0 +1,4 @@ +{ + "type": "minecraft:entity", + "random_sequence": "testmod:entities/testitem" +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json new file mode 100644 index 0000000..66c260d --- /dev/null +++ b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json @@ -0,0 +1,10 @@ +{ + "type": "minecraft:campfire_cooking", + "category": "misc", + "cookingtime": 600, + "experience": 1.0, + "ingredient": "testmod:testblock", + "result": { + "id": "minecraft:diamond_block" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json new file mode 100644 index 0000000..4b5e4df --- /dev/null +++ b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json @@ -0,0 +1,10 @@ +{ + "type": "minecraft:smelting", + "category": "misc", + "cookingtime": 200, + "experience": 1.0, + "ingredient": "testmod:testblock", + "result": { + "id": "minecraft:diamond_block" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json new file mode 100644 index 0000000..69eed99 --- /dev/null +++ b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json @@ -0,0 +1,10 @@ +{ + "type": "minecraft:smoking", + "category": "misc", + "cookingtime": 100, + "experience": 1.0, + "ingredient": "testmod:testblock", + "result": { + "id": "minecraft:diamond_block" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/testblock.json b/src/test/generated/resources/data/testmod/recipe/testblock.json new file mode 100644 index 0000000..6e325d8 --- /dev/null +++ b/src/test/generated/resources/data/testmod/recipe/testblock.json @@ -0,0 +1,16 @@ +{ + "type": "minecraft:crafting_shaped", + "category": "misc", + "key": { + "D": "minecraft:diamond", + "E": "minecraft:egg" + }, + "pattern": [ + "DDD", + "DED", + "DDD" + ], + "result": { + "id": "testmod:testblock" + } +} \ No newline at end of file diff --git a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java b/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java new file mode 100644 index 0000000..9e7e6b4 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java @@ -0,0 +1,24 @@ +package com.modularmc.registrate.test.gametests; + +import com.modularmc.registrate.test.mod.TestMod; + +import net.neoforged.testframework.DynamicTest; +import net.neoforged.testframework.annotation.ForEachTest; +import net.neoforged.testframework.annotation.TestHolder; +import net.neoforged.testframework.gametest.EmptyTemplate; +import net.neoforged.testframework.gametest.GameTest; + +@ForEachTest(groups = "custom-item") +@SuppressWarnings("unused") +public class CustomItemTests { + + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = "Ensure custom item is registered and has the expected properties") + public static void ensureItemContent(final DynamicTest test) { + test.onGameTest(helper -> helper.startSequence(() -> TestMod.instance().testitem.asStack()) + .thenMap(stack -> stack.getItem().getDescriptionId()) + .thenExecute(descriptionId -> helper.assertValueEqual("item.testmod.testitem", descriptionId, "Test Item translation key")) + .thenSucceed()); + } +} diff --git a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java b/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java new file mode 100644 index 0000000..95e5eb3 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java @@ -0,0 +1,45 @@ +package com.modularmc.registrate.test.gametests; + +import com.modularmc.registrate.test.mod.TestMod; + +import net.minecraft.world.item.SpawnEggItem; +import net.neoforged.testframework.DynamicTest; +import net.neoforged.testframework.annotation.ForEachTest; +import net.neoforged.testframework.annotation.TestHolder; +import net.neoforged.testframework.gametest.EmptyTemplate; +import net.neoforged.testframework.gametest.GameTest; + +@ForEachTest(groups = "registrate-runtime") +@SuppressWarnings("unused") +public class RegistrationRuntimeTests { + + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = "Ensure block item lang reuse and fluid optional helpers behave as expected") + public static void ensureItemAndFluidHelpers(final DynamicTest test) { + test.onGameTest(helper -> helper.startSequence(() -> TestMod.instance().testblockitem.asStack().getItem().getDescriptionId()) + .thenExecute(blockItemDescriptionId -> { + helper.assertValueEqual(TestMod.instance().testblock.get().getDescriptionId(), blockItemDescriptionId, "Block item should reuse the block description key"); + helper.assertValueEqual(true, TestMod.instance().testfluid.getBlock().isEmpty(), "Fluid entry should return an empty block optional when no sibling exists"); + helper.assertValueEqual(true, TestMod.instance().testfluid.getBucket().isEmpty(), "Fluid entry should hide buckets when noBucket() is used"); + }) + .thenSucceed()); + } + + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = "Ensure auxiliary registrations remain available at runtime") + public static void ensureAuxiliaryRegistrations(final DynamicTest test) { + test.onGameTest(helper -> helper.startSequence(() -> TestMod.instance().testmenu.getId().getPath()) + .thenExecute(menuId -> { + helper.assertValueEqual("testmenu", menuId, "Menu registration path"); + helper.assertValueEqual("entity.testmod.testentity", TestMod.instance().testentity.get().getDescriptionId(), "Entity translation key"); + helper.assertValueEqual(TestMod.instance().testentity.get(), SpawnEggItem.getType(TestMod.instance().testentitySpawnEgg.asStack()), "Spawn egg should resolve to the registered entity type"); + helper.assertValueEqual("testitem", TestMod.instance().testduplicatename.getId().getPath(), "Duplicate-name entity registration path"); + helper.assertValueEqual("testblockentity", TestMod.instance().testblockentity.getId().getPath(), "Standalone block entity registration path"); + helper.assertValueEqual("testcustom", TestMod.instance().testcustom.getId().getPath(), "Custom registry entry path"); + helper.assertValueEqual("block.testmod.magic_item_model", TestMod.instance().magicItemModelTest.asStack().getItem().getDescriptionId(), "Magic item-model block description key"); + }) + .thenSucceed()); + } +} diff --git a/src/test/java/com/modularmc/registrate/test/gametests/package-info.java b/src/test/java/com/modularmc/registrate/test/gametests/package-info.java new file mode 100644 index 0000000..7ab2d70 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/gametests/package-info.java @@ -0,0 +1,5 @@ +/** + * Executable game tests that validate runtime behavior for the sample mod. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.test.gametests; diff --git a/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java b/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java new file mode 100644 index 0000000..8d73b9b --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java @@ -0,0 +1,103 @@ +package com.modularmc.registrate.test.meta; + +import com.modularmc.registrate.test.meta.ProtectedMethodScraper.Header; + +import com.google.common.collect.ImmutableList; +import lombok.RequiredArgsConstructor; +import lombok.Value; +import org.apache.commons.lang3.tuple.Pair; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +@RequiredArgsConstructor +public class MethodGenerator { + + @Value + private class Exclusion { + + String name; + String[] params; + + public boolean matches(Header header) { + if (!header.getName().equals(this.name)) { + return false; + } + return this.params == null ? true : Arrays.equals(header.getParamTypes(), this.params); + } + } + + private static final String START_KEY = "// GENERATED START"; + private static final String END_KEY = "// GENERATED END"; + + private final List> typeReplacements; + private final Set excludes = new HashSet<>(); + + private final Class mainClass; + + public MethodGenerator(Class mainClass) { + this(ImmutableList.of(), mainClass); + } + + public MethodGenerator exclude(String name) { + excludes.add(new Exclusion(name, null)); + return this; + } + + public MethodGenerator exclude(String name, String... paramTypes) { + excludes.add(new Exclusion(name, paramTypes)); + return this; + } + + public void generate(Path output) throws IOException { + List currentSource = Files.readAllLines(output, StandardCharsets.UTF_8); + List

newHeaders = ProtectedMethodScraper.scrapeInput(); + ListIterator
headerItr = newHeaders.listIterator(); + while (headerItr.hasNext()) { + Header header = headerItr.next(); + for (Pair repl : typeReplacements) { + header = header.applyTypeReplacement(repl); + } + headerItr.set(header); + } + ListIterator itr = currentSource.listIterator(); + while (itr.hasNext()) { + int index = itr.nextIndex(); + String line = itr.next(); + if (line.contains(START_KEY)) { + itr.remove(); + while (itr.hasNext()) { + if (!itr.next().contains(END_KEY)) { + itr.remove(); + } else { + itr.remove(); + itr = currentSource.listIterator(index); + break; + } + } + itr.add(line); + for (Header header : newHeaders) { + if (excludes.stream().anyMatch(e -> e.matches(header))) continue; + itr.add(""); + for (String s : header.printStubMethod(mainClass).split("\n")) { + itr.add(" " + s); + } + } + itr.add(""); + itr.add(" " + END_KEY); + break; + } + } + Files.write(output, currentSource); + System.out.print("Updated source code: " + Paths.get("src/main/java").relativize(output).toString().replace(File.separator, ".").replace(".java", "")); + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java b/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java new file mode 100644 index 0000000..739833a --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java @@ -0,0 +1,127 @@ +package com.modularmc.registrate.test.meta; + +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import lombok.Value; +import org.apache.commons.lang3.tuple.Pair; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Scrapes all protected methods from pasted source, and emits them as public super-calling stubs. Used to create the + * bouncer classes such as BuilderModelProvider. + */ +public class ProtectedMethodScraper { + + @Value + @RequiredArgsConstructor(access = AccessLevel.PRIVATE) + public static class Header { + + String className; + boolean isStatic; + String generics; + String type; + String name; + String[] paramTypes; + String[] paramNames; + + public Header applyTypeReplacement(Pair repl) { + String[] newParamTypes = Arrays.copyOf(paramTypes, paramTypes.length); + for (int i = 0; i < newParamTypes.length; i++) { + if (newParamTypes[i].equals(repl.getKey())) { + newParamTypes[i] = repl.getValue(); + } + } + String type = this.type.equals(repl.getKey()) ? repl.getValue() : this.type; + return new Header(this.className, this.isStatic, this.generics, type, this.name, newParamTypes, this.paramNames); + } + + public String printStubMethod(Class source) { + StringBuilder base = new StringBuilder(); + base.append("/** Generated override to expose protected method: {@link ").append(className).append("#").append(name).append("} */\n"); + if (!isStatic) { + base.append("@Override\n"); + } + base.append("@Generated(value = \"").append(source.getName()).append("\", date = \"") + .append(DateTimeFormatter.RFC_1123_DATE_TIME.format(Instant.now().atZone(ZoneOffset.UTC))).append("\")\n"); + base.append("public ").append(isStatic ? "static " : ""); + if (generics != null) { + base.append(generics).append(" "); + } + base.append(type).append(" ").append(name).append("("); + for (int i = 0; i < paramTypes.length; i++) { + if (i > 0) { + base.append(", "); + } + base.append(paramTypes[i]).append(" ").append(paramNames[i]); + } + base.append(") { ").append(type.equals("void") ? "" : "return "); + if (isStatic) { + base.append(className).append("."); + } else { + base.append("super."); + } + base.append(name).append("(").append(Arrays.stream(paramNames).collect(Collectors.joining(", "))).append("); }"); + return base.toString(); + } + + // Match generics up to three levels deep -- java does not support recursive patterns + private static final Pattern HEADER_PATTERN = Pattern.compile("^\\s*protected\\s+(?:(static)\\s)?\\s*(<[^<>]+(?:<[^<>]+(?:<[^<>]+>[^<>]*)*>[^<>]*)*>)?\\s*(\\S+)\\s+(\\S+)\\((.+)\\)\\s\\{$"); + private static final Pattern PARAM_PATTERN = Pattern.compile("([a-zA-Z_][\\w.$]+(?:<.+>)?)\\s+(\\S+)"); + + public static Optional
parse(String className, String code) { + Matcher h = HEADER_PATTERN.matcher(code); + if (h.matches()) { + boolean isStatic = h.group(1) != null; + String generics = h.group(2); + String type = h.group(3); + String name = h.group(4); + String params = h.group(5); + String[] paramList = params.split(","); + String[] paramTypes = new String[paramList.length]; + String[] paramNames = new String[paramList.length]; + for (int i = 0; i < paramList.length; i++) { + String param = paramList[i].trim(); + Matcher p = PARAM_PATTERN.matcher(param); + if (p.matches()) { + paramTypes[i] = p.group(1); + paramNames[i] = p.group(2); + } else { + return Optional.empty(); + } + } + return Optional.of(new Header(className, isStatic, generics, type, name, paramTypes, paramNames)); + } + return Optional.empty(); + } + } + + public static List
scrapeInput() { + @SuppressWarnings("resource") + Scanner scanner = new Scanner(System.in); + System.out.println("Paste class source:"); + String line = scanner.nextLine(); + List
headers = new ArrayList<>(); + String className = null; + do { + if (className != null) { + Header.parse(className, line).ifPresent(headers::add); + } else if (line.startsWith("public class ") || line.startsWith("public abstract class")) { + className = line.replaceAll("public (abstract )?class ", "").split("\\s+")[0]; + } + line = scanner.nextLine(); + } while (!"done".equals(line) && !"}".equals(line)); + System.out.println("Text processed! Found " + headers.size() + " methods to generate."); + return headers; + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java b/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java new file mode 100644 index 0000000..83e9cdf --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java @@ -0,0 +1,12 @@ +package com.modularmc.registrate.test.meta; + +import java.io.IOException; +import java.nio.file.Paths; + +public class UpdateBlockLootTables { + + public static void main(String[] args) throws IOException { + new MethodGenerator(UpdateBlockLootTables.class) + .generate(Paths.get("src", "main", "java", "com", "tterrag", "registrate", "providers", "loot", "RegistrateBlockLootTables.java")); + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java b/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java new file mode 100644 index 0000000..b441f03 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java @@ -0,0 +1,13 @@ +package com.modularmc.registrate.test.meta; + +import java.io.IOException; +import java.nio.file.Paths; + +public class UpdateEntityLootTables { + + public static void main(String[] args) throws IOException { + new MethodGenerator(UpdateEntityLootTables.class) + .exclude("isNonLiving").exclude("getKnownEntities") + .generate(Paths.get("src", "main", "java", "com", "tterrag", "registrate", "providers", "loot", "RegistrateEntityLootTables.java")); + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java b/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java new file mode 100644 index 0000000..105799f --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java @@ -0,0 +1,13 @@ +package com.modularmc.registrate.test.meta; + +import java.io.IOException; +import java.nio.file.Paths; + +public class UpdateRecipeProvider { + + public static void main(String[] args) throws IOException { + new MethodGenerator(UpdateRecipeProvider.class) + .exclude("buildCraftingRecipes") + .generate(Paths.get("src", "main", "java", "com", "tterrag", "registrate", "providers", "generators", "RegistrateRecipeProvider.java")); + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/package-info.java b/src/test/java/com/modularmc/registrate/test/meta/package-info.java new file mode 100644 index 0000000..150891c --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/package-info.java @@ -0,0 +1,8 @@ +/** + * Maintenance helpers for generated bridge methods and protected API snapshots. + * + *

+ * These tests support source upkeep rather than runtime game behavior. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.test.meta; diff --git a/src/test/java/com/modularmc/registrate/test/mod/TestMod.java b/src/test/java/com/modularmc/registrate/test/mod/TestMod.java new file mode 100644 index 0000000..4c3c3fb --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/mod/TestMod.java @@ -0,0 +1,481 @@ +package com.modularmc.registrate.test.mod; + +import com.modularmc.registrate.Registrate; +import com.modularmc.registrate.builders.BlockBuilder; +import com.modularmc.registrate.providers.DataGenContext; +import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator; +import com.modularmc.registrate.util.DataIngredient; +import com.modularmc.registrate.util.entry.*; + +import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementType; +import net.minecraft.advancements.criterion.InventoryChangeTrigger; +import net.minecraft.client.color.block.BlockTintSources; +import net.minecraft.client.color.item.Constant; +import net.minecraft.client.data.models.model.ModelTemplates; +import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.client.gui.screens.inventory.ContainerScreen; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; +import net.minecraft.client.renderer.blockentity.state.BlockEntityRenderState; +import net.minecraft.client.renderer.entity.PigRenderer; +import net.minecraft.client.renderer.entity.state.EntityRenderState; +import net.minecraft.client.renderer.feature.ModelFeatureRenderer; +import net.minecraft.client.renderer.item.ItemModelResolver; +import net.minecraft.client.renderer.item.ItemStackRenderState; +import net.minecraft.client.renderer.state.level.CameraRenderState; +import net.minecraft.client.renderer.texture.OverlayTexture; +import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistrySetBuilder; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.worldgen.biome.OverworldBiomes; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.EntityTypeTags; +import net.minecraft.tags.ItemTags; +import net.minecraft.tags.TimelineTags; +import net.minecraft.util.ARGB; +import net.minecraft.util.valueproviders.UniformInt; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.attribute.*; +import net.minecraft.world.clock.WorldClocks; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.entity.SpawnPlacementTypes; +import net.minecraft.world.entity.animal.Animal; +import net.minecraft.world.entity.animal.pig.Pig; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.food.FoodProperties; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ChestMenu; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.*; +import net.minecraft.world.item.crafting.CookingBookCategory; +import net.minecraft.world.level.CardinalLighting; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.Biomes; +import net.minecraft.world.level.biome.FixedBiomeSource; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.entity.ChestBlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.StateDefinition.Builder; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import net.minecraft.world.level.storage.loot.LootPool; +import net.minecraft.world.level.storage.loot.LootTable; +import net.minecraft.world.level.storage.loot.entries.LootItem; +import net.minecraft.world.level.storage.loot.functions.EnchantedCountIncreaseFunction; +import net.minecraft.world.level.storage.loot.functions.SetItemCountFunction; +import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; +import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.common.data.DatapackBuiltinEntriesProvider; +import net.neoforged.neoforge.event.RegisterCommandsEvent; +import net.neoforged.neoforge.event.entity.RegisterSpawnPlacementsEvent; +import net.neoforged.neoforge.fluids.BaseFlowingFluid; +import net.neoforged.neoforge.fluids.FluidType; +import net.neoforged.neoforge.registries.RegistryBuilder; +import net.neoforged.testframework.conf.ClientConfiguration; +import net.neoforged.testframework.conf.Feature; +import net.neoforged.testframework.conf.FrameworkConfiguration; +import net.neoforged.testframework.impl.MutableTestFramework; + +import com.google.common.annotations.VisibleForTesting; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import org.lwjgl.glfw.GLFW; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.annotation.Nullable; + +@Mod(TestMod.MOD_ID) +public class TestMod { + + public static final String MOD_ID = "testmod"; + + public static final class TestBlock extends Block implements EntityBlock { + + public TestBlock(Properties properties) { + super(properties); + } + + @Override + protected void createBlockStateDefinition(Builder builder) { + super.createBlockStateDefinition(builder); + builder.add(BlockStateProperties.CHEST_TYPE); + } + + @Override + protected InteractionResult useWithoutItem(BlockState state, Level worldIn, BlockPos pos, Player player, BlockHitResult hit) { + if (!worldIn.isClientSide()) { + player.openMenu(new MenuProvider() { + + @Override + public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { + return new ChestMenu(MenuType.GENERIC_9x3, windowId, inv, TestMod.instance().testblockbe.get(worldIn, pos).orElseThrow(IllegalStateException::new), 3); + } + + @Override + public Component getDisplayName() { + return Component.literal("Test"); + } + }); + } + return InteractionResult.SUCCESS; + } + + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { + return TestMod.instance().testblockbe.create(pos, state); + } + } + + private static class TestBlockEntity extends ChestBlockEntity { + + public TestBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); + } + } + + private static class TestBlockEntityRenderer implements BlockEntityRenderer { + + private final ItemModelResolver itemModelResolver; + + public TestBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { + itemModelResolver = ctx.itemModelResolver(); + } + + @Override + public RenderState createRenderState() { + return new RenderState(); + } + + @Override + public void extractRenderState(TestBlockEntity blockEntity, RenderState state, float partialTicks, Vec3 cameraPosition, @Nullable ModelFeatureRenderer.CrumblingOverlay breakProgress) { + BlockEntityRenderer.super.extractRenderState(blockEntity, state, partialTicks, cameraPosition, breakProgress); + itemModelResolver.updateForTopItem(state.item, new ItemStack(Items.DIAMOND), ItemDisplayContext.GROUND, blockEntity.getLevel(), null, 0); + } + + @Override + public void submit(RenderState state, PoseStack poseStack, SubmitNodeCollector submitNodeCollector, CameraRenderState camera) { + poseStack.pushPose(); + poseStack.translate(0.5, 0.5, 0.5); + state.item.submit(poseStack, submitNodeCollector, state.lightCoords, OverlayTexture.NO_OVERLAY, EntityRenderState.NO_OUTLINE); + poseStack.popPose(); + } + + private static class RenderState extends BlockEntityRenderState { + + private final ItemStackRenderState item = new ItemStackRenderState(); + } + } + + public static final class TestDummyBlockEntity extends BlockEntity { + + public TestDummyBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); + } + } + + public static final class TestEntity extends Pig { + + public TestEntity(EntityType p_i50250_1_, Level p_i50250_2_) { + super(p_i50250_1_, p_i50250_2_); + } + } + + public static final class TestCustomRegistryEntry {} + + private final Registrate registrate = Registrate.create("testmod"); + + @VisibleForTesting + public final RegistryEntry testcreativetab = registrate.object("test_creative_mode_tab") + .defaultCreativeTab(tab -> tab.withLabelColor(0xFF00AA00)) + .register(); + + private final AtomicBoolean sawCallback = new AtomicBoolean(); + + @VisibleForTesting + public final ItemEntry testitem = registrate.object("testitem") + .item(Item::new) + .onRegister(ignored -> sawCallback.set(true)) + .properties(p -> p.food(new FoodProperties.Builder().nutrition(1).saturationModifier(0.2f).build())) + .tag(ItemTags.BEDS) + .model(() -> (ctx, prov) -> prov.createWithExistingModel(ctx.getEntry(), prov.mcLoc("block/stone"))) + .tab(testcreativetab.getKey(), (ctx, modifier) -> modifier.accept(ctx)) + .register(); + + @VisibleForTesting + public final EntityEntry testduplicatename = registrate.object("testitem") + .entity(TestEntity::new, MobCategory.CREATURE) + .attributes(Pig::createAttributes) + .loot((tb, e) -> tb.add(e, LootTable.lootTable())) + .renderer(() -> PigRenderer::new) + .register(); + + @VisibleForTesting + public final BlockEntry testblock = registrate.object("testblock") + .block(TestBlock::new) + .properties(BlockBehaviour.Properties::noOcclusion) + .blockstate(() -> (ctx, prov) -> prov.create(ctx.getEntry(), prov.mcLoc("block/glass"))) + .transform(TestMod::applyDiamondDrop) + .recipe((ctx, prov) -> { + prov.shaped(RecipeCategory.MISC, ctx.getEntry()) + .pattern("DDD").pattern("DED").pattern("DDD") + .define('D', Items.DIAMOND) + .define('E', Items.EGG) + .unlockedBy("has_egg", prov.has(Items.EGG)) + .save(prov); + + prov.food(DataIngredient.items(ctx), RecipeCategory.MISC, CookingBookCategory.MISC, () -> Blocks.DIAMOND_BLOCK, 1f); + }) + .tag(BlockTags.SUPPORTS_BAMBOO, BlockTags.DRAGON_IMMUNE) + .tag(BlockTags.WITHER_IMMUNE) + .color(() -> () -> List.of(BlockTintSources.constant(0xFFFF0000))) + .item() + .model(() -> Client::testBlockModel) + .build() + .blockEntity(TestBlockEntity::new) + .renderer(() -> TestBlockEntityRenderer::new) + .build() + .register(); + + @VisibleForTesting + public final BlockEntry magicItemModelTest = registrate.object("magic_item_model") + .block(Block::new) + .blockstate(() -> (ctx, prov) -> prov.create( + ctx.getEntry(), + ModelTemplates.CUBE_ALL.create( + prov.modLoc("block/subfolder/" + ctx.getName()), + TextureMapping.cube(prov.mcBlockTexture("gold_block")), + prov.modelOutput))) + .simpleItem() + .register(); + + @VisibleForTesting + public final ItemEntry testblockitem = (ItemEntry) testblock.getSibling(Registries.ITEM); + @VisibleForTesting + public final BlockEntityEntry testblockbe = BlockEntityEntry.cast(testblock.getSibling(Registries.BLOCK_ENTITY_TYPE)); + + @VisibleForTesting + public final EntityEntry testentity = registrate.object("testentity") + .entity(TestEntity::new, MobCategory.CREATURE) + .attributes(Pig::createAttributes) + .renderer(() -> PigRenderer::new) + .spawnPlacement(SpawnPlacementTypes.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules, RegisterSpawnPlacementsEvent.Operation.OR) + .spawnEgg(egg -> egg.model(() -> (ctx, prov) -> prov.generateFlatItem(ctx.getEntry(), new Material(Identifier.fromNamespaceAndPath(MOD_ID, "item/testentity_spawn_egg"))))) + .loot((prov, type) -> prov.add(type, LootTable.lootTable() + .withPool(LootPool.lootPool() + .setRolls(ConstantValue.exactly(1)) + .add(LootItem.lootTableItem(Items.DIAMOND) + .apply(SetItemCountFunction.setCount(UniformGenerator.between(1, 3))) + .apply(EnchantedCountIncreaseFunction.lootingMultiplier(prov.getRegistries(), UniformGenerator.between(0, 2))))))) + .tag(EntityTypeTags.RAIDERS) + .register(); + @VisibleForTesting + public final ItemEntry testentitySpawnEgg = ItemEntry.cast(registrate.get("testentity_spawn_egg", Registries.ITEM)); + + @VisibleForTesting + public final BlockEntityEntry testblockentity = registrate.object("testblockentity") + .blockEntity(TestDummyBlockEntity::new) + .validBlock(() -> Blocks.DIRT) + .register(); + + @VisibleForTesting + public final FluidEntry testfluid = registrate.object("testfluid") + .fluid( + Identifier.withDefaultNamespace("block/water_flow"), + Identifier.withDefaultNamespace("block/lava_still"), + FluidType::new) + .properties(p -> p.lightLevel(15).canConvertToSource(true)) + .noBucket() + .register(); + + @VisibleForTesting + public final FluidEntry testbucketfluid = registrate.object("testbucketfluid") + .fluid( + Identifier.withDefaultNamespace("block/water_still"), + Identifier.withDefaultNamespace("block/water_flow"), + FluidType::new) + .properties(p -> p.lightLevel(7).canConvertToSource(true)) + .register(); + + @VisibleForTesting + public final MenuEntry testmenu = registrate.object("testmenu") + .menu((type, windowId, inv) -> new ChestMenu(type, windowId, inv, new SimpleContainer(9 * 9), 9), () -> ContainerScreen::new) + .register(); + + @VisibleForTesting + public final ResourceKey> CUSTOM_REGISTRY = registrate.makeRegistry("custom", RegistryBuilder::new); + @VisibleForTesting + public final RegistryEntry testcustom = registrate.object("testcustom") + .simple(CUSTOM_REGISTRY, TestCustomRegistryEntry::new); + + private static BlockBuilder applyDiamondDrop(BlockBuilder builder) { + return builder.loot((prov, block) -> prov.dropOther(block, Items.DIAMOND)); + } + + private static @Nullable TestMod INSTANCE = null; + + public TestMod(IEventBus eventBus, ModContainer container) { + INSTANCE = this; + + registrate.addRawLang("testmod.custom.lang", "Test"); + registrate.addRawLang("testmod.custom.lang.with_placeholders1", "Placeholder 1 %s Placeholder 2 %s"); + registrate.addRawLang("testmod.custom.lang.with_placeholders2", "Placeholder 1 %s Placeholder 2 %2$s Placeholder 3 %s"); + registrate.addRawLang("testmod.custom.lang.brackets", "(Bracket 1) [Bracket 2] {Bracket 3} ◁Bracket 5▷"); + registrate.addRawLang("testmod.custom.lang.slashes", "/commmands look good and here is a backslash \\"); + registrate.addLang("tooltip", testblock.getId(), "Egg."); + registrate.addLang("item", testitem.getId(), "testextra", "Magic!"); + registrate.addDataGenerator(ProviderType.ADVANCEMENT, adv -> Advancement.Builder.advancement() + .addCriterion("has_egg", InventoryChangeTrigger.TriggerInstance.hasItems(Items.EGG)) + .display(Items.EGG, + adv.title(registrate.getModid(), "root", "Test Advancement"), adv.desc(registrate.getModid(), "root", "Get an egg."), + Identifier.withDefaultNamespace("textures/gui/advancements/backgrounds/stone.png"), AdvancementType.TASK, true, true, false) + .save(adv, registrate.getModid() + ":root")); + registrate.addDataGenerator(ProviderType.GENERIC_SERVER, provider -> provider.add(data -> { + // generic server side provider to generate custom dimension + // to teleport to this dimension use the following command + // /execute as @s in testmod:test_dimension run tp @s 0 64 0 + // you can validate you are in this dimension by checking the debug screen + // right underneath the `Chunks[C]` and `Chunk[S]` should be the dimension name + var testDimensionTypeKey = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.fromNamespaceAndPath("testmod", "test_dimension_type")); + + return new DatapackBuiltinEntriesProvider( + data.output(), + data.registries(), + new RegistrySetBuilder() + // custom dimension type, just a simple overworld-like dimension + .add(Registries.DIMENSION_TYPE, context -> context.register( + testDimensionTypeKey, + new DimensionType( + /* hasFixedTime */ false, + /* hasSky */ true, + /* hasCeiling */ false, + /* hasEnderDragonFight */ false, + /* coordinateScale */ 1D, + /* minY */ -64, + /* height */ 384, + /* localHeight */ 384, + /* infiniBurn */ BlockTags.INFINIBURN_OVERWORLD, + /* ambientLight */ 0F, + new DimensionType.MonsterSettings( + /* monsterSpawnLightTest */ UniformInt.of(0, 7), + /* monsterSpawnBlockLightLimit */ 0), + DimensionType.Skybox.OVERWORLD, + CardinalLighting.Type.DEFAULT, + EnvironmentAttributeMap.builder() + .set(EnvironmentAttributes.FOG_COLOR, 0xffc0d8ff) + .set(EnvironmentAttributes.SKY_COLOR, OverworldBiomes.calculateSkyColor(0.8F)) + .set(EnvironmentAttributes.AMBIENT_LIGHT_COLOR, 0xff0a0a0a) + .set(EnvironmentAttributes.CLOUD_COLOR, ARGB.white(0.8F)) + .set(EnvironmentAttributes.CLOUD_HEIGHT, 192.33f) + .set(EnvironmentAttributes.BACKGROUND_MUSIC, BackgroundMusic.OVERWORLD) + .set(EnvironmentAttributes.BED_RULE, BedRule.CAN_SLEEP_WHEN_DARK) + .set(EnvironmentAttributes.RESPAWN_ANCHOR_WORKS, false) + .set(EnvironmentAttributes.NETHER_PORTAL_SPAWNS_PIGLINS, true) + .set(EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.LEGACY_CAVE_SETTINGS) + .build(), + context.lookup(Registries.TIMELINE).getOrThrow(TimelineTags.IN_OVERWORLD), + Optional.of(context.lookup(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD))))) + // register custom dimension for the dimension type + // simple single biome (plains) dimension + .add(Registries.LEVEL_STEM, context -> { + var plains = context.lookup(Registries.BIOME).getOrThrow(Biomes.PLAINS); + var testDimensionType = context.lookup(Registries.DIMENSION_TYPE).getOrThrow(testDimensionTypeKey); + var overworldNoiseSettings = context.lookup(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD); + + context.register( + ResourceKey.create(Registries.LEVEL_STEM, Identifier.fromNamespaceAndPath("testmod", "test_dimension")), + new LevelStem( + testDimensionType, + new NoiseBasedChunkGenerator( + new FixedBiomeSource(plains), + overworldNoiseSettings))); + }), + Set.of("testmod")); + })); + + eventBus.addListener(this::onCommonSetup); + + // Setup gametests for normal run config + final MutableTestFramework framework = FrameworkConfiguration + .builder(Identifier.fromNamespaceAndPath(MOD_ID, "tests")) + .clientConfiguration(() -> ClientConfiguration.builder() + .toggleOverlayKey(GLFW.GLFW_KEY_O) + .openManagerKey(GLFW.GLFW_KEY_M) + .build()) + .enable(Feature.CLIENT_SYNC, Feature.TEST_STORE) + .build() + .create(); + + framework.init(eventBus, container); + + NeoForge.EVENT_BUS.addListener((final RegisterCommandsEvent event) -> { + final LiteralArgumentBuilder node = Commands.literal("tests"); + framework.registerCommands(node); + event.getDispatcher().register(node); + }); + } + + private void onCommonSetup(FMLCommonSetupEvent event) { + if (!sawCallback.get()) { + throw new IllegalStateException("Register callback not fired!"); + } + + testblock.asStackTemplate(); + testitem.is(Items.SNOWBALL); + testblockitem.is(Items.STONE); + testblockbe.is(BlockEntityType.CHEST); + // testbiome.is(Feature.BAMBOO); // should not compile + if (testfluid.getBucket().isPresent()) throw new IllegalStateException("Expected no bucket entry for test fluid"); + if (testfluid.getSiblingOptional(Registries.ITEM).isPresent()) throw new IllegalStateException("Expected no item sibling for test fluid"); + if (testfluid.getBlock().isPresent()) throw new IllegalStateException("Expected no block sibling for test fluid"); + if (testfluid.getSource().getSource() != testfluid.getSource()) throw new IllegalStateException("Expected canonical fluid source"); + if (testbucketfluid.getBucket().isEmpty()) throw new IllegalStateException("Expected a generated bucket entry for test bucket fluid"); + } + + private static class Client { + + private static void testBlockModel(DataGenContext ctx, RegistrateItemModelGenerator prov) { + prov.generateTintedModel(ctx.get(), prov.mcLoc("item/egg"), new Constant(0xFFFF0000)); + } + } + + public static TestMod instance() { + Objects.requireNonNull(INSTANCE, "Attempting to get mod instance before mod construction"); + return INSTANCE; + } +} diff --git a/src/test/java/com/modularmc/registrate/test/mod/package-info.java b/src/test/java/com/modularmc/registrate/test/mod/package-info.java new file mode 100644 index 0000000..c111488 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/mod/package-info.java @@ -0,0 +1,5 @@ +/** + * Sample mod sources used as an integration harness for the public API. + */ +@org.jspecify.annotations.NullMarked +package com.modularmc.registrate.test.mod; diff --git a/src/test/resources/META-INF/neoforge.mods.toml b/src/test/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..ea4e5ea --- /dev/null +++ b/src/test/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,45 @@ +# This is an example mods.toml file. It contains the data relating to the loading mods. +# There are several mandatory fields (#mandatory), and many more that are optional (#optional). +# The overall format is standard TOML format, v0.5.0. +# Note that there are a couple of TOML lists in this file. +# Find more information on toml format here: https://github.com/toml-lang/toml +# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml +modLoader="javafml" #mandatory +# A version range to match for said mod loader - for regular FML @Mod it will be the forge version +loaderVersion="[2,)" #mandatory (2 is current neoforge version) +# A URL to refer people to when problems occur with this mod +issueTrackerURL="http://my.issue.tracker/" #optional +license="MPL 2.0" +# A list of mods - how many allowed here is determined by the individual mod loader +[[mods]] #mandatory +# The modid of the mod +modId="testmod" #mandatory +# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it +version="${file.jarVersion}" #mandatory + # A display name for the mod +displayName="Test Mod" #mandatory +# A URL to query for updates for this mod. See the JSON update specification +#updateJSONURL="http://myurl.me/" #optional +# A URL for the "homepage" for this mod, displayed in the mod UI +#displayURL="https://.net" #optional +# A file name (in the root of the mod JAR) containing a logo for display +#logoFile="examplemod.png" #optional +# A text field displayed in the mod UI +#credits="" #optional +# A text field displayed in the mod UI +#authors="Cojomax99, Corosus, tterrag, Mr_okushama, MrRube, etc" #optional +# The description text for the mod (multi line!) (#mandatory) +description=''' +This is a long form description of the mod. You can write whatever you want here + +Have some lorem ipsum. + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mollis lacinia magna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed sagittis luctus odio eu tempus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque volutpat ligula eget lacus auctor sagittis. In hac habitasse platea dictumst. Nunc gravida elit vitae sem vehicula efficitur. Donec mattis ipsum et arcu lobortis, eleifend sagittis sem rutrum. Cras pharetra quam eget posuere fermentum. Sed id tincidunt justo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. +''' + +[[dependencies.testmod]] +modId="registratelib" +type="required" +versionRange="[2.0.0,)" +ordering="AFTER" +side="BOTH" diff --git a/src/test/resources/assets/testmod/textures/item/testentity_spawn_egg.png b/src/test/resources/assets/testmod/textures/item/testentity_spawn_egg.png new file mode 100644 index 0000000000000000000000000000000000000000..2831ddeb2f666f4a6249c40739ac8dc41114e6ec GIT binary patch literal 220 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|SkfJR9T^xl z_H+M9WCij$3p^r=85sBugD~Uq{1quc!9q_L#}Etut$i1H8x(k0XC4ofIm#bi;Lv`^ zBj}RMdQ+ELPx}X7`MiE=AKw{j|K_m7hV|aFH7BwwH{P8r8yCh@7IYxBRGpP8V8dMY z3EVQ@E;IRw2OK%-;kQqQb|Mhjx<(DK=_L+Q%XeMTp8}LKU={X#J@LR!@WDq9cEB06nRYW-Ki7!k>LEmC9>5w#A zNTDcCJvmQ6Hve=NN52Cy=*ar5!XNVu>wGlB)!xjmG0R|W0)evP(vo48%GNgW3Sa?6O-B_~HFb?tE$s}jfUbbPfnlDpiK&^n1z14DN|fK$ z&fbB;$(ai*;OgcsD(vay&B5U#2o_-S^AF(X3 Date: Fri, 20 Nov 2026 16:02:37 +0800 Subject: [PATCH 2/7] =?UTF-8?q?=E9=80=82=E9=85=8D=20Minecraft=201.21.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/build_setup/action.yml | 2 +- build.gradle | 40 +- dependencies.gradle | 1 + gradle/libs.versions.toml | 9 +- gradle/scripts/moddevgradle.gradle | 32 +- gradle/scripts/repositories.gradle | 3 + gradle/scripts/resources.gradle | 4 +- .../registrate/AbstractRegistrate.java | 90 +-- .../registrate/builders/BlockBuilder.java | 52 +- .../builders/BlockEntityBuilder.java | 10 +- .../registrate/builders/EntityBuilder.java | 32 +- .../registrate/builders/FluidBuilder.java | 101 ++- .../registrate/builders/ItemBuilder.java | 32 +- .../builders/base/AbstractBuilder.java | 6 +- .../internal/RegistrationTracker.java | 24 +- .../datagen/RegistrateDatagenBootstrap.java | 22 - .../lifecycle/RegistrateLifecycle.java | 13 +- .../internal/util/RegistrateDistExecutor.java | 2 +- .../registrate/providers/DataGenContext.java | 6 +- .../RegistrateAdvancementProvider.java | 8 +- .../providers/RegistrateItemTagsProvider.java | 8 +- .../providers/RegistrateLangProvider.java | 2 +- .../providers/RegistrateTagsProvider.java | 29 +- .../providers/core/ProviderType.java | 38 +- .../core/RegistrateDataProvider.java | 25 +- .../core/RegistrateProviderDelegate.java | 4 +- .../RegistrateBlockModelGenerator.java | 536 ++------------- .../RegistrateItemModelGenerator.java | 116 ++-- .../RegistrateLegacyBlockModelBuilder.java | 126 ---- .../generators/RegistrateModelProvider.java | 31 +- .../generators/RegistrateRecipeProvider.java | 642 ++++++++---------- .../generators/RegistrateRecipeRunner.java | 45 -- .../loot/RegistrateBlockLootTables.java | 178 +++-- .../loot/RegistrateEntityLootTables.java | 26 +- .../loot/RegistrateLootTableProvider.java | 34 +- .../providers/loot/RegistrateLootTables.java | 9 +- .../registrate/util/DataIngredient.java | 24 +- .../registrate/util/entry/EntityEntry.java | 5 +- .../util/entry/ItemProviderEntry.java | 9 - .../testmod/items/magic_item_model.json | 6 - .../assets/testmod/items/testblock.json | 12 - .../testmod/items/testbucketfluid_bucket.json | 12 - .../testmod/items/testentity_spawn_egg.json | 6 - .../assets/testmod/items/testitem.json | 6 - .../testmod/models/item/magic_item_model.json | 3 + .../assets/testmod/models/item/testblock.json | 3 + .../models/item/testbucketfluid_bucket.json | 11 + .../assets/testmod/models/item/testitem.json | 3 + ...s_bamboo.json => bamboo_plantable_on.json} | 0 .../data/testmod/advancement/root.json | 1 + .../dimension_type/test_dimension_type.json | 46 +- ...diamond_block_from_testblock_campfire.json | 7 +- ...diamond_block_from_testblock_smelting.json | 7 +- .../diamond_block_from_testblock_smoking.json | 7 +- .../data/testmod/recipe/testblock.json | 9 +- .../test/gametests/CustomItemTests.java | 2 +- .../gametests/RegistrationRuntimeTests.java | 5 +- .../registrate/test/mod/TestMod.java | 137 +--- src/test/resources/pack.mcmeta | 8 +- 59 files changed, 865 insertions(+), 1802 deletions(-) delete mode 100644 src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java delete mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java delete mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java delete mode 100644 src/test/generated/resources/assets/testmod/items/magic_item_model.json delete mode 100644 src/test/generated/resources/assets/testmod/items/testblock.json delete mode 100644 src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json delete mode 100644 src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json delete mode 100644 src/test/generated/resources/assets/testmod/items/testitem.json create mode 100644 src/test/generated/resources/assets/testmod/models/item/magic_item_model.json create mode 100644 src/test/generated/resources/assets/testmod/models/item/testblock.json create mode 100644 src/test/generated/resources/assets/testmod/models/item/testbucketfluid_bucket.json create mode 100644 src/test/generated/resources/assets/testmod/models/item/testitem.json rename src/test/generated/resources/data/minecraft/tags/block/{supports_bamboo.json => bamboo_plantable_on.json} (100%) diff --git a/.github/actions/build_setup/action.yml b/.github/actions/build_setup/action.yml index c1bf4ed..cda90ea 100644 --- a/.github/actions/build_setup/action.yml +++ b/.github/actions/build_setup/action.yml @@ -22,7 +22,7 @@ runs: REF: ${{ inputs.ref || github.ref }} with: distribution: temurin - java-version: 25 + java-version: 21 - name: Setup Gradle uses: gradle/actions/setup-gradle@v4 diff --git a/build.gradle b/build.gradle index 80cd051..5499a08 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,6 @@ plugins { id 'eclipse' id 'idea' id 'maven-publish' - id 'jacoco' alias libs.plugins.modDevGradle //alias libs.plugins.shadow alias libs.plugins.spotless @@ -18,7 +17,7 @@ version = "${mod_version}" + (isSnapshot ? "-SNAPSHOT" : "") boolean isCI = System.getenv("CI") != null java { - toolchain.languageVersion = JavaLanguageVersion.of(25) + toolchain.languageVersion = JavaLanguageVersion.of(21) } sourceSets { @@ -91,39 +90,4 @@ tasks.named('test') { lombok { version = "1.18.38" -} - -jacoco { - applyTo runGameTestServer -} - -tasks.named('runGameTestServer') { - jacoco.excludes = ['com.mojang.*', 'net.minecraft.*', 'net.neoforged.*'] -} - -jacocoTestReport { - doFirst { - try { - runGameTestServer.exec() - } catch (RuntimeException ignored) {} - } - doLast { - println "Coverage report location:" - println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('index.html')).get()}" - println " - file://${layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml')).get()}" - } - executionData runGameTestServer - sourceSets sourceSets.test - reports { - csv.required = false - xml.required = true - html.outputLocation = layout.buildDirectory.dir('coverage') - xml.outputLocation = layout.buildDirectory.dir('coverage').map(a -> a.file('coverage.xml')) - } - afterEvaluate { - classDirectories.setFrom(files(classDirectories.files.collect { - fileTree(dir: it, exclude: '**/client/**') - fileTree(dir: it, exclude: '**/mixins/**') - })) - } -} +} \ No newline at end of file diff --git a/dependencies.gradle b/dependencies.gradle index a44c5cb..35602b2 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,5 +1,6 @@ dependencies { compileOnly(libs.jetbrains.annotations) + compileOnly(libs.jspecify) testImplementation(libs.testframework.get()) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 13e9fb3..63d131b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,12 +1,14 @@ [versions] -minecraft = "26.1.2" -neoForge = "26.1.2.126" +minecraft = "1.21.1" +neoForge = "21.1.265" loader = "4" +parchment = "2024.11.17" # https://parchmentmc.org/docs/getting-started shadow = "9.6.1" spotless = "8.10.4" modDevGradle = "2.0.147" lombok = "9.8.2" jetbrains-annotations = "26.1.0" +jspecify = "1.0.1" renderNurse = "0.0.26" mixin = "0.8.7" @@ -14,9 +16,10 @@ mixin = "0.8.7" minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" } neoForge = { module = "net.neoforged:neoforge", version.ref = "neoForge" } testframework = { module = "net.neoforged:testframework", version.ref = "neoForge" } -jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } renderNurse = { module = "net.neoforged:render-nurse", version.ref = "renderNurse" } mixin = { module = "org.spongepowered:mixin", version.ref = "mixin" } +jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } +jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" } [plugins] modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGradle" } diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle index 43a47c4..a70c044 100644 --- a/gradle/scripts/moddevgradle.gradle +++ b/gradle/scripts/moddevgradle.gradle @@ -1,14 +1,15 @@ -import org.gradle.internal.os.OperatingSystem - -static def isJetBrainsRuntime() { - return System.getProperty('java.vm.vendor').contains('JetBrains') -} +import org.slf4j.event.Level def devTestModId = 'testmod' neoForge { version = libs.versions.neoForge.get() + parchment { + minecraftVersion = libs.versions.minecraft.get() + mappingsVersion = libs.versions.parchment.get() + } + accessTransformers { var file = project.file('src/main/resources/META-INF/accesstransformer.cfg') from(file) @@ -48,7 +49,6 @@ neoForge { gameDirectory.set(file('run/client')) - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) } server { @@ -58,7 +58,6 @@ neoForge { gameDirectory.set(file('run/server')) programArguments.addAll('--nogui', '--world', 'world-extra') - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) } // This run config launches GameTestServer and runs all registered gametests, then exits. @@ -84,27 +83,14 @@ neoForge { environment('TEST', 'true') } - data { - type = 'clientData' - sourceSet = sourceSets.main - ideName = "Data Generation" - - gameDirectory.set(file('run/data')) - // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - programArguments.addAll('--mod', project.mod_id) - programArguments.addAll('--all') - programArguments.addAll('--output', file('src/generated/resources/').getAbsolutePath()) - programArguments.addAll('--existing', file('src/main/resources/').getAbsolutePath()) - } - Testdata { - type = 'clientData' + data() sourceSet = sourceSets.test ideName = "Test Data Generation" gameDirectory.set(file('run/data')) // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - programArguments.addAll('--mod', "${devTestModId}") + programArguments.addAll('--mod', devTestModId) programArguments.addAll('--all') programArguments.addAll('--output', file('src/test/generated/resources/').getAbsolutePath()) programArguments.addAll('--existing', file('src/test/resources/').getAbsolutePath()) @@ -125,7 +111,7 @@ neoForge { // Recommended logging level for the console // You can set various levels here. // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels - logLevel = org.slf4j.event.Level.INFO + logLevel = Level.INFO } } } diff --git a/gradle/scripts/repositories.gradle b/gradle/scripts/repositories.gradle index 7518783..792c1d0 100644 --- a/gradle/scripts/repositories.gradle +++ b/gradle/scripts/repositories.gradle @@ -7,6 +7,9 @@ repositories { filter { includeGroup("it.unimi.dsi") includeGroup("org.lwjgl") + includeGroup("com.google.guava") + includeGroupAndSubgroups("io.netty") + includeGroupAndSubgroups("org.jetbrains") } } maven { diff --git a/gradle/scripts/resources.gradle b/gradle/scripts/resources.gradle index 52ba62c..9019055 100644 --- a/gradle/scripts/resources.gradle +++ b/gradle/scripts/resources.gradle @@ -35,7 +35,7 @@ var generateModMetadata = tasks.register("generateModMetadata", ProcessResources var replaceProperties = [ version : version_toml, mod_id : mod_id, - minecraft_version : "[26.1,)", + minecraft_version : "[${libs.versions.minecraft.get()}]", loader_version : libs.versions.loader.get(), neo_version : neoVersion, mod_license : mod_license, @@ -50,4 +50,4 @@ var generateModMetadata = tasks.register("generateModMetadata", ProcessResources into "build/generated/sources/modMetadata" } sourceSets.main.resources.srcDir generateModMetadata -neoForge.ideSyncTask generateModMetadata \ No newline at end of file +neoForge.ideSyncTask generateModMetadata diff --git a/src/main/java/com/modularmc/registrate/AbstractRegistrate.java b/src/main/java/com/modularmc/registrate/AbstractRegistrate.java index 733cf03..3bece30 100644 --- a/src/main/java/com/modularmc/registrate/AbstractRegistrate.java +++ b/src/main/java/com/modularmc/registrate/AbstractRegistrate.java @@ -18,6 +18,7 @@ import com.modularmc.registrate.util.entry.RegistryEntry; import com.modularmc.registrate.util.nullness.*; +import net.minecraft.Util; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.MenuAccess; import net.minecraft.client.multiplayer.ClientPacketListener; @@ -25,9 +26,8 @@ import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; -import net.minecraft.util.Util; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType.EntityFactory; import net.minecraft.world.entity.MobCategory; @@ -36,6 +36,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; +import net.neoforged.bus.api.EventPriority; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.loading.FMLEnvironment; import net.neoforged.neoforge.data.event.GatherDataEvent; @@ -95,10 +96,10 @@ public abstract class AbstractRegistrate> { /** * Checks if Minecraft is running from a dev environment. Enables certain debug logging. * - * @return {@code true} when in a dev environment (specifically, {@link FMLEnvironment#isProduction()} == false) + * @return {@code true} when {@link FMLEnvironment#production} is false */ public static boolean isDevEnvironment() { - return !FMLEnvironment.isProduction(); + return !FMLEnvironment.production; } private final class LifecycleHooks implements RegistrateLifecycle.Hooks { @@ -580,24 +581,25 @@ public DataProviderInitializer getDataGenInitializer() { }); /** - * Add a custom translation mapping using the vanilla style of Identifier -> translation key conversion. + * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. * * @param type * Type of the object, this is used as a prefix (e.g. * {@code ["block", "mymod:myblock"] -> "block.mymod.myblock"}) * @param id * ID of the object, which will be converted to a lang key via - * {@link Util#makeDescriptionId(String, Identifier)} + * {@link Util#makeDescriptionId(String, ResourceLocation)} * @param localizedName * (English) translation value * @return A {@link MutableComponent} representing the translated text */ - public MutableComponent addLang(String type, Identifier id, String localizedName) { + public MutableComponent addLang(String type, ResourceLocation id, String localizedName) { return addRawLang(Util.makeDescriptionId(type, id), localizedName); } /** - * Add a custom translation mapping using the vanilla style of Identifier -> translation key conversion. Also + * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. + * Also * appends a suffix to the key. * * @param type @@ -605,14 +607,14 @@ public MutableComponent addLang(String type, Identifier id, String localizedName * {@code ["block", "mymod:myblock"] -> "block.mymod.myblock"}) * @param id * ID of the object, which will be converted to a lang key via - * {@link Util#makeDescriptionId(String, Identifier)} + * {@link Util#makeDescriptionId(String, ResourceLocation)} * @param suffix * A suffix which will be appended to the generated key (separated by a dot) * @param localizedName * (English) translation value * @return A {@link MutableComponent} representing the translated text */ - public MutableComponent addLang(String type, Identifier id, String suffix, String localizedName) { + public MutableComponent addLang(String type, ResourceLocation id, String suffix, String localizedName) { return addRawLang(Util.makeDescriptionId(type, id) + "." + suffix, localizedName); } @@ -669,7 +671,7 @@ public void genData(GeneratorType type, T gen) { modid, RegistrateDataProvider.getTypeName(type), entry.get().getLeft(), - entry.get().getRight().identifier()); + entry.get().getRight().location()); } else { DATAGEN_LOGGER.debug( DebugMarkers.DATA, @@ -692,7 +694,7 @@ public void genData(GeneratorType type, T gen) { modid, RegistrateDataProvider.getTypeName(type), entry.get().getLeft(), - entry.get().getRight().identifier()); + entry.get().getRight().location()); } else { err = DATAGEN_LOGGER.getMessageFactory().newMessage( RegistrateLogger.modMessage("Unexpected error while running unassociated data generator of type {} ({})"), @@ -921,7 +923,7 @@ protected RegistryEntry accept(String name, ResourceKey ResourceKey> makeRegistry(String name, Function>, RegistryBuilder> builder) { - final ResourceKey> registryId = ResourceKey.createRegistryKey(Identifier.fromNamespaceAndPath(getModid(), name)); + final ResourceKey> registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(getModid(), name)); OneTimeEventReceiver.addModListener(this, NewRegistryEvent.class, e -> e.register(builder.apply(registryId).create())); return registryId; } @@ -963,7 +965,7 @@ public ResourceKey> makeDatapackRegistry(String name, Codec c * @see #makeDatapackRegistry(String, Codec) */ public ResourceKey> makeDatapackRegistry(String name, Codec codec, @Nullable Codec networkCodec) { - final ResourceKey> registryId = ResourceKey.createRegistryKey(Identifier.fromNamespaceAndPath(getModid(), name)); + final ResourceKey> registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(getModid(), name)); OneTimeEventReceiver.addModListener(this, DataPackRegistryEvent.NewRegistry.class, event -> event.dataPackRegistry(registryId, codec, networkCodec)); return registryId; } @@ -1091,29 +1093,29 @@ public FluidBuilder fluid(NonNullSupplier fluid(Identifier stillTexture, Identifier flowingTexture) { + public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture) { return fluid(self(), stillTexture, flowingTexture); } - public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { return fluid(self(), stillTexture, flowingTexture, typeFactory); } - public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { return fluid(self(), stillTexture, flowingTexture, fluidType); } - public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidFactory fluidFactory) { return fluid(self(), stillTexture, flowingTexture, fluidFactory); } - public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { return fluid(self(), stillTexture, flowingTexture, typeFactory, fluidFactory); } - public FluidBuilder fluid(Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { return fluid(self(), stillTexture, flowingTexture, fluidType, fluidFactory); } @@ -1130,29 +1132,29 @@ public FluidBuilder fluid(String name, NonNullSuppl return fluid(self(), name, fluidType); } - public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture) { + public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture) { return fluid(self(), name, stillTexture, flowingTexture); } - public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { return fluid(self(), name, stillTexture, flowingTexture, typeFactory); } - public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { return fluid(self(), name, stillTexture, flowingTexture, fluidType); } - public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidFactory fluidFactory) { return fluid(self(), name, stillTexture, flowingTexture, fluidFactory); } - public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { return fluid(self(), name, stillTexture, flowingTexture, typeFactory, fluidFactory); } - public FluidBuilder fluid(String name, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { return fluid(self(), name, stillTexture, flowingTexture, fluidType, fluidFactory); } @@ -1169,29 +1171,29 @@ public

FluidBuilder fluid(P parent, NonNullSupp return fluid(parent, currentName(), fluidType); } - public

FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture) { + public

FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture) { return fluid(parent, currentName(), stillTexture, flowingTexture); } - public

FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + public

FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { return fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory); } - public

FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + public

FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { return fluid(parent, currentName(), stillTexture, flowingTexture, fluidType); } - public FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidFactory fluidFactory) { return fluid(parent, currentName(), stillTexture, flowingTexture, fluidFactory); } - public FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { return fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory, fluidFactory); } - public FluidBuilder fluid(P parent, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { return fluid(parent, currentName(), stillTexture, flowingTexture, fluidType, fluidFactory); } @@ -1208,37 +1210,37 @@ public

FluidBuilder fluid(P parent, String name return fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), fluidType); } - private Identifier defaultStillTexture() { - return Identifier.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_still"); + private ResourceLocation defaultStillTexture() { + return ResourceLocation.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_still"); } - private Identifier defaultFlowingTexture() { - return Identifier.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_flow"); + private ResourceLocation defaultFlowingTexture() { + return ResourceLocation.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_flow"); } - public

FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture) { + public

FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture) { return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, FluidType::new)).model(stillTexture, flowingTexture); } - public

FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { + public

FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, typeFactory)).model(stillTexture, flowingTexture); } - public

FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, NonNullSupplier fluidType) { + public

FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidType)).model(stillTexture, flowingTexture); } - public FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidFactory fluidFactory) { return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidFactory)).model(stillTexture, flowingTexture); } - public FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, typeFactory, fluidFactory)).model(stillTexture, flowingTexture); } - public FluidBuilder fluid(P parent, String name, Identifier stillTexture, Identifier flowingTexture, + public FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidType, fluidFactory)).model(stillTexture, flowingTexture); } @@ -1308,11 +1310,11 @@ public

NoConfigBuilder defaultCreativeT } public

NoConfigBuilder defaultCreativeTab(P parent, String name, Consumer config) { - this.defaultCreativeModeTab = ResourceKey.create(Registries.CREATIVE_MODE_TAB, Identifier.fromNamespaceAndPath(this.modid, name)); + this.defaultCreativeModeTab = ResourceKey.create(Registries.CREATIVE_MODE_TAB, ResourceLocation.fromNamespaceAndPath(this.modid, name)); return this.generic(parent, name, Registries.CREATIVE_MODE_TAB, () -> { var builder = CreativeModeTab.builder() .icon(() -> getAll(Registries.ITEM).stream().findFirst().map(ItemEntry::cast).map(ItemEntry::asStack).orElse(new ItemStack(Items.AIR))) - .title(this.addLang("itemGroup", this.defaultCreativeModeTab.identifier(), RegistrateLangProvider.toEnglishName(name))); + .title(this.addLang("itemGroup", this.defaultCreativeModeTab.location(), RegistrateLangProvider.toEnglishName(name))); config.accept(builder); return builder.build(); }); diff --git a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java index e325beb..35ff835 100644 --- a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java +++ b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java @@ -22,9 +22,7 @@ import com.modularmc.registrate.util.nullness.NonNullSupplier; import com.modularmc.registrate.util.nullness.NonNullUnaryOperator; -import net.minecraft.client.color.block.BlockTintSource; -import net.minecraft.client.renderer.block.dispatch.SingleVariant; -import net.minecraft.client.renderer.block.dispatch.Variant; +import net.minecraft.client.color.block.BlockColor; import net.minecraft.core.registries.Registries; import net.minecraft.tags.TagKey; import net.minecraft.world.item.BlockItem; @@ -32,6 +30,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.storage.loot.BuiltInLootTables; import net.neoforged.api.distmarker.Dist; import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent; import net.neoforged.neoforge.client.extensions.common.IClientBlockExtensions; @@ -40,7 +39,6 @@ import org.jspecify.annotations.Nullable; -import java.util.List; import java.util.function.Supplier; import javax.annotation.Nonnull; @@ -94,7 +92,7 @@ public static BlockBuilder create(AbstractRegistrate< private NonNullSupplier initialProperties; private NonNullFunction propertiesCallback = NonNullUnaryOperator.identity(); - private @Nullable NonNullSupplier>> tintSources; + private @Nullable NonNullSupplier> colorHandler; protected BlockBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory, NonNullSupplier initialProperties) { super(owner, parent, name, callback, Registries.BLOCK); @@ -171,20 +169,17 @@ public ItemBuilder> item() { * @return the {@link ItemBuilder} for the {@link BlockItem} */ public ItemBuilder> item(NonNullBiFunction factory) { - return getOwner().>item(this, getName(), p -> factory.apply(getEntry(), p.useBlockDescriptionPrefix())) + return getOwner().>item(this, getName(), p -> factory.apply(getEntry(), p)) .removeData(ProviderType.LANG) .model(() -> (ctx, prov) -> { - getOwner().getDataProvider(ProviderType.BLOCKSTATE) - .map(g -> g.seenBlockstates.get(getEntry())) - .flatMap(b -> b.simpleModels()) - .map(b -> b.models().get("")) - .map(unbaked -> { - if (unbaked instanceof SingleVariant.Unbaked(Variant variant)) { - return variant.modelLocation(); - } - return null; - }) - .ifPresent(model -> prov.createWithExistingModel(ctx.get(), model)); + if (prov.hasModel(ctx.get())) { + return; + } + var block = getEntry(); + var model = getOwner().getDataProvider(ProviderType.BLOCKSTATE) + .flatMap(generator -> generator.getSingleVariantModel(block)) + .orElseGet(() -> RegistrateBlockModelGenerator.modelLocation(block)); + prov.createWithExistingModel(ctx.get(), model); }); } @@ -219,25 +214,24 @@ public BlockEntityBuilder> block } /** - * Register a set of block tint sources for this block. The {@link BlockTintSource} instances can be shared across - * many blocks. + * Registers the client color handler for all tint indices of this block. * - * @param tintSources The tint sources to register for this block, indexed by tint index + * @param colorHandler A side-safe supplier of the client color handler * @return this {@link BlockBuilder} */ - public BlockBuilder color(NonNullSupplier>> tintSources) { - if (this.tintSources == null) { + public BlockBuilder color(NonNullSupplier> colorHandler) { + if (this.colorHandler == null) { RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerBlockColor); } - this.tintSources = tintSources; + this.colorHandler = colorHandler; return this; } protected void registerBlockColor() { - OneTimeEventReceiver.addModListener(getOwner(), RegisterColorHandlersEvent.BlockTintSources.class, e -> { - NonNullSupplier>> tintSources = this.tintSources; - if (tintSources != null) { - e.register(tintSources.get().get(), getEntry()); + OneTimeEventReceiver.addModListener(getOwner(), RegisterColorHandlersEvent.Block.class, event -> { + var colorHandler = this.colorHandler; + if (colorHandler != null) { + event.register(colorHandler.get().get(), getEntry()); } }); } @@ -315,7 +309,7 @@ public BlockBuilder defaultLoot() { */ public BlockBuilder loot(NonNullBiConsumer cons) { return setData(ProviderType.LOOT, (ctx, prov) -> prov.addLootAction(LootType.BLOCK, tb -> { - if (ctx.getEntry().getLootTable().isPresent()) { + if (ctx.getEntry().getLootTable() != BuiltInLootTables.EMPTY) { cons.accept(tb, ctx.getEntry()); } })); @@ -377,7 +371,7 @@ protected T createEntry() { @Nonnull BlockBehaviour.Properties properties = this.initialProperties.get(); properties = propertiesCallback.apply(properties); - return factory.apply(properties.setId(getResourceKey())); + return factory.apply(properties); } @Override diff --git a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java index 11635d5..e4ccc55 100644 --- a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java +++ b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java @@ -44,7 +44,7 @@ public class BlockEntityBuilder extends AbstractBuilde public interface BlockEntityFactory { - public T create(BlockEntityType type, BlockPos pos, BlockState state); + T create(BlockEntityType type, BlockPos pos, BlockState state); } /** @@ -75,7 +75,7 @@ public static BlockEntityBuilder create(Abstrac private final BlockEntityFactory factory; private final Set> validBlocks = new HashSet<>(); - private @Nullable NonNullSupplier>> renderer; + private @Nullable NonNullSupplier>> renderer; protected BlockEntityBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, BlockEntityFactory factory) { super(owner, parent, name, callback, Registries.BLOCK_ENTITY_TYPE); @@ -119,7 +119,7 @@ public final BlockEntityBuilder validBlocks(NonNullSupplier renderer(NonNullSupplier>> renderer) { + public BlockEntityBuilder renderer(NonNullSupplier>> renderer) { if (this.renderer == null) { // First call only RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerRenderer); } @@ -151,7 +151,9 @@ public BlockEntityBuilder registerCapability(Consumer createEntry() { BlockEntityFactory factory = this.factory; final var supplier = asSupplier(); - return new BlockEntityType<>((pos, state) -> factory.create(supplier.get(), pos, state), validBlocks.stream().map(NonNullSupplier::get).toArray(Block[]::new)); + return BlockEntityType.Builder.of( + (pos, state) -> factory.create(supplier.get(), pos, state), + validBlocks.stream().map(NonNullSupplier::get).toArray(Block[]::new)).build(null); } @Override diff --git a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java index 86edccd..7ba4aa6 100644 --- a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java +++ b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java @@ -29,8 +29,8 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.levelgen.Heightmap; import net.neoforged.api.distmarker.Dist; -import net.neoforged.fml.loading.FMLEnvironment; import net.neoforged.neoforge.client.event.EntityRenderersEvent; +import net.neoforged.neoforge.common.DeferredSpawnEggItem; import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent; import net.neoforged.neoforge.event.entity.RegisterSpawnPlacementsEvent; import net.neoforged.neoforge.registries.DeferredHolder; @@ -87,7 +87,7 @@ public static EntityBuilder create(AbstractRegistrat private NonNullConsumer> builderCallback = $ -> {}; - private @Nullable NonNullSupplier>> renderer; + private @Nullable NonNullSupplier>> renderer; private boolean attributesConfigured, spawnConfigured; @@ -119,8 +119,8 @@ public EntityBuilder properties(NonNullConsumer> con * renderer * @return this {@link EntityBuilder} */ - public EntityBuilder renderer(NonNullSupplier>> renderer) { - if (this.renderer == null && FMLEnvironment.getDist().isClient()) { // First call only + public EntityBuilder renderer(NonNullSupplier>> renderer) { + if (this.renderer == null) { RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerRenderer); } this.renderer = renderer; @@ -206,22 +206,28 @@ public EntityBuilder spawnEgg() { * Create a spawn egg item for this entity and expose its builder for further customization. * *

- * The created egg uses the modern {@link net.minecraft.world.item.Item.Properties#spawnEgg(EntityType)} API and is - * added to {@link CreativeModeTabs#SPAWN_EGGS} by default. - * - *

- * No default item model is generated. If a consumer wants spawn egg visuals, - * it should provide them explicitly via the nested {@link ItemBuilder}. + * The egg resolves the entity after registration and uses the standard spawn egg model by default. * * @param consumer * A callback for customizing the nested egg {@link ItemBuilder} * @return this {@link EntityBuilder} */ public EntityBuilder spawnEgg(NonNullConsumer>> consumer) { + return spawnEgg(0xFFFFFF, 0xFFFFFF, consumer); + } + + /** + * Registers a spawn egg with the given base and highlight colors and configures it before registration. + */ + @SuppressWarnings("unchecked") + public EntityBuilder spawnEgg(int baseColor, int highlightColor, NonNullConsumer>> consumer) { NonNullSupplier> entityType = asSupplier(); + // NeoForge's deferred egg API accepts a mob factory. Registrate resolves the type after the item registry runs. + Supplier> mobType = (Supplier>) (Supplier) entityType; ItemBuilder> eggBuilder = getOwner() - .item(this, getName() + "_spawn_egg", SpawnEggItem::new) - .properties(properties -> properties.spawnEgg(entityType.get())) + .>item(this, getName() + "_spawn_egg", + properties -> new DeferredSpawnEggItem(mobType, baseColor, highlightColor, properties)) + .model(() -> (ctx, prov) -> prov.createWithExistingModel(ctx.get(), prov.mcLoc("item/template_spawn_egg"))) .tab(CreativeModeTabs.SPAWN_EGGS); consumer.accept(eggBuilder); return eggBuilder.build(); @@ -279,7 +285,7 @@ public final EntityBuilder tag(TagKey>... tags) { protected EntityType createEntry() { EntityType.Builder builder = this.builder.get(); builderCallback.accept(builder); - return builder.build(getResourceKey()); + return builder.build(getResourceKey().location().toString()); } @Override diff --git a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java index 3bee7af..01a2a26 100644 --- a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java +++ b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java @@ -12,14 +12,10 @@ import com.modularmc.registrate.util.entry.RegistryEntry; import com.modularmc.registrate.util.nullness.*; -import net.minecraft.client.data.models.model.ModelTemplates; -import net.minecraft.client.data.models.model.TextureMapping; -import net.minecraft.client.renderer.block.FluidModel; -import net.minecraft.client.resources.model.sprite.Material; +import net.minecraft.Util; import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; -import net.minecraft.util.Util; import net.minecraft.world.item.BucketItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; @@ -30,10 +26,9 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.neoforged.api.distmarker.Dist; -import net.neoforged.neoforge.client.event.RegisterFluidModelsEvent; -import net.neoforged.neoforge.client.extensions.common.IClientBlockExtensions; import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; +import net.neoforged.neoforge.client.model.DynamicFluidContainerModel.Colors; import net.neoforged.neoforge.common.util.Lazy; import net.neoforged.neoforge.fluids.BaseFlowingFluid; import net.neoforged.neoforge.fluids.FluidType; @@ -65,65 +60,56 @@ public interface FluidFactory { T create(BaseFlowingFluid.Properties properties); } - private @Nullable NonNullSupplier> model; - private @Nullable Material blockParticleTexture; + private record FluidTextures(ResourceLocation still, ResourceLocation flowing) {} + private @Nullable FluidTextures textures; private @Nullable NonNullSupplier> clientExtension; /** - * Register a client extension for this block. The {@link IClientBlockExtensions} instance can be shared across many - * items. + * Supplies the client extension for this fluid type. The extension controls its textures, tint and overlays. * - * @param clientExtension - * The client extension to register for this block - * @return this {@link BlockBuilder} + * @param clientExtension the side-safe supplier of the client extension + * @return this fluid builder */ public FluidBuilder clientExtension(NonNullSupplier> clientExtension) { - if (this.clientExtension == null) { + if (this.clientExtension == null && !(registerType && textures != null)) { RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); } this.clientExtension = clientExtension; return this; } - public FluidBuilder model(Identifier stillTexture, Identifier flowingTexture) { - this.blockParticleTexture = new Material(stillTexture); - return model(() -> () -> new FluidModel.Unbaked(new Material(stillTexture), new Material(flowingTexture), null, null)); - } - - public FluidBuilder model(NonNullSupplier> model) { - if (this.model == null) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerModel); + /** + * Sets the block particle texture and the default client textures for a fluid type registered by this builder. + * A shared fluid type supplied to the builder uses its own client extension. + */ + public FluidBuilder model(ResourceLocation stillTexture, ResourceLocation flowingTexture) { + if (textures == null && registerType && clientExtension == null) { + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); } - this.model = model; + textures = new FluidTextures(stillTexture, flowingTexture); return this; } - protected void registerModel() { - var modEventBus = getOwner().getModEventBus(); - java.util.function.Consumer listener = e -> { - NonNullSupplier> model = this.model; - if (model != null) { - NonNullSupplier source = this.source; - if (source != null) { - e.register(model.get().get(), source.get(), getEntry()); - } else { - e.register(model.get().get(), getEntry()); - } - } - }; - if (modEventBus != null) { - modEventBus.addListener(listener); - } else { - OneTimeEventReceiver.addModListener(getOwner(), RegisterFluidModelsEvent.class, listener); - } - } - protected void registerClientExtension() { - OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, e -> { - NonNullSupplier> clientExtension = this.clientExtension; - if (clientExtension != null) { - e.registerFluidType(clientExtension.get().get(), fluidType.get()); + OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, event -> { + var custom = clientExtension; + var fluidTextures = textures; + if (custom != null) { + event.registerFluidType(custom.get().get(), fluidType.get()); + } else if (fluidTextures != null) { + event.registerFluidType(new IClientFluidTypeExtensions() { + + @Override + public ResourceLocation getStillTexture() { + return fluidTextures.still(); + } + + @Override + public ResourceLocation getFlowingTexture() { + return fluidTextures.flowing(); + } + }, fluidType.get()); } }); } @@ -301,7 +287,7 @@ public static FluidBuilder create(Abstract private final FluidFactory fluidFactory; - private @Nullable final NonNullSupplier fluidType; + private final NonNullSupplier fluidType; private @Nullable Boolean defaultSource, defaultBlock, defaultBucket; @@ -309,7 +295,7 @@ public static FluidBuilder create(Abstract private NonNullConsumer fluidProperties = $ -> {}; - private boolean registerType; + private final boolean registerType; private @Nullable NonNullSupplier source; private final List> tags = new ArrayList<>(); @@ -459,16 +445,16 @@ public BlockBuilder> block(NonNull final NonNullSupplier supplier = asSupplier(); final var lightLevel = Lazy.of(() -> fluidType.get().getLightLevel()); final ToIntFunction lightLevelInt = $ -> lightLevel.get(); - final Material particleTexture = this.blockParticleTexture; final var ret = getOwner().>block(this, sourceName, p -> factory.apply(supplier.get(), p)) .properties(p -> BlockBehaviour.Properties.ofFullCopy(Blocks.WATER).noLootTable()) .properties(p -> p.lightLevel(lightLevelInt)) .blockstate(() -> (ctx, prov) -> { - if (particleTexture != null) { - prov.generateWithTemplate(ctx.get(), ModelTemplates.PARTICLE_ONLY, TextureMapping.particle(particleTexture)); - } else { - prov.createNonTemplateModelBlock(ctx.get()); + var model = prov.models().getBuilder("block/" + ctx.getName()); + var fluidTextures = textures; + if (fluidTextures != null) { + model.texture("particle", fluidTextures.still()); } + prov.simpleBlock(ctx.get(), model); }); this.fluidProperties(p -> p.block(ret.asSupplier())); return ret; @@ -533,6 +519,7 @@ public ItemBuilder> bucket(NonNullB } final var ret = getOwner().>item(this, bucketName, p -> factory.apply(source.get(), p)) .properties(p -> p.craftRemainder(Items.BUCKET).stacksTo(1)) + .color(() -> Colors::new) .model(() -> (ctx, prov) -> prov.generateFluidBucket(ctx.getEntry(), source.get())); this.fluidProperties(p -> p.bucket(ret.asSupplier())); return ret; @@ -604,7 +591,7 @@ private FluidType.Properties makeTypeProperties() { properties.descriptionId(block.get().get().getDescriptionId()); removeData(ProviderType.LANG); } else { - properties.descriptionId(Util.makeDescriptionId("fluid", Identifier.fromNamespaceAndPath(getOwner().getModid(), sourceName))); + properties.descriptionId(Util.makeDescriptionId("fluid", ResourceLocation.fromNamespaceAndPath(getOwner().getModid(), sourceName))); } return properties; diff --git a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java index 2462102..cbcdcef 100644 --- a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java +++ b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java @@ -19,15 +19,14 @@ import com.modularmc.registrate.util.nullness.NonNullSupplier; import com.modularmc.registrate.util.nullness.NonNullUnaryOperator; -import net.minecraft.client.color.item.ItemTintSource; -import net.minecraft.client.data.models.model.ModelTemplates; -import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.client.color.item.ItemColor; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.TagKey; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.neoforged.api.distmarker.Dist; +import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent; import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; import net.neoforged.neoforge.registries.DeferredHolder; @@ -88,6 +87,7 @@ public static ItemBuilder create(AbstractRegistrate private NonNullSupplier initialProperties = Item.Properties::new; private NonNullFunction propertiesCallback = NonNullUnaryOperator.identity(); + private @Nullable NonNullSupplier> colorHandler; private Map, NonNullBiConsumer, CreativeModeTabModifier>> creativeModeTabs = Maps.newLinkedHashMap(); @@ -219,18 +219,30 @@ public ItemBuilder removeTab(ResourceKey tab) { * @return this {@link ItemBuilder} */ public ItemBuilder defaultModel() { - return defaultModel(new ItemTintSource[0]); + return model(() -> (ctx, prov) -> prov.generateFlatItem(ctx.get(), prov.modItemTexture(ctx.getName()))); } /** - * Assign the default generated model to this item and apply the supplied item tint sources to its layers. + * Registers the client color handler for the tint indices used by the item model. * - * @param tints - * Tint sources to apply to the generated model layers + * @param colorHandler A side-safe supplier of the client color handler * @return this {@link ItemBuilder} */ - public ItemBuilder defaultModel(ItemTintSource... tints) { - return model(() -> (ctx, prov) -> prov.generateFlatItem(ctx.get(), ModelTemplates.FLAT_ITEM, TextureMapping.layer0(ctx.get()), tints)); + public ItemBuilder color(NonNullSupplier> colorHandler) { + if (this.colorHandler == null) { + RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerItemColor); + } + this.colorHandler = colorHandler; + return this; + } + + protected void registerItemColor() { + OneTimeEventReceiver.addModListener(getOwner(), RegisterColorHandlersEvent.Item.class, event -> { + var colorHandler = this.colorHandler; + if (colorHandler != null) { + event.register(colorHandler.get().get(), getEntry()); + } + }); } /** @@ -342,7 +354,7 @@ public final ItemBuilder tag(TagKey... tags) { protected T createEntry() { Item.Properties properties = this.initialProperties.get(); properties = propertiesCallback.apply(properties); - return factory.apply(properties.setId(getResourceKey())); + return factory.apply(properties); } @Override diff --git a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java index d67442b..593fa68 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java +++ b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java @@ -12,8 +12,8 @@ import net.minecraft.core.Registry; import net.minecraft.data.tags.TagsProvider; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagEntry; import net.minecraft.tags.TagKey; import net.neoforged.neoforge.registries.DeferredHolder; @@ -119,7 +119,7 @@ public S asOptional() { } protected TagEntry asTag() { - Identifier id = Identifier.fromNamespaceAndPath(getOwner().getModid(), getName()); + ResourceLocation id = ResourceLocation.fromNamespaceAndPath(getOwner().getModid(), getName()); if (isOptional) return TagEntry.optionalElement(id); return TagEntry.element(id); } @@ -178,6 +178,6 @@ private S lang(NonNullFunction langKeyProvider, NonNullBiFunction getResourceKey() { - return ResourceKey.create(getRegistryKey(), Identifier.fromNamespaceAndPath(getOwner().getModid(), getName())); + return ResourceKey.create(getRegistryKey(), ResourceLocation.fromNamespaceAndPath(getOwner().getModid(), getName())); } } diff --git a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java index e43afe9..ad87edd 100644 --- a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java +++ b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java @@ -8,8 +8,8 @@ import com.modularmc.registrate.util.nullness.NonNullSupplier; import net.minecraft.core.Registry; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.neoforged.neoforge.registries.DeferredHolder; import net.neoforged.neoforge.registries.RegisterEvent; @@ -36,14 +36,14 @@ public final class RegistrationTracker { private static final class Registration { - private final Identifier identifier; + private final ResourceLocation identifier; private final ResourceKey> registryKey; private final NonNullSupplier creator; private final RegistryEntry delegate; private final List> callbacks = new ArrayList<>(); private Registration( - Identifier identifier, + ResourceLocation identifier, ResourceKey> registryKey, NonNullSupplier creator, NonNullFunction, ? extends RegistryEntry> entryFactory) { @@ -53,7 +53,7 @@ private Registration( this.delegate = entryFactory.apply(DeferredHolder.create(registryKey, identifier)); } - private Identifier getIdentifier() { + private ResourceLocation getIdentifier() { return identifier; } @@ -100,7 +100,7 @@ public void onRegister(RegisterEvent event, boolean skipErrors, boolean devEnvir modId, callbacks.size(), entryKey.getLeft(), - entryKey.getRight().identifier())); + entryKey.getRight().location())); pendingEntryCallbacks.clear(); if (devEnvironment) { throw new IllegalStateException("Found unused register callbacks, see logs"); @@ -117,7 +117,7 @@ public void onRegister(RegisterEvent event, boolean skipErrors, boolean devEnvir RegistrateLogger.modMessage("Registering {} captured object(s) in {}"), modId, registrationsForType.size(), - registryKey.identifier()); + registryKey.location()); for (var entry : registrationsForType.entrySet()) { Registration registration = entry.getValue(); try { @@ -127,7 +127,7 @@ public void onRegister(RegisterEvent event, boolean skipErrors, boolean devEnvir RegistrateLogger.modMessage("Registered {} in {}"), modId, registration.getIdentifier(), - registryKey.identifier()); + registryKey.location()); } catch (Exception exception) { if (skipErrors) { LOGGER.error( @@ -135,12 +135,12 @@ public void onRegister(RegisterEvent event, boolean skipErrors, boolean devEnvir RegistrateLogger.modMessage("Unexpected error while registering entry {} in {}"), modId, registration.getIdentifier(), - registryKey.identifier(), + registryKey.location(), exception); } else { throw new RuntimeException( "[%s] Unexpected error while registering entry %s in %s" - .formatted(modId, registration.getIdentifier(), registryKey.identifier()), + .formatted(modId, registration.getIdentifier(), registryKey.location()), exception); } } @@ -165,7 +165,7 @@ public RegistryEntry track( NonNullSupplier creator, NonNullFunction, ? extends RegistryEntry> entryFactory) { Registration registration = new Registration<>( - Identifier.fromNamespaceAndPath(modId, name), + ResourceLocation.fromNamespaceAndPath(modId, name), registryKey, creator, entryFactory); @@ -174,7 +174,7 @@ public RegistryEntry track( RegistrateLogger.modMessage("Captured registration {} for registry {}"), modId, registration.getIdentifier(), - registryKey.identifier()); + registryKey.location()); pendingEntryCallbacks.removeAll(Pair.of(name, registryKey)).forEach(callback -> { @SuppressWarnings("unchecked") NonNullConsumer unsafeCallback = (NonNullConsumer) callback; @@ -231,7 +231,7 @@ private Registration getRegistration(String name, Resourc if (registration != null) { return registration; } - throw new IllegalArgumentException("Unknown registration " + name + " for type " + registryKey.identifier()); + throw new IllegalArgumentException("Unknown registration " + name + " for type " + registryKey.location()); } @SuppressWarnings("unchecked") diff --git a/src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java b/src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java deleted file mode 100644 index a23ed28..0000000 --- a/src/main/java/com/modularmc/registrate/internal/datagen/RegistrateDatagenBootstrap.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.modularmc.registrate.internal.datagen; - -import net.minecraft.client.ClientBootstrap; - -/** - * Bridges the gap between NeoForge's server-side datagen entrypoints and - * Minecraft's client-side model codec bootstrap. - * - *

- * In 26.1, item model serialization depends on client bootstrap state even when - * data generation is launched through the server datagen path. Triggering the - * vanilla bootstrap here keeps Registrate's client-facing generators usable in - * headless datagen runs. - */ -public final class RegistrateDatagenBootstrap { - - private RegistrateDatagenBootstrap() {} - - public static void bootstrapClientCodecs() { - ClientBootstrap.bootstrap(); - } -} diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java index 7f175a6..1f677ac 100644 --- a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java @@ -12,7 +12,6 @@ import org.jspecify.annotations.Nullable; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; /** @@ -70,17 +69,7 @@ public void register(IEventBus bus) { }); if (hooks.doDatagen()) { - AtomicBoolean dataHooked = new AtomicBoolean(); - Consumer onData = event -> { - if (dataHooked.compareAndSet(false, true)) { - hooks.onData(event); - } - }; - - // Different moddev run types dispatch different concrete gather events. - // Register both and guard the callback so data providers are only attached once. - OneTimeEventReceiver.addModListener(owner, GatherDataEvent.Client.class, onData); - OneTimeEventReceiver.addModListener(owner, GatherDataEvent.Server.class, onData); + OneTimeEventReceiver.addModListener(owner, GatherDataEvent.class, hooks::onData); } } } diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java index e9c46d1..6500d91 100644 --- a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java @@ -10,7 +10,7 @@ public final class RegistrateDistExecutor { private RegistrateDistExecutor() {} public static void unsafeRunWhenOn(Dist dist, Supplier toRun) { - if (dist == FMLEnvironment.getDist()) { + if (dist == FMLEnvironment.dist) { toRun.get().run(); } } diff --git a/src/main/java/com/modularmc/registrate/providers/DataGenContext.java b/src/main/java/com/modularmc/registrate/providers/DataGenContext.java index a3733e4..2c14c65 100644 --- a/src/main/java/com/modularmc/registrate/providers/DataGenContext.java +++ b/src/main/java/com/modularmc/registrate/providers/DataGenContext.java @@ -4,8 +4,8 @@ import com.modularmc.registrate.util.nullness.NonNullSupplier; import net.minecraft.core.Registry; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import lombok.AccessLevel; import lombok.Getter; @@ -28,7 +28,7 @@ public class DataGenContext implements NonNullSupplier { @Delegate NonNullSupplier entry; String name; - Identifier id; + ResourceLocation id; @SuppressWarnings("null") public E getEntry() { @@ -42,6 +42,6 @@ public static DataGenContext from(Builder bui public static DataGenContext from(Builder builder) { return new DataGenContext<>(NonNullSupplier.of(builder.getOwner().get(builder.getName(), builder.getRegistryKey())), builder.getName(), - Identifier.fromNamespaceAndPath(builder.getOwner().getModid(), builder.getName())); + ResourceLocation.fromNamespaceAndPath(builder.getOwner().getModid(), builder.getName())); } } diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java index 8019de5..5528cf6 100644 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java @@ -12,8 +12,8 @@ import net.minecraft.data.DataProvider; import net.minecraft.data.PackOutput; import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.neoforged.fml.LogicalSide; import net.neoforged.neoforge.common.conditions.ICondition; import net.neoforged.neoforge.common.conditions.WithConditions; @@ -60,15 +60,15 @@ public LogicalSide getSide() { } public MutableComponent title(String category, String name, String title) { - return owner.addLang("advancements", Identifier.fromNamespaceAndPath(category, name), "title", title); + return owner.addLang("advancements", ResourceLocation.fromNamespaceAndPath(category, name), "title", title); } public MutableComponent desc(String category, String name, String desc) { - return owner.addLang("advancements", Identifier.fromNamespaceAndPath(category, name), "description", desc); + return owner.addLang("advancements", ResourceLocation.fromNamespaceAndPath(category, name), "description", desc); } private @Nullable CachedOutput cache; - private Set seenAdvancements = new HashSet<>(); + private Set seenAdvancements = new HashSet<>(); @Override public CompletableFuture run(CachedOutput cache) { diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java index 1b77d6e..c5ef80c 100644 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java @@ -1,6 +1,7 @@ package com.modularmc.registrate.providers; import com.modularmc.registrate.AbstractRegistrate; +import com.modularmc.registrate.providers.RegistrateTagsProvider.IntrinsicTags; import com.modularmc.registrate.providers.core.ProviderType; import net.minecraft.core.HolderLookup; @@ -12,20 +13,21 @@ import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; -public class RegistrateItemTagsProvider extends RegistrateTagsProvider.IntrinsicImpl { +public class RegistrateItemTagsProvider extends IntrinsicTags { private final CompletableFuture> blockTags; private final Map, TagKey> tagsToCopy = new HashMap<>(); - public RegistrateItemTagsProvider(AbstractRegistrate owner, ProviderType type, String name, PackOutput output, CompletableFuture registriesLookup, CompletableFuture> blockTags) { + public RegistrateItemTagsProvider(AbstractRegistrate owner, ProviderType type, String name, PackOutput output, CompletableFuture registriesLookup, CompletableFuture> blockTags, ExistingFileHelper fileHelper) { super(owner, type, name, output, Registries.ITEM, registriesLookup, item -> BuiltInRegistries.ITEM.getResourceKey(item) - .orElseThrow(() -> new IllegalStateException("Cannot generate tags for unregistered item: " + item))); + .orElseThrow(() -> new IllegalStateException("Cannot generate tags for unregistered item: " + item)), fileHelper); this.blockTags = blockTags; } diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java index ac14ff5..0f53996 100644 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java @@ -80,7 +80,7 @@ public static final String toEnglishName(String internalName) { @SuppressWarnings({ "unchecked", "ConstantConditions" }) public String getAutomaticName(NonNullSupplier sup, ResourceKey> registry) { - return toEnglishName(((Registry>) BuiltInRegistries.REGISTRY).getValue(registry.identifier()).getKey(sup.get()).getPath()); + return toEnglishName(((Registry>) BuiltInRegistries.REGISTRY).get(registry.location()).getKey(sup.get()).getPath()); } public void addBlock(NonNullSupplier block) { diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java index cd3b8f0..12ca1b4 100644 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java @@ -8,13 +8,14 @@ import net.minecraft.core.Registry; import net.minecraft.data.PackOutput; import net.minecraft.data.tags.IntrinsicHolderTagsProvider; -import net.minecraft.data.tags.KeyTagProvider; -import net.minecraft.data.tags.TagAppender; +import net.minecraft.data.tags.IntrinsicHolderTagsProvider.IntrinsicTagAppender; import net.minecraft.data.tags.TagsProvider; +import net.minecraft.data.tags.TagsProvider.TagAppender; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.TagBuilder; import net.minecraft.tags.TagKey; import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import java.util.concurrent.CompletableFuture; import java.util.function.Function; @@ -29,22 +30,22 @@ public interface RegistrateTagsProvider extends RegistrateLookupFillerProvide interface Key extends RegistrateTagsProvider { - TagAppender, T> tag(TagKey key); + TagAppender tag(TagKey key); } interface Intrinsic extends RegistrateTagsProvider { - TagAppender tag(TagKey key); + IntrinsicTagAppender tag(TagKey key); } - class Impl extends KeyTagProvider implements RegistrateTagsProvider.Key { + class KeyTags extends TagsProvider implements RegistrateTagsProvider.Key { private final AbstractRegistrate owner; - private final ProviderType> type; + private final ProviderType> type; private final String name; - public Impl(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup) { - super(packOutput, registryIn, registriesLookup, owner.getModid()); + public KeyTags(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup, ExistingFileHelper fileHelper) { + super(packOutput, registryIn, registriesLookup, owner.getModid(), fileHelper); this.owner = owner; this.type = type; @@ -72,7 +73,7 @@ public TagBuilder rawBuilder(final TagKey key) { } @Override - public TagAppender, T> tag(TagKey key) { + public TagAppender tag(TagKey key) { return super.tag(key); } @@ -87,14 +88,14 @@ public ResourceKey> registry() { } } - class IntrinsicImpl extends IntrinsicHolderTagsProvider implements RegistrateTagsProvider.Intrinsic { + class IntrinsicTags extends IntrinsicHolderTagsProvider implements RegistrateTagsProvider.Intrinsic { private final AbstractRegistrate owner; - private final ProviderType> type; + private final ProviderType> type; private final String name; - public IntrinsicImpl(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup, Function> keyExtractor) { - super(packOutput, registryIn, registriesLookup, keyExtractor, owner.getModid()); + public IntrinsicTags(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup, Function> keyExtractor, ExistingFileHelper fileHelper) { + super(packOutput, registryIn, registriesLookup, keyExtractor, owner.getModid(), fileHelper); this.owner = owner; this.type = type; @@ -122,7 +123,7 @@ public TagBuilder rawBuilder(TagKey key) { } @Override - public TagAppender tag(final TagKey key) { + public IntrinsicTagAppender tag(final TagKey key) { return super.tag(key); } diff --git a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java index c6ae126..484d360 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java +++ b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java @@ -8,7 +8,12 @@ import com.modularmc.registrate.providers.RegistrateItemTagsProvider; import com.modularmc.registrate.providers.RegistrateLangProvider; import com.modularmc.registrate.providers.RegistrateTagsProvider; -import com.modularmc.registrate.providers.generators.*; +import com.modularmc.registrate.providers.RegistrateTagsProvider.IntrinsicTags; +import com.modularmc.registrate.providers.RegistrateTagsProvider.KeyTags; +import com.modularmc.registrate.providers.generators.RegistrateBlockModelGenerator; +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator; +import com.modularmc.registrate.providers.generators.RegistrateModelProvider; +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider; import com.modularmc.registrate.util.nullness.NonNullSupplier; @@ -23,6 +28,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.material.Fluid; import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.common.data.ExistingFileHelper; import net.neoforged.neoforge.data.loading.DatagenModLoader; import java.util.Map; @@ -46,29 +52,29 @@ public interface ProviderType extends GeneratorTyp // SERVER DATA ProviderType DYNAMIC = registerServerData("dynamic", RegistrateDatapackProvider::new); ProviderType DATA_MAP = registerServerData("data_map", RegistrateDataMapProvider::new); - ProviderType RECIPE_RUNNER = registerServerData("recipe_runner", RegistrateRecipeRunner::new); + ProviderType RECIPE = registerServerData("recipe", RegistrateRecipeProvider::new); ProviderType ADVANCEMENT = registerServerData("advancement", RegistrateAdvancementProvider::new); ProviderType LOOT = registerServerData("loot", RegistrateLootTableProvider::new); - ProviderType> BLOCK_TAGS = registerIntrinsicTag("tags/block", "blocks", Registries.BLOCK, BuiltInRegistries.BLOCK); - ProviderType> ENCHANTMENT_TAGS = registerDynamicTag("tags/enchantment", "enchantments", Registries.ENCHANTMENT); - ProviderType ITEM_TAGS = registerTag("tags/item", Registries.ITEM, c -> new RegistrateItemTagsProvider(c.parent(), c.type(), "items", c.output(), c.provider(), c.require(BLOCK_TAGS).contentsGetter())); - ProviderType> FLUID_TAGS = registerIntrinsicTag("tags/fluid", "fluids", Registries.FLUID, BuiltInRegistries.FLUID); - ProviderType>> ENTITY_TAGS = registerIntrinsicTag("tags/entity", "entity_types", Registries.ENTITY_TYPE, BuiltInRegistries.ENTITY_TYPE); + ProviderType> BLOCK_TAGS = registerIntrinsicTag("tags/block", "blocks", Registries.BLOCK, BuiltInRegistries.BLOCK); + ProviderType> ENCHANTMENT_TAGS = registerDynamicTag("tags/enchantment", "enchantments", Registries.ENCHANTMENT); + ProviderType ITEM_TAGS = registerTag("tags/item", Registries.ITEM, c -> new RegistrateItemTagsProvider(c.parent(), c.type(), "items", c.output(), c.provider(), c.require(BLOCK_TAGS).contentsGetter(), c.fileHelper())); + ProviderType> FLUID_TAGS = registerIntrinsicTag("tags/fluid", "fluids", Registries.FLUID, BuiltInRegistries.FLUID); + ProviderType>> ENTITY_TAGS = registerIntrinsicTag("tags/entity", "entity_types", Registries.ENTITY_TYPE, BuiltInRegistries.ENTITY_TYPE); ProviderType GENERIC_SERVER = registerProvider("registrate_generic_server_provider", c -> new RegistrateGenericProvider(c.parent(), c.output(), c.provider(), LogicalSide.SERVER, c.type())); // CLIENT DATA - ProviderType MODEL = registerClientProvider("model", () -> c -> new RegistrateModelProvider(c.parent(), c.output())); + ProviderType MODEL = registerClientProvider("model", () -> c -> new RegistrateModelProvider(c.parent(), c.output(), c.fileHelper())); ProviderType LANG = registerClientProvider("lang", () -> c -> new RegistrateLangProvider(c.parent(), c.output())); ProviderType GENERIC_CLIENT = registerClientProvider("registrate_generic_client_provider", () -> c -> new RegistrateGenericProvider(c.parent(), c.output(), c.provider(), LogicalSide.CLIENT, c.type())); - GeneratorType RECIPE = RECIPE_RUNNER.createGenerator("recipe"); GeneratorType BLOCKSTATE = MODEL.createGenerator("blockstate"); GeneratorType ITEM_MODEL = MODEL.createGenerator("item_model"); record Context(ProviderType type, AbstractRegistrate parent, Map, RegistrateProvider> existing, PackOutput output, - CompletableFuture provider) { + CompletableFuture provider, + ExistingFileHelper fileHelper) { public R require(ProviderType other) { return other.cast(Objects.requireNonNull( @@ -134,16 +140,16 @@ static > ProviderType registerTag(Stri return type; } - static ProviderType> registerIntrinsicTag(String providerName, String typeName, ResourceKey> registryKey, Registry registry) { - return registerTag(providerName, registryKey, c -> new RegistrateTagsProvider.IntrinsicImpl<>(c.parent(), c.type(), typeName, c.output(), registryKey, c.provider(), keyExtractor(registry, typeName))); + static ProviderType> registerIntrinsicTag(String providerName, String typeName, ResourceKey> registryKey, Registry registry) { + return registerTag(providerName, registryKey, c -> new IntrinsicTags<>(c.parent(), c.type(), typeName, c.output(), registryKey, c.provider(), keyExtractor(registry, typeName), c.fileHelper())); } - static ProviderType> registerDynamicTag(String providerName, String typeName, ResourceKey> registry) { - return registerTag(providerName, registry, c -> new RegistrateTagsProvider.Impl<>(c.parent(), c.type(), typeName, c.output(), registry, c.provider())); + static ProviderType> registerDynamicTag(String providerName, String typeName, ResourceKey> registry) { + return registerTag(providerName, registry, c -> new KeyTags<>(c.parent(), c.type(), typeName, c.output(), registry, c.provider(), c.fileHelper())); } - static T create(ProviderType type, AbstractRegistrate parent, Map, RegistrateProvider> existing, PackOutput output, CompletableFuture provider) { - return type.create(new Context<>(type, parent, existing, output, provider)); + static T create(ProviderType type, AbstractRegistrate parent, Map, RegistrateProvider> existing, PackOutput output, CompletableFuture provider, ExistingFileHelper fileHelper) { + return type.create(new Context<>(type, parent, existing, output, provider, fileHelper)); } private static Function> keyExtractor(Registry registry, String typeName) { diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java index 6698a79..dd15529 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java @@ -1,7 +1,6 @@ package com.modularmc.registrate.providers.core; import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.internal.datagen.RegistrateDatagenBootstrap; import com.modularmc.registrate.internal.util.DebugMarkers; import com.modularmc.registrate.internal.util.RegistrateLogger; import com.modularmc.registrate.providers.RegistrateTagsProvider; @@ -44,49 +43,35 @@ public class RegistrateDataProvider implements DataProvider { private final String mod; private final Map, RegistrateProvider> subProviders = new LinkedHashMap<>(); - private final Map, Object> subGenerators = new LinkedHashMap<>(); + private final Map, Object> subGenerators = new ConcurrentHashMap<>(); private final CompletableFuture registriesLookup; public RegistrateDataProvider(AbstractRegistrate parent, String modid, GatherDataEvent event) { this.mod = modid; this.registriesLookup = event.getLookupProvider(); - // For now, generate everything together - /* - * EnumSet sides = EnumSet.noneOf(LogicalSide.class); - * if (event.includeServer()) { - * sides.add(LogicalSide.SERVER); - * } - * if (event.includeClient()) { - * sides.add(LogicalSide.CLIENT); - * } - */ - LOGGER.debug(DebugMarkers.DATA, RegistrateLogger.modMessage("Collecting datagen providers"), mod); Map, RegistrateProvider> known = new HashMap<>(); for (DataProviderInitializer.Sorted sorted : parent.getDataGenInitializer().getSortedProviders()) { ProviderType type = sorted.type(); var lookup = registriesLookup; if (sorted.parent() != null) lookup = ((RegistrateLookupFillerProvider) known.get(sorted.parent())).getFilledProvider(); - RegistrateProvider prov = ProviderType.create(type, parent, known, event.getGenerator().getPackOutput(), lookup); + RegistrateProvider prov = ProviderType.create(type, parent, known, event.getGenerator().getPackOutput(), lookup, event.getExistingFileHelper()); if (prov instanceof RegistrateTagsProvider tagsProvider && TAG_TYPES.get(tagsProvider.registry()) != type) { throw new IllegalStateException("Tag providers must be registered through ProviderType::registerTag"); } known.put(type, prov); - // if (sides.contains(prov.getSide())) { LOGGER.debug( DebugMarkers.DATA, RegistrateLogger.modMessage("Added datagen provider {}"), mod, sorted.id()); subProviders.put(type, prov); - // } } } @Override public CompletableFuture run(CachedOutput cache) { - RegistrateDatagenBootstrap.bootstrapClientCodecs(); return registriesLookup.thenCompose(provider -> { var list = Lists.>newArrayList(); @@ -97,7 +82,7 @@ public CompletableFuture run(CachedOutput cache) { mod, getTypeName(e.getKey())); list.add(e.getValue().run(cache)); - } ; + } return CompletableFuture.allOf(list.toArray(CompletableFuture[]::new)); }); @@ -116,6 +101,8 @@ public

Optional

getSubProvider(GeneratorType

type) { } public void putSubProvider(GeneratorType type, T gen) { - subGenerators.put(type, gen); + if (!(type instanceof ProviderType)) { + subGenerators.put(type, gen); + } } } diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java index 0a939b5..3e20c95 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java @@ -1,13 +1,13 @@ package com.modularmc.registrate.providers.core; import net.minecraft.data.DataProvider; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; public interface RegistrateProviderDelegate extends DataProvider { String getName(); - Identifier getId(); + ResourceLocation getId(); T getEntry(); } diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java index 5101007..cb4ebeb 100644 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java @@ -3,524 +3,84 @@ import com.modularmc.registrate.AbstractRegistrate; import com.modularmc.registrate.providers.core.ProviderType; -import net.minecraft.client.data.models.BlockModelGenerators; -import net.minecraft.client.data.models.ItemModelOutput; -import net.minecraft.client.data.models.MultiVariant; -import net.minecraft.client.data.models.blockstates.BlockModelDefinitionGenerator; -import net.minecraft.client.data.models.blockstates.MultiPartGenerator; -import net.minecraft.client.data.models.blockstates.MultiVariantGenerator; -import net.minecraft.client.data.models.blockstates.PropertyDispatch; -import net.minecraft.client.data.models.model.ModelInstance; -import net.minecraft.client.data.models.model.ModelTemplate; -import net.minecraft.client.data.models.model.ModelTemplates; -import net.minecraft.client.data.models.model.TextureMapping; -import net.minecraft.client.data.models.model.TextureSlot; -import net.minecraft.client.data.models.model.TexturedModel; -import net.minecraft.client.renderer.block.dispatch.BlockStateModelDispatcher; -import net.minecraft.client.renderer.block.dispatch.VariantMutator; -import net.minecraft.client.resources.model.sprite.Material; -import net.minecraft.core.Direction; -import net.minecraft.resources.Identifier; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.ButtonBlock; -import net.minecraft.world.level.block.CeilingHangingSignBlock; -import net.minecraft.world.level.block.CrossCollisionBlock; -import net.minecraft.world.level.block.DoorBlock; -import net.minecraft.world.level.block.FenceBlock; -import net.minecraft.world.level.block.FenceGateBlock; -import net.minecraft.world.level.block.IronBarsBlock; -import net.minecraft.world.level.block.PipeBlock; -import net.minecraft.world.level.block.PressurePlateBlock; -import net.minecraft.world.level.block.RotatedPillarBlock; -import net.minecraft.world.level.block.SlabBlock; -import net.minecraft.world.level.block.StairBlock; -import net.minecraft.world.level.block.StandingSignBlock; -import net.minecraft.world.level.block.TrapDoorBlock; -import net.minecraft.world.level.block.WallBlock; -import net.minecraft.world.level.block.WallHangingSignBlock; -import net.minecraft.world.level.block.WallSignBlock; -import net.minecraft.world.level.block.state.properties.AttachFace; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.neoforged.fml.util.ObfuscationReflectionHelper; -import net.neoforged.neoforge.client.model.generators.template.ExtendedModelTemplateBuilder; +import net.neoforged.neoforge.client.model.generators.BlockStateProvider; +import net.neoforged.neoforge.client.model.generators.MultiPartBlockStateBuilder; +import net.neoforged.neoforge.client.model.generators.VariantBlockStateBuilder; +import net.neoforged.neoforge.common.data.ExistingFileHelper; -import java.util.HashMap; -import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.Consumer; +import com.google.gson.JsonElement; -public class RegistrateBlockModelGenerator extends BlockModelGenerators { +import java.util.Optional; + +public class RegistrateBlockModelGenerator extends BlockStateProvider { private final AbstractRegistrate parent; - public final Map seenBlockstates = new HashMap<>(); + private final RegistrateItemModelGenerator itemModels; - public RegistrateBlockModelGenerator(AbstractRegistrate parent, Consumer known, ItemModelOutput item, BiConsumer model) { - super(known, item, model); - ObfuscationReflectionHelper.>setPrivateValue(BlockModelGenerators.class, this, g -> { - this.seenBlockstates.put(g.block(), g.create()); - known.accept(g); - }, "blockStateOutput"); + public RegistrateBlockModelGenerator(AbstractRegistrate parent, PackOutput output, ExistingFileHelper fileHelper) { + super(output, parent.getModid(), fileHelper); this.parent = parent; + this.itemModels = new RegistrateItemModelGenerator(parent, output, fileHelper); } @Override - public void run() { + protected void registerStatesAndModels() { parent.genData(ProviderType.BLOCKSTATE, this); + itemModels.registerModels(); } - public void create(Block block, Identifier model) { - this.blockStateOutput.accept(createSimpleBlock(block, plainVariant(model))); - } - - public Identifier mcLoc(String id) { - return Identifier.withDefaultNamespace(id); - } - - public Identifier modLoc(String id) { - return Identifier.fromNamespaceAndPath(parent.getModid(), id); - } - - public Material mcBlockTexture(String path) { - return new Material(mcLoc("block/" + path)); - } - - public Material modBlockTexture(String path) { - return new Material(modLoc("block/" + path)); - } - - public RegistrateLegacyBlockModelBuilder withBuilder(ExtendedModelTemplateBuilder template, TextureMapping texture) { - return new RegistrateLegacyBlockModelBuilder(modelOutput, template, texture); - } - - public RegistrateLegacyBlockModelBuilder withBuilder(ExtendedModelTemplateBuilder template) { - return withBuilder(template, new TextureMapping()); - } - - public RegistrateLegacyBlockModelBuilder getBuilder() { - return withBuilder(new ExtendedModelTemplateBuilder()); - } - - public RegistrateLegacyBlockModelBuilder withParent(ModelTemplate template) { - return withBuilder(ExtendedModelTemplateBuilder.of(template)); - } - - public RegistrateLegacyBlockModelBuilder withParent(ModelTemplate template, TextureMapping texture) { - return withBuilder(ExtendedModelTemplateBuilder.of(template), texture); - } - - public RegistrateLegacyBlockModelBuilder withParent(TexturedModel model) { - return withBuilder(ExtendedModelTemplateBuilder.of(model.getTemplate()), model.getMapping()); - } - - private static TextureMapping sideBottomTopTextures(Material side, Material bottom, Material top) { - return new TextureMapping() - .put(TextureSlot.SIDE, side) - .put(TextureSlot.BOTTOM, bottom) - .put(TextureSlot.TOP, top); - } - - public Material blockTexture(Block block) { - return TextureMapping.getBlockTexture(block); - } - - public Material blockTexture(Block block, String suffix) { - return TextureMapping.getBlockTexture(block, suffix); - } - - public void generateWithTemplate(Block block, ModelTemplate template, TextureMapping textures) { - create(block, template.create(block, textures, modelOutput)); - } - - public void generate(Block block, TexturedModel.Provider texture) { - blockStateOutput.accept(createSimpleBlock(block, plainVariant(texture.create(block, modelOutput)))); - } - - public void generateAxisBlock(RotatedPillarBlock block) { - generateAxisBlock(block, blockTexture(block, "_side"), blockTexture(block, "_end")); - } - - public void generateLogBlock(RotatedPillarBlock block) { - generateAxisBlock(block, blockTexture(block), blockTexture(block, "_top")); - } - - public void generateAxisBlock(RotatedPillarBlock block, Material side, Material end) { - generateAxisBlockInternal(block, side, end, ModelTemplates.CUBE_COLUMN, ModelTemplates.CUBE_COLUMN_HORIZONTAL); - } - - private void generateAxisBlockInternal(RotatedPillarBlock block, Material side, Material end, ModelTemplate cubeColumn, ModelTemplate cubeColumnHorizontal) { - generateAxisBlock(block, - plainVariant(cubeColumn.create(block, TextureMapping.column(side, end), modelOutput)), - plainVariant(cubeColumnHorizontal.create(block, TextureMapping.column(side, end), modelOutput))); - } - - public void generateAxisBlock(RotatedPillarBlock block, MultiVariant vertical, MultiVariant horizontal) { - blockStateOutput.accept(createRotatedPillarWithHorizontalVariant(block, vertical, horizontal)); - } - - private static final int DEFAULT_ANGLE_OFFSET = 180; - - public void generateHorizontalBlock(Block block, Material side, Material front, Material top) { - TextureMapping mapping = new TextureMapping().put(TextureSlot.SIDE, side).put(TextureSlot.FRONT, front).put(TextureSlot.TOP, top); - generateHorizontalBlock(block, plainVariant(ModelTemplates.CUBE_ORIENTABLE.create(block, mapping, modelOutput))); - } - - private static VariantMutator yRot(Direction direction, int angleOffset) { - return switch ((direction.get2DDataValue() + angleOffset / 90) % 4) { - case 0 -> NOP; - case 1 -> Y_ROT_90; - case 2 -> Y_ROT_180; - case 3 -> Y_ROT_270; - default -> throw new IllegalStateException(); - }; - } - - public static PropertyDispatch rotationHorizontalFacing(int angleOffset) { - return PropertyDispatch.modify(BlockStateProperties.HORIZONTAL_FACING) - .generate(direction -> yRot(direction, angleOffset)); - } - - public static PropertyDispatch rotationFacing(int angleOffsetY) { - return PropertyDispatch.modify(BlockStateProperties.FACING).generate(direction -> { - VariantMutator xRot = switch (direction) { - case DOWN -> X_ROT_180; - case UP -> NOP; - case NORTH, EAST, SOUTH, WEST -> X_ROT_90; - }; - VariantMutator yRot = direction.getAxis().isVertical() ? NOP : yRot(direction, angleOffsetY); - return xRot.then(yRot); - }); - } - - public static PropertyDispatch rotationAttachFaceAndHorizontalFacing(int angleOffsetY) { - return PropertyDispatch.modify(BlockStateProperties.ATTACH_FACE, BlockStateProperties.HORIZONTAL_FACING).generate((attachFace, direction) -> { - VariantMutator xRot = switch (attachFace) { - case FLOOR -> NOP; - case WALL -> X_ROT_90; - case CEILING -> X_ROT_180; - }; - VariantMutator yRot = yRot(direction, attachFace == AttachFace.CEILING ? angleOffsetY + 180 : angleOffsetY); - return xRot.then(yRot); - }); - } - - public void generateHorizontalBlock(Block block, MultiVariant model) { - blockStateOutput.accept(MultiVariantGenerator.dispatch(block, model).with(ROTATION_HORIZONTAL_FACING)); - } - - public void generateHorizontalBlock(Block block, MultiVariant multiVariant, int angleOffset) { - blockStateOutput.accept(MultiVariantGenerator.dispatch(block, multiVariant).with(rotationHorizontalFacing(angleOffset))); - } - - public void generateHorizontalFaceBlock(Block block, MultiVariant model) { - generateHorizontalFaceBlock(block, model, DEFAULT_ANGLE_OFFSET); - } - - public void generateHorizontalFaceBlock(Block block, MultiVariant variant, int angleOffset) { - blockStateOutput.accept(MultiVariantGenerator.dispatch(block, variant).with(rotationAttachFaceAndHorizontalFacing(angleOffset))); - } - - public void generateDirectionalBlock(Block block, MultiVariant model) { - generateDirectionalBlock(block, model, DEFAULT_ANGLE_OFFSET); - } - - public void generateDirectionalBlock(Block block, MultiVariant model, int angleOffsetY) { - blockStateOutput.accept(MultiVariantGenerator.dispatch(block, model).with(rotationFacing(angleOffsetY))); - } - - public void generateStairsBlock(StairBlock block, Material texture) { - generateStairsBlock(block, texture, texture, texture); - } - - public void generateStairsBlock(StairBlock block, String name, Material texture) { - generateStairsBlock(block, name, texture, texture, texture); - } - - public void generateStairsBlock(StairBlock block, Material side, Material bottom, Material top) { - TextureMapping textures = sideBottomTopTextures(side, bottom, top); - blockStateOutput.accept(createStairs(block, - plainVariant(ModelTemplates.STAIRS_INNER.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.STAIRS_STRAIGHT.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.STAIRS_OUTER.create(block, textures, modelOutput)))); - } - - public void generateStairsBlock(StairBlock block, String name, Material side, Material bottom, Material top) { - generateStairsBlockInternal(block, modLoc(name + "_stairs"), side, bottom, top, ModelTemplates.STAIRS_STRAIGHT, ModelTemplates.STAIRS_INNER, ModelTemplates.STAIRS_OUTER); - } - - private void generateStairsBlockInternal(StairBlock block, Identifier baseName, Material side, Material bottom, Material top, ModelTemplate straightTemplate, ModelTemplate innerTemplate, ModelTemplate outerTemplate) { - Identifier modelLocation = baseName.withPrefix("block/"); - TextureMapping textures = sideBottomTopTextures(side, bottom, top); - MultiVariant straightVariant = plainVariant(straightTemplate.create(modelLocation, textures, modelOutput)); - MultiVariant innerVariant = plainVariant(innerTemplate.create(modelLocation.withSuffix("_inner"), textures, modelOutput)); - MultiVariant outerVariant = plainVariant(outerTemplate.create(modelLocation.withSuffix("_outer"), textures, modelOutput)); - blockStateOutput.accept(createStairs(block, innerVariant, straightVariant, outerVariant)); - } - - public void generateStairsBlock(StairBlock block, MultiVariant stairs, MultiVariant stairsInner, MultiVariant stairsOuter) { - blockStateOutput.accept(createStairs(block, stairsInner, stairs, stairsOuter)); - } - - public void generateSlabBlock(SlabBlock block, MultiVariant doubleSlab, Material texture) { - generateSlabBlock(block, doubleSlab, texture, texture, texture); - } - - public void generateSlabBlock(SlabBlock block, MultiVariant doubleSlab, Material side, Material bottom, Material top) { - TextureMapping textures = sideBottomTopTextures(side, bottom, top); - MultiVariant slabTop = plainVariant(ModelTemplates.SLAB_TOP.create(block, textures, modelOutput)); - MultiVariant slabBottom = plainVariant(ModelTemplates.SLAB_BOTTOM.create(block, textures, modelOutput)); - generateSlabBlock(block, slabBottom, slabTop, doubleSlab); - } - - public void generateSlabBlock(SlabBlock block, MultiVariant bottom, MultiVariant top, MultiVariant doubleslab) { - blockStateOutput.accept(createSlab(block, bottom, top, doubleslab)); - } - - public void generateButtonBlock(ButtonBlock block, Material texture) { - TextureMapping textures = TextureMapping.defaultTexture(texture); - MultiVariant button = plainVariant(ModelTemplates.BUTTON.create(block, textures, modelOutput)); - MultiVariant buttonPressed = plainVariant(ModelTemplates.BUTTON_PRESSED.create(block, textures, modelOutput)); - generateButtonBlock(block, button, buttonPressed); - } - - public void generateButtonBlock(ButtonBlock block, MultiVariant button, MultiVariant buttonPressed) { - blockStateOutput.accept(createButton(block, button, buttonPressed)); - } - - public void generatePressurePlateBlock(PressurePlateBlock block, Material texture) { - TextureMapping textures = TextureMapping.defaultTexture(texture); - MultiVariant pressurePlate = plainVariant(ModelTemplates.PRESSURE_PLATE_UP.create(block, textures, modelOutput)); - MultiVariant pressurePlateDown = plainVariant(ModelTemplates.PRESSURE_PLATE_DOWN.create(block, textures, modelOutput)); - generatePressurePlateBlock(block, pressurePlate, pressurePlateDown); - } - - public void generatePressurePlateBlock(PressurePlateBlock block, MultiVariant pressurePlate, MultiVariant pressurePlateDown) { - blockStateOutput.accept(createPressurePlate(block, pressurePlate, pressurePlateDown)); - } - - public void generateSignBlock(StandingSignBlock signBlock, WallSignBlock wallSignBlock, Material texture) { - MultiVariant sign = plainVariant(ModelTemplates.PARTICLE_ONLY.create(signBlock, TextureMapping.particle(texture), modelOutput)); - generateSignBlock(signBlock, wallSignBlock, sign); - } - - public void generateSignBlock(StandingSignBlock signBlock, WallSignBlock wallSignBlock, MultiVariant sign) { - blockStateOutput.accept(createSimpleBlock(signBlock, sign)); - blockStateOutput.accept(createSimpleBlock(wallSignBlock, sign)); - } - - public void generateHangingSignBlock(CeilingHangingSignBlock hangingSignBlock, WallHangingSignBlock wallHangingSignBlock, Material texture) { - MultiVariant hangingSign = plainVariant(ModelTemplates.PARTICLE_ONLY.create(hangingSignBlock, TextureMapping.particle(texture), modelOutput)); - generateHangingSignBlock(hangingSignBlock, wallHangingSignBlock, hangingSign); - } - - public void generateHangingSignBlock(CeilingHangingSignBlock hangingSignBlock, WallHangingSignBlock wallHangingSignBlock, MultiVariant hangingSign) { - blockStateOutput.accept(createSimpleBlock(hangingSignBlock, hangingSign)); - blockStateOutput.accept(createSimpleBlock(wallHangingSignBlock, hangingSign)); - } - - public void generateFourWayBlock(CrossCollisionBlock block, MultiVariant post, MultiVariant side) { - MultiPartGenerator builder = MultiPartGenerator.multiPart(block).with(post); - generateFourWayMultipart(builder, side); - } - - public void generateFourWayMultipart(MultiPartGenerator builder, MultiVariant side) { - PipeBlock.PROPERTY_BY_DIRECTION.forEach((direction, property) -> { - if (direction.getAxis().isHorizontal()) { - VariantMutator yRot = switch (direction) { - case NORTH -> NOP; - case EAST -> Y_ROT_90; - case SOUTH -> Y_ROT_180; - case WEST -> Y_ROT_270; - default -> throw new IllegalStateException(); - }; - builder.with(condition().term(property, true), side.with(UV_LOCK.then(yRot))); - } - }); - blockStateOutput.accept(builder); - } - - public void generateFenceBlock(FenceBlock block, Material texture) { - generateFenceBlockInternal(block, texture, ModelTemplates.FENCE_POST, ModelTemplates.FENCE_SIDE); - } - - public void generateFenceBlock(FenceBlock block, String name, Material texture) { - generateFenceBlockInternal(block, name, texture, ModelTemplates.FENCE_POST, ModelTemplates.FENCE_SIDE); - } - - private void generateFenceBlockInternal(FenceBlock block, Material texture, ModelTemplate fencePostTemplate, ModelTemplate fenceSideTemplate) { - TextureMapping textures = TextureMapping.defaultTexture(texture); - generateFourWayBlock(block, - plainVariant(fencePostTemplate.create(block, textures, modelOutput)), - plainVariant(fenceSideTemplate.create(block, textures, modelOutput))); - } - - private void generateFenceBlockInternal(FenceBlock block, String name, Material texture, ModelTemplate fencePostTemplate, ModelTemplate fenceSideTemplate) { - TextureMapping textures = TextureMapping.defaultTexture(texture); - generateFourWayBlock(block, - plainVariant(fencePostTemplate.create(modLoc("block/" + name + "_fence_post"), textures, modelOutput)), - plainVariant(fenceSideTemplate.create(modLoc("block/" + name + "_fence_side"), textures, modelOutput))); - } - - public void generateFenceGateBlock(FenceGateBlock block, Material texture) { - TextureMapping textures = TextureMapping.defaultTexture(texture); - generateFenceGateBlock(block, - plainVariant(ModelTemplates.FENCE_GATE_CLOSED.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.FENCE_GATE_OPEN.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.FENCE_GATE_WALL_CLOSED.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.FENCE_GATE_WALL_OPEN.create(block, textures, modelOutput))); - } - - public void generateFenceGateBlock(FenceGateBlock block, String name, Material texture) { - generateFenceGateBlockInternal(block, modLoc(name + "_fence_gate"), texture, ModelTemplates.FENCE_GATE_CLOSED, ModelTemplates.FENCE_GATE_OPEN, ModelTemplates.FENCE_GATE_WALL_CLOSED, ModelTemplates.FENCE_GATE_WALL_OPEN); - } - - private void generateFenceGateBlockInternal(FenceGateBlock block, Identifier baseName, Material texture, ModelTemplate closedTemplate, ModelTemplate openTemplate, ModelTemplate wallClosedTemplate, ModelTemplate wallOpenTemplate) { - Identifier baseModel = baseName.withPrefix("block/"); - TextureMapping textures = TextureMapping.defaultTexture(texture); - MultiVariant gate = plainVariant(closedTemplate.create(baseModel, textures, modelOutput)); - MultiVariant gateOpen = plainVariant(openTemplate.create(baseModel.withSuffix("_open"), textures, modelOutput)); - MultiVariant gateWall = plainVariant(wallClosedTemplate.create(baseModel.withSuffix("_wall"), textures, modelOutput)); - MultiVariant gateWallOpen = plainVariant(wallOpenTemplate.create(baseModel.withSuffix("_wall_open"), textures, modelOutput)); - generateFenceGateBlock(block, gate, gateOpen, gateWall, gateWallOpen); - } - - public void generateFenceGateBlock(FenceGateBlock block, MultiVariant gate, MultiVariant gateOpen, MultiVariant gateWall, MultiVariant gateWallOpen) { - blockStateOutput.accept(createFenceGate(block, gateOpen, gate, gateWallOpen, gateWall, true)); - } - - public void generateWallBlock(WallBlock block, Material texture) { - TextureMapping textures = TextureMapping.singleSlot(TextureSlot.WALL, texture); - blockStateOutput.accept(createWall(block, - plainVariant(ModelTemplates.WALL_POST.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.WALL_LOW_SIDE.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.WALL_TALL_SIDE.create(block, textures, modelOutput)))); - } - - public void generateWallBlock(WallBlock block, String name, Material texture) { - Identifier baseName = modLoc(name + "_wall"); - generateWallBlockInternal(block, baseName, texture, ModelTemplates.WALL_POST, ModelTemplates.WALL_LOW_SIDE, ModelTemplates.WALL_TALL_SIDE); - } - - private void generateWallBlockInternal(WallBlock block, Identifier baseName, Material texture, ModelTemplate postTemplate, ModelTemplate sideTemplate, ModelTemplate tallSideTemplate) { - TextureMapping textures = TextureMapping.singleSlot(TextureSlot.WALL, texture); - Identifier baseModel = baseName.withPrefix("block/"); - generateWallBlock(block, - plainVariant(postTemplate.create(baseModel.withSuffix("_post"), textures, modelOutput)), - plainVariant(sideTemplate.create(baseModel.withSuffix("_side"), textures, modelOutput)), - plainVariant(tallSideTemplate.create(baseModel.withSuffix("_side_tall"), textures, modelOutput))); - } - - public void generateWallBlock(WallBlock block, MultiVariant post, MultiVariant side, MultiVariant sideTall) { - blockStateOutput.accept(createWall(block, post, side, sideTall)); - } - - public void generatePaneBlock(IronBarsBlock block, Material pane, Material edge) { - TextureMapping textures = new TextureMapping().put(TextureSlot.PANE, pane).put(TextureSlot.EDGE, edge); - generatePaneBlock(block, - plainVariant(ModelTemplates.STAINED_GLASS_PANE_POST.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.STAINED_GLASS_PANE_SIDE.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.STAINED_GLASS_PANE_SIDE_ALT.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.STAINED_GLASS_PANE_NOSIDE.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.STAINED_GLASS_PANE_NOSIDE_ALT.create(block, textures, modelOutput))); - } - - public void generatePaneBlock(IronBarsBlock block, String name, Material pane, Material edge) { - Identifier baseName = modLoc(name + "_pane"); - generatePaneBlockInternal(block, baseName, pane, edge, ModelTemplates.STAINED_GLASS_PANE_POST, ModelTemplates.STAINED_GLASS_PANE_SIDE, ModelTemplates.STAINED_GLASS_PANE_SIDE_ALT, ModelTemplates.STAINED_GLASS_PANE_NOSIDE, ModelTemplates.STAINED_GLASS_PANE_NOSIDE_ALT); - } - - private void generatePaneBlockInternal(IronBarsBlock block, Identifier baseName, Material pane, Material edge, ModelTemplate postTemplate, ModelTemplate sideTemplate, ModelTemplate sideAltTemplate, ModelTemplate noSideTemplate, ModelTemplate noSideAltTemplate) { - Identifier baseModel = baseName.withPrefix("block/"); - TextureMapping textures = new TextureMapping().put(TextureSlot.PANE, pane).put(TextureSlot.EDGE, edge); - generatePaneBlock(block, - plainVariant(postTemplate.create(baseModel.withSuffix("_post"), textures, modelOutput)), - plainVariant(sideTemplate.create(baseModel.withSuffix("_side"), textures, modelOutput)), - plainVariant(sideAltTemplate.create(baseModel.withSuffix("_side_alt"), textures, modelOutput)), - plainVariant(noSideTemplate.create(baseModel.withSuffix("_noside"), textures, modelOutput)), - plainVariant(noSideAltTemplate.create(baseModel.withSuffix("_noside_alt"), textures, modelOutput))); - } - - public void generatePaneBlock(IronBarsBlock block, MultiVariant post, MultiVariant side, MultiVariant sideAlt, MultiVariant noSide, MultiVariant noSideAlt) { - blockStateOutput.accept(MultiPartGenerator.multiPart(block) - .with(post) - .with(condition().term(BlockStateProperties.NORTH, true), side) - .with(condition().term(BlockStateProperties.EAST, true), side.with(Y_ROT_90)) - .with(condition().term(BlockStateProperties.SOUTH, true), sideAlt) - .with(condition().term(BlockStateProperties.WEST, true), sideAlt.with(Y_ROT_90)) - .with(condition().term(BlockStateProperties.NORTH, false), noSide) - .with(condition().term(BlockStateProperties.EAST, false), noSideAlt) - .with(condition().term(BlockStateProperties.SOUTH, false), noSideAlt.with(Y_ROT_90)) - .with(condition().term(BlockStateProperties.WEST, false), noSide.with(Y_ROT_270))); - } - - public void generateDoorBlock(DoorBlock block, Material bottom, Material top) { - TextureMapping textures = TextureMapping.door(top, bottom); - generateDoorBlock(block, - plainVariant(ModelTemplates.DOOR_BOTTOM_LEFT.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.DOOR_BOTTOM_LEFT_OPEN.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.DOOR_BOTTOM_RIGHT.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.DOOR_BOTTOM_RIGHT_OPEN.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.DOOR_TOP_LEFT.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.DOOR_TOP_LEFT_OPEN.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.DOOR_TOP_RIGHT.create(block, textures, modelOutput)), - plainVariant(ModelTemplates.DOOR_TOP_RIGHT_OPEN.create(block, textures, modelOutput))); + @Override + public RegistrateItemModelGenerator itemModels() { + return itemModels; } - public void generateDoorBlock(DoorBlock block, String name, Material bottom, Material top) { - generateDoorBlockInternal(block, modLoc(name + "_door"), bottom, top); + public void create(Block block, ResourceLocation model) { + simpleBlock(block, models().getExistingFile(model)); } - private void generateDoorBlockInternal(DoorBlock block, Identifier baseName, Material bottom, Material top) { - generateDoorBlockInternal(block, baseName, bottom, top, ModelTemplates.DOOR_BOTTOM_LEFT, ModelTemplates.DOOR_BOTTOM_LEFT_OPEN, ModelTemplates.DOOR_BOTTOM_RIGHT, ModelTemplates.DOOR_BOTTOM_RIGHT_OPEN, ModelTemplates.DOOR_TOP_LEFT, ModelTemplates.DOOR_TOP_LEFT_OPEN, ModelTemplates.DOOR_TOP_RIGHT, ModelTemplates.DOOR_TOP_RIGHT_OPEN); + public void createTrivialCube(Block block) { + simpleBlock(block, models().cubeAll(modelLocation(block).getPath(), blockTexture(block))); } - private void generateDoorBlockInternal(DoorBlock block, Identifier baseName, Material bottom, Material top, ModelTemplate bottomLeftTemplate, ModelTemplate bottomLeftOpenTemplate, ModelTemplate bottomRightTemplate, ModelTemplate bottomRightOpenTemplate, ModelTemplate topLeftTemplate, ModelTemplate topLeftOpenTemplate, ModelTemplate topRightTemplate, ModelTemplate topRightOpenTemplate) { - Identifier baseModel = baseName.withPrefix("block/"); - TextureMapping textures = TextureMapping.door(top, bottom); - MultiVariant bottomLeft = plainVariant(bottomLeftTemplate.create(baseModel.withSuffix("_bottom_left"), textures, modelOutput)); - MultiVariant bottomLeftOpen = plainVariant(bottomLeftOpenTemplate.create(baseModel.withSuffix("_bottom_left_open"), textures, modelOutput)); - MultiVariant bottomRight = plainVariant(bottomRightTemplate.create(baseModel.withSuffix("_bottom_right"), textures, modelOutput)); - MultiVariant bottomRightOpen = plainVariant(bottomRightOpenTemplate.create(baseModel.withSuffix("_bottom_right_open"), textures, modelOutput)); - MultiVariant topLeft = plainVariant(topLeftTemplate.create(baseModel.withSuffix("_top_left"), textures, modelOutput)); - MultiVariant topLeftOpen = plainVariant(topLeftOpenTemplate.create(baseModel.withSuffix("_top_left_open"), textures, modelOutput)); - MultiVariant topRight = plainVariant(topRightTemplate.create(baseModel.withSuffix("_top_right"), textures, modelOutput)); - MultiVariant topRightOpen = plainVariant(topRightOpenTemplate.create(baseModel.withSuffix("_top_right_open"), textures, modelOutput)); - generateDoorBlock(block, bottomLeft, bottomLeftOpen, bottomRight, bottomRightOpen, topLeft, topLeftOpen, topRight, topRightOpen); + public ResourceLocation mcBlockTexture(String path) { + return mcLoc("block/" + path); } - public void generateDoorBlock(DoorBlock block, MultiVariant bottomLeft, MultiVariant bottomLeftOpen, MultiVariant bottomRight, MultiVariant bottomRightOpen, MultiVariant topLeft, MultiVariant topLeftOpen, MultiVariant topRight, MultiVariant topRightOpen) { - blockStateOutput.accept(createDoor(block, bottomLeft, bottomLeftOpen, bottomRight, bottomRightOpen, topLeft, topLeftOpen, topRight, topRightOpen)); + public ResourceLocation modBlockTexture(String path) { + return modLoc("block/" + path); } - public void generateTrapdoorBlock(TrapDoorBlock block, Material texture, boolean orientable) { - TextureMapping textures = TextureMapping.defaultTexture(texture); - generateTrapdoorBlock(block, - plainVariant((orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_BOTTOM : ModelTemplates.TRAPDOOR_BOTTOM).create(block, textures, modelOutput)), - plainVariant((orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_TOP : ModelTemplates.TRAPDOOR_TOP).create(block, textures, modelOutput)), - plainVariant((orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_OPEN : ModelTemplates.TRAPDOOR_OPEN).create(block, textures, modelOutput)), - orientable); + public ResourceLocation blockTexture(Block block, String suffix) { + return blockTexture(block).withSuffix(suffix); } - public void generateTrapdoorBlock(TrapDoorBlock block, String name, Material texture, boolean orientable) { - generateTrapdoorBlockInternal(block, modLoc(name + "_trapdoor"), texture, orientable); + public static ResourceLocation modelLocation(Block block) { + return BuiltInRegistries.BLOCK.getKey(block).withPrefix("block/"); } - private void generateTrapdoorBlockInternal(TrapDoorBlock block, Identifier baseName, Material texture, boolean orientable) { - generateTrapdoorBlockInternal(block, baseName, texture, orientable, - orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_BOTTOM : ModelTemplates.TRAPDOOR_BOTTOM, - orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_TOP : ModelTemplates.TRAPDOOR_TOP, - orientable ? ModelTemplates.ORIENTABLE_TRAPDOOR_OPEN : ModelTemplates.TRAPDOOR_OPEN); + public Optional getExistingVariantBuilder(Block block) { + return Optional.ofNullable(registeredBlocks.get(block)) + .filter(VariantBlockStateBuilder.class::isInstance) + .map(VariantBlockStateBuilder.class::cast); } - private void generateTrapdoorBlockInternal(TrapDoorBlock block, Identifier baseName, Material texture, boolean orientable, ModelTemplate bottomTemplate, ModelTemplate topTemplate, ModelTemplate openTemplate) { - Identifier baseModel = baseName.withPrefix("block/"); - TextureMapping textures = TextureMapping.defaultTexture(texture); - MultiVariant bottom = plainVariant(bottomTemplate.create(baseModel.withSuffix("_bottom"), textures, modelOutput)); - MultiVariant top = plainVariant(topTemplate.create(baseModel.withSuffix("_top"), textures, modelOutput)); - MultiVariant open = plainVariant(openTemplate.create(baseModel.withSuffix("_open"), textures, modelOutput)); - generateTrapdoorBlock(block, bottom, top, open, orientable); + public Optional getExistingMultipartBuilder(Block block) { + return Optional.ofNullable(registeredBlocks.get(block)) + .filter(MultiPartBlockStateBuilder.class::isInstance) + .map(MultiPartBlockStateBuilder.class::cast); } - public void generateTrapdoorBlock(TrapDoorBlock block, MultiVariant bottom, MultiVariant top, MultiVariant open, boolean orientable) { - blockStateOutput.accept(orientable ? createOrientableTrapdoor(block, top, bottom, open) : createTrapdoor(block, top, bottom, open)); + public Optional getSingleVariantModel(Block block) { + return getExistingVariantBuilder(block) + .map(builder -> builder.getModels().get(builder.partialState())) + .map(ConfiguredModelList::toJSON) + .filter(JsonElement::isJsonObject) + .map(json -> json.getAsJsonObject().get("model")) + .map(JsonElement::getAsString) + .map(ResourceLocation::parse); } } diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java index 56eaa19..0e6c97c 100644 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java @@ -4,101 +4,80 @@ import com.modularmc.registrate.providers.core.ProviderType; import com.modularmc.registrate.util.nullness.NonNullSupplier; -import net.minecraft.client.color.item.ItemTintSource; -import net.minecraft.client.data.models.ItemModelGenerators; -import net.minecraft.client.data.models.ItemModelOutput; -import net.minecraft.client.data.models.model.ItemModelUtils; -import net.minecraft.client.data.models.model.ModelInstance; -import net.minecraft.client.data.models.model.ModelLocationUtils; -import net.minecraft.client.data.models.model.ModelTemplate; -import net.minecraft.client.data.models.model.ModelTemplates; -import net.minecraft.client.data.models.model.TextureMapping; -import net.minecraft.client.resources.model.sprite.Material; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.Identifier; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.material.Fluid; -import net.neoforged.neoforge.client.model.item.DynamicFluidContainerModel; +import net.neoforged.neoforge.client.model.generators.ItemModelBuilder; +import net.neoforged.neoforge.client.model.generators.ItemModelProvider; +import net.neoforged.neoforge.client.model.generators.loaders.DynamicFluidContainerModelBuilder; +import net.neoforged.neoforge.common.data.ExistingFileHelper; -import java.util.Optional; -import java.util.function.BiConsumer; import java.util.function.UnaryOperator; -public class RegistrateItemModelGenerator extends ItemModelGenerators { +public class RegistrateItemModelGenerator extends ItemModelProvider { private final AbstractRegistrate parent; - public RegistrateItemModelGenerator(AbstractRegistrate parent, ItemModelOutput output, BiConsumer model) { - super(output, model); + public RegistrateItemModelGenerator(AbstractRegistrate parent, PackOutput output, ExistingFileHelper fileHelper) { + super(output, parent.getModid(), fileHelper); this.parent = parent; } @Override - public void run() { + protected void registerModels() { parent.genData(ProviderType.ITEM_MODEL, this); } - public void createWithExistingModel(Item item, Identifier id) { - itemModelOutput.accept(item, ItemModelUtils.plainModel(id)); + public boolean hasModel(Item item) { + return generatedModels.containsKey(itemLocation(item)); } - public void generateWithTemplate(Item item, ModelTemplate template, TextureMapping textures) { - itemModelOutput.accept(item, ItemModelUtils.plainModel(template.create(item, textures, modelOutput))); + public ItemModelBuilder createWithExistingModel(Item item, ResourceLocation model) { + return withExistingParent(itemLocation(item).toString(), model); } - public void generateFlatItem(Item item, Material layer0) { - generateFlatItem(item, ModelTemplates.FLAT_ITEM, layer0); + public ItemModelBuilder generateFlatItem(Item item, ResourceLocation texture) { + return generateFlatItem(item, mcLoc("item/generated"), texture); } - public void generateFlatItem(Item item, ModelTemplate template, Material layer0) { - itemModelOutput.accept(item, ItemModelUtils.plainModel(template.create(item, TextureMapping.layer0(layer0), modelOutput))); + public ItemModelBuilder generateFlatItem(Item item, ResourceLocation parentModel, ResourceLocation texture) { + return createWithExistingModel(item, parentModel).texture("layer0", texture); } - public void generateFlatItem(Item item, ModelTemplate template, TextureMapping textures, ItemTintSource... tints) { - Identifier model = template.create(item, textures, modelOutput); - itemModelOutput.accept(item, tints.length == 0 ? ItemModelUtils.plainModel(model) : ItemModelUtils.tintedModel(model, tints)); + public ItemModelBuilder generateFlatBlockItem(BlockItem item) { + return generateFlatBlockItem(item, ""); } - public void generateFlatBlockItem(BlockItem item) { - generateFlatItem(item, TextureMapping.getBlockTexture(item.getBlock())); + public ItemModelBuilder generateFlatBlockItem(BlockItem item, String suffix) { + return generateFlatItem(item, RegistrateBlockModelGenerator.modelLocation(item.getBlock()).withSuffix(suffix)); } - public void generateFlatBlockItem(BlockItem item, String suffix) { - generateFlatItem(item, TextureMapping.getBlockTexture(item.getBlock(), suffix)); + public ItemModelBuilder generateBlockItem(BlockItem item, UnaryOperator modelMapper) { + return createWithExistingModel(item, modelMapper.apply(RegistrateBlockModelGenerator.modelLocation(item.getBlock()))); } - public void generateBlockItem(BlockItem item, UnaryOperator modelMapper) { - itemModelOutput.accept(item, ItemModelUtils.plainModel(modelMapper.apply(ModelLocationUtils.getModelLocation(item.getBlock())))); + public ItemModelBuilder generateBlockItem(BlockItem item, String suffix) { + return generateBlockItem(item, model -> model.withSuffix(suffix)); } - public void generateBlockItem(BlockItem item, String suffix) { - generateBlockItem(item, model -> model.withSuffix(suffix)); + public ResourceLocation mcBlockTexture(String path) { + return mcLoc("block/" + path); } - public Identifier mcLoc(String id) { - return Identifier.withDefaultNamespace(id); + public ResourceLocation modBlockTexture(String path) { + return modLoc("block/" + path); } - public Identifier modLoc(String id) { - return Identifier.fromNamespaceAndPath(parent.getModid(), id); + public ResourceLocation mcItemTexture(String path) { + return mcLoc("item/" + path); } - public Material mcBlockTexture(String path) { - return new Material(mcLoc("block/" + path)); - } - - public Material modBlockTexture(String path) { - return new Material(modLoc("block/" + path)); - } - - public Material mcItemTexture(String path) { - return new Material(mcLoc("item/" + path)); - } - - public Material modItemTexture(String path) { - return new Material(modLoc("item/" + path)); + public ResourceLocation modItemTexture(String path) { + return modLoc("item/" + path); } public String modid(NonNullSupplier item) { @@ -109,20 +88,19 @@ public String name(NonNullSupplier item) { return BuiltInRegistries.ITEM.getKey(item.get().asItem()).getPath(); } - public void generateTintedModel(Item entry, Identifier model, ItemTintSource tint) { - this.itemModelOutput.accept(entry, ItemModelUtils.tintedModel(model, tint)); - } - public void generateFluidBucket(Item item, Fluid fluid) { - itemModelOutput.accept(item, new DynamicFluidContainerModel.Unbaked( - new DynamicFluidContainerModel.Textures( - Optional.of(mcItemTexture("bucket")), - Optional.of(mcItemTexture("bucket")), - Optional.of(new Material(Identifier.fromNamespaceAndPath("neoforge", "item/mask/bucket_fluid"))), - Optional.empty()), - fluid, - true, - true, - true)); + getBuilder(itemLocation(item).toString()) + .texture("particle", mcItemTexture("bucket")) + .texture("base", mcItemTexture("bucket")) + .texture("fluid", ResourceLocation.fromNamespaceAndPath("neoforge", "item/mask/bucket_fluid")) + .customLoader(DynamicFluidContainerModelBuilder::begin) + .fluid(fluid) + .flipGas(true) + .applyFluidLuminosity(true) + .end(); + } + + private static ResourceLocation itemLocation(Item item) { + return BuiltInRegistries.ITEM.getKey(item).withPrefix("item/"); } } diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java deleted file mode 100644 index 8e85469..0000000 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateLegacyBlockModelBuilder.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.modularmc.registrate.providers.generators; - -import net.minecraft.client.data.models.model.ModelInstance; -import net.minecraft.client.data.models.model.TextureMapping; -import net.minecraft.client.data.models.model.TextureSlot; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.client.resources.model.sprite.Material; -import net.minecraft.resources.Identifier; -import net.minecraft.world.item.ItemDisplayContext; -import net.minecraft.world.level.block.Block; -import net.neoforged.neoforge.client.model.generators.template.CustomLoaderBuilder; -import net.neoforged.neoforge.client.model.generators.template.ExtendedModelTemplateBuilder; -import net.neoforged.neoforge.client.model.generators.template.RootTransformsBuilder; -import net.neoforged.neoforge.client.model.generators.template.TransformVecBuilder; - -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class RegistrateLegacyBlockModelBuilder { - - private final ExtendedModelTemplateBuilder template; - private final TextureMapping texture; - private final BiConsumer output; - - RegistrateLegacyBlockModelBuilder(BiConsumer output, ExtendedModelTemplateBuilder template, TextureMapping texture) { - this.output = output; - this.template = template; - this.texture = texture.copy(); - } - - public RegistrateLegacyBlockModelBuilder texture(TextureSlot slot, Material texture) { - this.template.requiredTextureSlot(slot); - this.texture.put(slot, texture); - return this; - } - - public RegistrateLegacyBlockModelBuilder transformTemplate(Consumer action) { - action.accept(template); - return this; - } - - public RegistrateLegacyBlockModelBuilder transformTexture(Consumer action) { - action.accept(texture); - return this; - } - - public Identifier build(Block block) { - return template.build().create(block, texture, output); - } - - public Identifier build(Identifier loc) { - return template.build().create(loc, texture, output); - } - - // Delegated methods from Template Builder - - /** - * Parent model which this template will inherit its properties from. - */ - public RegistrateLegacyBlockModelBuilder parent(Identifier parent) { - template.parent(parent); - return this; - } - - /** - * Suffix appended onto the models file path. - */ - public RegistrateLegacyBlockModelBuilder suffix(String suffix) { - template.suffix(suffix); - return this; - } - - /** - * Begin building a new transform for the given perspective. - * - * @param type the perspective to create or return the builder for - * @return the builder for the given perspective - * @throws NullPointerException if {@code type} is {@code null} - */ - public RegistrateLegacyBlockModelBuilder transform(ItemDisplayContext type, Consumer action) { - template.transform(type, action); - return this; - } - - /** - * Sets whether or not this model should apply ambient occlusion. - */ - public RegistrateLegacyBlockModelBuilder ambientOcclusion(boolean ambientOcclusion) { - template.ambientOcclusion(ambientOcclusion); - return this; - } - - /** - * Sets the gui light style for this model. - * - *

    - *
  • {@link UnbakedModel.GuiLight#FRONT} for head on light, commonly used for items.
  • - *
  • {@link UnbakedModel.GuiLight#SIDE} for the model to be side lit, commonly used for blocks.
  • - *
- */ - public RegistrateLegacyBlockModelBuilder guiLight(UnbakedModel.GuiLight light) { - template.guiLight(light); - return this; - } - - /** - * Use a custom loader instead of the vanilla elements. - * - * @param customLoaderFactory function that returns the custom loader to set, given this - * @return the custom loader builder - */ - public RegistrateLegacyBlockModelBuilder customLoader(Supplier customLoaderFactory, Consumer action) { - template.customLoader(customLoaderFactory, action); - return this; - } - - /** - * Modifies the transformation applied right before item display transformations and rotations specified in block - * states. - */ - public RegistrateLegacyBlockModelBuilder rootTransforms(Consumer action) { - template.rootTransforms(action); - return this; - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java index 4b19029..c3656b0 100644 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java @@ -3,38 +3,19 @@ import com.modularmc.registrate.AbstractRegistrate; import com.modularmc.registrate.providers.core.RegistrateProvider; -import net.minecraft.client.data.models.BlockModelGenerators; -import net.minecraft.client.data.models.ItemModelGenerators; -import net.minecraft.client.data.models.ModelProvider; -import net.minecraft.client.renderer.block.dispatch.BlockStateModelDispatcher; import net.minecraft.data.PackOutput; import net.neoforged.fml.LogicalSide; +import net.neoforged.neoforge.common.data.ExistingFileHelper; -import com.mojang.serialization.JsonOps; +public class RegistrateModelProvider extends RegistrateBlockModelGenerator implements RegistrateProvider { -public class RegistrateModelProvider extends ModelProvider implements RegistrateProvider { - - private final AbstractRegistrate parent; - - public RegistrateModelProvider(AbstractRegistrate parent, PackOutput p_388260_) { - super(p_388260_, parent.getModid()); - this.parent = parent; + public RegistrateModelProvider(AbstractRegistrate parent, PackOutput output, ExistingFileHelper fileHelper) { + super(parent, output, fileHelper); } @Override - protected void registerModels(BlockModelGenerators blockModels, ItemModelGenerators itemModels) { - var registrateBlockModels = new RegistrateBlockModelGenerator(parent, blockModels.blockStateOutput, blockModels.itemModelOutput, blockModels.modelOutput); - registrateBlockModels.run(); - registrateBlockModels.seenBlockstates.forEach((block, dispatcher) -> validateBlockStateEncoding(block, dispatcher)); - new RegistrateItemModelGenerator(parent, itemModels.itemModelOutput, itemModels.modelOutput).run(); - } - - private static void validateBlockStateEncoding(net.minecraft.world.level.block.Block block, BlockStateModelDispatcher dispatcher) { - try { - BlockStateModelDispatcher.CODEC.encodeStart(JsonOps.INSTANCE, dispatcher); - } catch (RuntimeException ex) { - throw new IllegalStateException("Failed to encode blockstate definition for " + block.builtInRegistryHolder().key().identifier(), ex); - } + public String getName() { + return "Blockstates and item models"; } @Override diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java index 6dcada7..515a542 100644 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java @@ -1,115 +1,147 @@ package com.modularmc.registrate.providers.generators; +import com.modularmc.registrate.AbstractRegistrate; import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.core.RegistrateProvider; import com.modularmc.registrate.util.DataIngredient; import com.modularmc.registrate.util.nullness.NonNullSupplier; +import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.Criterion; -import net.minecraft.advancements.criterion.EnterBlockTrigger; -import net.minecraft.advancements.criterion.InventoryChangeTrigger; -import net.minecraft.advancements.criterion.ItemPredicate; -import net.minecraft.advancements.criterion.MinMaxBounds; +import net.minecraft.advancements.critereon.EnterBlockTrigger; +import net.minecraft.advancements.critereon.InventoryChangeTrigger; +import net.minecraft.advancements.critereon.ItemPredicate; +import net.minecraft.advancements.critereon.MinMaxBounds; import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.data.BlockFamily; -import net.minecraft.data.recipes.*; -import net.minecraft.resources.Identifier; +import net.minecraft.data.CachedOutput; +import net.minecraft.data.PackOutput; +import net.minecraft.data.recipes.RecipeBuilder; +import net.minecraft.data.recipes.RecipeCategory; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.data.recipes.RecipeProvider; +import net.minecraft.data.recipes.ShapedRecipeBuilder; +import net.minecraft.data.recipes.ShapelessRecipeBuilder; +import net.minecraft.data.recipes.SimpleCookingRecipeBuilder; +import net.minecraft.data.recipes.SingleItemRecipeBuilder; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.entity.EntityType; import net.minecraft.world.flag.FeatureFlagSet; import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStackTemplate; import net.minecraft.world.item.crafting.*; -import net.minecraft.world.item.equipment.trim.TrimPattern; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.SuspiciousEffectHolder; +import net.neoforged.fml.LogicalSide; import net.neoforged.neoforge.common.Tags; +import net.neoforged.neoforge.common.conditions.ICondition; -import lombok.experimental.Delegate; +import com.google.common.collect.ImmutableMap; import org.jspecify.annotations.Nullable; import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import javax.annotation.CheckReturnValue; import javax.annotation.processing.Generated; -public class RegistrateRecipeProvider extends RecipeProvider implements RecipeOutput { +public class RegistrateRecipeProvider extends RecipeProvider implements RegistrateProvider, RecipeOutput { - private final RegistrateRecipeRunner runner; + private final AbstractRegistrate owner; + private final CompletableFuture lookupProvider; + private @Nullable RecipeOutput callback; - @Delegate - private final RecipeOutput outputDelegated; - - private final HolderLookup itemLookup; - private final HolderLookup blockLookup; - private final HolderLookup> entityLookup; - - public RegistrateRecipeProvider(RegistrateRecipeRunner runner, HolderLookup.Provider registries, RecipeOutput output) { - super(registries, output); - this.runner = runner; - this.outputDelegated = output; - itemLookup = registries.lookupOrThrow(Registries.ITEM); - blockLookup = registries.lookupOrThrow(Registries.BLOCK); - entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE); - } - - @Override - public void buildRecipes() { - runner.provider = this; - runner.owner.genData(ProviderType.RECIPE, this); - runner.provider = null; + public RegistrateRecipeProvider(AbstractRegistrate owner, PackOutput output, CompletableFuture lookupProvider) { + super(output, lookupProvider); + this.owner = owner; + this.lookupProvider = lookupProvider; } public HolderLookup.Provider registries() { - return registries; + return Objects.requireNonNull(lookupProvider.getNow(null), "Recipe registry lookup is not ready"); } public HolderLookup itemLookup() { - return itemLookup; + return registries().lookupOrThrow(Registries.ITEM); } public HolderLookup blockLookup() { - return blockLookup; + return registries().lookupOrThrow(Registries.BLOCK); } public HolderLookup> entityLookup() { - return entityLookup; + return registries().lookupOrThrow(Registries.ENTITY_TYPE); } public Holder resolve(ResourceKey key) { - return registries.lookupOrThrow(key.registryKey()).getOrThrow(key); + return registries().lookupOrThrow(key.registryKey()).getOrThrow(key); } - public Identifier safeId(Identifier id) { - return Identifier.fromNamespaceAndPath(runner.owner.getModid(), safeName(id)); + @Override + public LogicalSide getSide() { + return LogicalSide.SERVER; } - public Identifier safeId(DataIngredient source) { - return safeId(source.getId()); + @Override + public void accept(ResourceLocation id, Recipe recipe, @Nullable AdvancementHolder advancement, ICondition... conditions) { + recipeOutput().accept(id, recipe, advancement, conditions); } - public Identifier safeId(ItemLike registryEntry) { - return safeId(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); + @Override + public Advancement.Builder advancement() { + return recipeOutput().advancement(); + } + + private RecipeOutput recipeOutput() { + return Objects.requireNonNull(callback, "Recipe output is only available inside a recipe callback"); + } + + @Override + protected void buildRecipes(RecipeOutput output) { + callback = output; + try { + owner.genData(ProviderType.RECIPE, this); + } finally { + callback = null; + } } - public ResourceKey> safeKey(Identifier id) { - return ResourceKey.create(Registries.RECIPE, Identifier.fromNamespaceAndPath(runner.owner.getModid(), safeName(id))); + public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike result) { + return ShapedRecipeBuilder.shaped(category, result); } - public ResourceKey> safeKey(DataIngredient source) { - return safeKey(source.getId()); + public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike result, int count) { + return ShapedRecipeBuilder.shaped(category, result, count); } - public ResourceKey> safeKey(ItemLike registryEntry) { - return safeKey(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); + public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike result) { + return ShapelessRecipeBuilder.shapeless(category, result); } - public String safeName(Identifier id) { + public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike result, int count) { + return ShapelessRecipeBuilder.shapeless(category, result, count); + } + + public ResourceLocation safeId(ResourceLocation id) { + return ResourceLocation.fromNamespaceAndPath(owner.getModid(), safeName(id)); + } + + public ResourceLocation safeId(DataIngredient source) { + return safeId(source.getId()); + } + + public ResourceLocation safeId(ItemLike registryEntry) { + return safeId(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); + } + + public String safeName(ResourceLocation id) { return id.getPath().replace('/', '_'); } @@ -126,42 +158,53 @@ public String safeName(ItemLike registryEntry) { public static final int DEFAULT_SMOKE_TIME = DEFAULT_BLAST_TIME; public static final int DEFAULT_CAMPFIRE_TIME = DEFAULT_SMELT_TIME * 3; - public void cooking(DataIngredient source, RecipeCategory craftingCategory, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime, String typeName, AbstractCookingRecipe.Factory factory) { - SimpleCookingRecipeBuilder.generic(source.toVanilla(), craftingCategory, cookingCategory, result.get(), experience, cookingTime, factory) + private static final ImmutableMap, String> COOKING_TYPE_NAMES = ImmutableMap., String>builder() + .put(RecipeSerializer.SMELTING_RECIPE, "smelting") + .put(RecipeSerializer.BLASTING_RECIPE, "blasting") + .put(RecipeSerializer.SMOKING_RECIPE, "smoking") + .put(RecipeSerializer.CAMPFIRE_COOKING_RECIPE, "campfire") + .build(); + + public void cooking(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime, RecipeSerializer serializer, AbstractCookingRecipe.Factory factory) { + cooking(source, category, result, experience, cookingTime, COOKING_TYPE_NAMES.get(serializer), serializer, factory); + } + + public void cooking(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime, String typeName, RecipeSerializer serializer, AbstractCookingRecipe.Factory factory) { + SimpleCookingRecipeBuilder.generic(source.toVanilla(), category, result.get(), experience, cookingTime, serializer, factory) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) .save(this, safeId(result.get()) + "_from_" + safeName(source) + "_" + typeName); } - public void smelting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { - smelting(source, category, cookingCategory, result, experience, DEFAULT_SMELT_TIME); + public void smelting(DataIngredient source, RecipeCategory category, Supplier result, float experience) { + smelting(source, category, result, experience, DEFAULT_SMELT_TIME); } - public void smelting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { - cooking(source, category, cookingCategory, result, experience, cookingTime, "smelting", SmeltingRecipe::new); + public void smelting(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { + cooking(source, category, result, experience, cookingTime, RecipeSerializer.SMELTING_RECIPE, SmeltingRecipe::new); } - public void blasting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { - blasting(source, category, cookingCategory, result, experience, DEFAULT_BLAST_TIME); + public void blasting(DataIngredient source, RecipeCategory category, Supplier result, float experience) { + blasting(source, category, result, experience, DEFAULT_BLAST_TIME); } - public void blasting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { - cooking(source, category, cookingCategory, result, experience, cookingTime, "blasting", BlastingRecipe::new); + public void blasting(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { + cooking(source, category, result, experience, cookingTime, RecipeSerializer.BLASTING_RECIPE, BlastingRecipe::new); } - public void smoking(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { - smoking(source, category, cookingCategory, result, experience, DEFAULT_SMOKE_TIME); + public void smoking(DataIngredient source, RecipeCategory category, Supplier result, float experience) { + smoking(source, category, result, experience, DEFAULT_SMOKE_TIME); } - public void smoking(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { - cooking(source, category, cookingCategory, result, experience, cookingTime, "smoking", SmokingRecipe::new); + public void smoking(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { + cooking(source, category, result, experience, cookingTime, RecipeSerializer.SMOKING_RECIPE, SmokingRecipe::new); } - public void campfire(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience) { - campfire(source, category, cookingCategory, result, experience, DEFAULT_CAMPFIRE_TIME); + public void campfire(DataIngredient source, RecipeCategory category, Supplier result, float experience) { + campfire(source, category, result, experience, DEFAULT_CAMPFIRE_TIME); } - public void campfire(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float experience, int cookingTime) { - cooking(source, category, cookingCategory, result, experience, cookingTime, "campfire", CampfireCookingRecipe::new); + public void campfire(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { + cooking(source, category, result, experience, cookingTime, RecipeSerializer.CAMPFIRE_COOKING_RECIPE, CampfireCookingRecipe::new); } public void stonecutting(DataIngredient source, RecipeCategory category, Supplier result) { @@ -174,19 +217,19 @@ public void stonecutting(DataIngredient source, RecipeCateg .save(this, safeId(result.get()) + "_from_" + safeName(source) + "_stonecutting"); } - public void smeltingAndBlasting(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float xp) { - smelting(source, category, cookingCategory, result, xp); - blasting(source, category, cookingCategory, result, xp); + public void smeltingAndBlasting(DataIngredient source, RecipeCategory category, Supplier result, float xp) { + smelting(source, category, result, xp); + blasting(source, category, result, xp); } - public void food(DataIngredient source, RecipeCategory category, CookingBookCategory cookingCategory, Supplier result, float xp) { - smelting(source, category, cookingCategory, result, xp); - smoking(source, category, cookingCategory, result, xp); - campfire(source, category, cookingCategory, result, xp); + public void food(DataIngredient source, RecipeCategory category, Supplier result, float xp) { + smelting(source, category, result, xp); + smoking(source, category, result, xp); + campfire(source, category, result, xp); } public void square(DataIngredient source, RecipeCategory category, Supplier output, boolean small) { - ShapedRecipeBuilder builder = shaped(category, output.get()) + ShapedRecipeBuilder builder = ShapedRecipeBuilder.shaped(category, output.get()) .define('X', source.toVanilla()); if (small) { builder.pattern("XX").pattern("XX"); @@ -194,7 +237,7 @@ public void square(DataIngredient source, RecipeCategory ca builder.pattern("XXX").pattern("XXX").pattern("XXX"); } builder.unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(output.get())); + .save(this, safeId(output.get())); } /** @@ -224,491 +267,370 @@ public void storage(DataIngredient sourceIngredient, Recipe @CheckReturnValue public ShapelessRecipeBuilder singleItemUnfinished(DataIngredient source, RecipeCategory category, Supplier result, int required, int amount) { - return shapeless(category, result.get(), amount) + return ShapelessRecipeBuilder.shapeless(category, result.get(), amount) .requires(source.toVanilla(), required) .unlockedBy("has_" + safeName(source), source.getCriterion(this)); } public void singleItem(DataIngredient source, RecipeCategory category, Supplier result, int required, int amount) { - singleItemUnfinished(source, category, result, required, amount).save(this, safeKey(result.get())); + singleItemUnfinished(source, category, result, required, amount).save(this, safeId(result.get())); } public void planks(DataIngredient source, RecipeCategory category, Supplier result) { singleItemUnfinished(source, category, result, 1, 4) .group("planks") - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); } public void stairs(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group, boolean stone) { - shaped(category, result.get(), 4) + ShapedRecipeBuilder.shaped(category, result.get(), 4) .pattern("X ").pattern("XX ").pattern("XXX") .define('X', source.toVanilla()) .group(group) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); if (stone) { stonecutting(source, category, result); } } public void slab(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group, boolean stone) { - shaped(category, result.get(), 6) + ShapedRecipeBuilder.shaped(category, result.get(), 6) .pattern("XXX") .define('X', source.toVanilla()) .group(group) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); if (stone) { stonecutting(source, category, result, 2); } } public void fence(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - shaped(category, result.get(), 3) + ShapedRecipeBuilder.shaped(category, result.get(), 3) .pattern("W#W").pattern("W#W") .define('W', source.toVanilla()) .define('#', Tags.Items.RODS_WOODEN) .group(group) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); } public void fenceGate(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - shaped(category, result.get()) + ShapedRecipeBuilder.shaped(category, result.get()) .pattern("#W#").pattern("#W#") .define('W', source.toVanilla()) .define('#', Tags.Items.RODS_WOODEN) .group(group) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); } public void wall(DataIngredient source, RecipeCategory category, Supplier result) { - shaped(category, result.get(), 6) + ShapedRecipeBuilder.shaped(category, result.get(), 6) .pattern("XXX").pattern("XXX") .define('X', source.toVanilla()) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); stonecutting(source, category, result); } public void door(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - shaped(category, result.get(), 3) + ShapedRecipeBuilder.shaped(category, result.get(), 3) .pattern("XX").pattern("XX").pattern("XX") .define('X', source.toVanilla()) .group(group) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); } public void trapDoor(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - shaped(category, result.get(), 2) + ShapedRecipeBuilder.shaped(category, result.get(), 2) .pattern("XXX").pattern("XXX") .define('X', source.toVanilla()) .group(group) .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeKey(result.get())); + .save(this, safeId(result.get())); } // @formatter:off // GENERATED START - DO NOT EDIT BELOW THIS LINE + /** Generated override to expose protected method: {@link RecipeProvider#buildAdvancement} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public CompletableFuture buildAdvancement(CachedOutput output, HolderLookup.Provider registries, AdvancementHolder advancement) { return super.buildAdvancement(output, registries, advancement); } + + /** Generated override to expose protected method: {@link RecipeProvider#buildAdvancement} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public CompletableFuture buildAdvancement(CachedOutput output, HolderLookup.Provider registries, AdvancementHolder advancement, ICondition... conditions) { return super.buildAdvancement(output, registries, advancement, conditions); } + + /** Generated override to expose protected method: {@link RecipeProvider#buildRecipes} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public void buildRecipes(RecipeOutput p_recipeOutput, HolderLookup.Provider holderLookup) { super.buildRecipes(p_recipeOutput, holderLookup); } + /** Generated override to expose protected method: {@link RecipeProvider#generateForEnabledBlockFamilies} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void generateForEnabledBlockFamilies(FeatureFlagSet flagSet) { super.generateForEnabledBlockFamilies(flagSet); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public void generateForEnabledBlockFamilies(RecipeOutput enabledFeatures, FeatureFlagSet p_251836_) { super.generateForEnabledBlockFamilies(enabledFeatures, p_251836_); } /** Generated override to expose protected method: {@link RecipeProvider#netheriteSmithing} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void netheriteSmithing(Item base, RecipeCategory category, Item result) { super.netheriteSmithing(base, category, result); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void netheriteSmithing(RecipeOutput recipeOutput, Item ingredientItem, RecipeCategory category, Item resultItem) { RecipeProvider.netheriteSmithing(recipeOutput, ingredientItem, category, resultItem); } /** Generated override to expose protected method: {@link RecipeProvider#trimSmithing} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void trimSmithing(Item trimTemplate, ResourceKey patternId, ResourceKey> id) { super.trimSmithing(trimTemplate, patternId, id); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void trimSmithing(RecipeOutput recipeOutput, Item ingredientItem, ResourceLocation location) { RecipeProvider.trimSmithing(recipeOutput, ingredientItem, location); } /** Generated override to expose protected method: {@link RecipeProvider#twoByTwoPacker} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void twoByTwoPacker(RecipeCategory category, ItemLike result, ItemLike ingredient) { super.twoByTwoPacker(category, result, ingredient); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void twoByTwoPacker(RecipeOutput recipeOutput, RecipeCategory category, ItemLike packed, ItemLike unpacked) { RecipeProvider.twoByTwoPacker(recipeOutput, category, packed, unpacked); } /** Generated override to expose protected method: {@link RecipeProvider#threeByThreePacker} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void threeByThreePacker(RecipeCategory category, ItemLike result, ItemLike ingredient, String unlockedBy) { super.threeByThreePacker(category, result, ingredient, unlockedBy); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void threeByThreePacker(RecipeOutput recipeOutput, RecipeCategory category, ItemLike packed, ItemLike unpacked, String criterionName) { RecipeProvider.threeByThreePacker(recipeOutput, category, packed, unpacked, criterionName); } /** Generated override to expose protected method: {@link RecipeProvider#threeByThreePacker} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void threeByThreePacker(RecipeCategory category, ItemLike result, ItemLike ingredient) { super.threeByThreePacker(category, result, ingredient); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void threeByThreePacker(RecipeOutput recipeOutput, RecipeCategory category, ItemLike packed, ItemLike unpacked) { RecipeProvider.threeByThreePacker(recipeOutput, category, packed, unpacked); } /** Generated override to expose protected method: {@link RecipeProvider#planksFromLog} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void planksFromLog(ItemLike result, TagKey logs, int count) { super.planksFromLog(result, logs, count); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void planksFromLog(RecipeOutput recipeOutput, ItemLike planks, TagKey logs, int resultCount) { RecipeProvider.planksFromLog(recipeOutput, planks, logs, resultCount); } /** Generated override to expose protected method: {@link RecipeProvider#planksFromLogs} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void planksFromLogs(ItemLike result, TagKey logs, int count) { super.planksFromLogs(result, logs, count); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void planksFromLogs(RecipeOutput recipeOutput, ItemLike planks, TagKey logs, int result) { RecipeProvider.planksFromLogs(recipeOutput, planks, logs, result); } /** Generated override to expose protected method: {@link RecipeProvider#woodFromLogs} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void woodFromLogs(ItemLike result, ItemLike log) { super.woodFromLogs(result, log); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void woodFromLogs(RecipeOutput recipeOutput, ItemLike wood, ItemLike log) { RecipeProvider.woodFromLogs(recipeOutput, wood, log); } /** Generated override to expose protected method: {@link RecipeProvider#woodenBoat} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void woodenBoat(ItemLike result, ItemLike planks) { super.woodenBoat(result, planks); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void woodenBoat(RecipeOutput recipeOutput, ItemLike boat, ItemLike material) { RecipeProvider.woodenBoat(recipeOutput, boat, material); } /** Generated override to expose protected method: {@link RecipeProvider#chestBoat} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void chestBoat(ItemLike chestBoat, ItemLike boat) { super.chestBoat(chestBoat, boat); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void chestBoat(RecipeOutput recipeOutput, ItemLike boat, ItemLike material) { RecipeProvider.chestBoat(recipeOutput, boat, material); } /** Generated override to expose protected method: {@link RecipeProvider#buttonBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder buttonBuilder(ItemLike result, Ingredient base) { return super.buttonBuilder(result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder buttonBuilder(ItemLike button, Ingredient material) { return RecipeProvider.buttonBuilder(button, material); } /** Generated override to expose protected method: {@link RecipeProvider#doorBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder doorBuilder(ItemLike result, Ingredient base) { return super.doorBuilder(result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder doorBuilder(ItemLike door, Ingredient material) { return RecipeProvider.doorBuilder(door, material); } /** Generated override to expose protected method: {@link RecipeProvider#fenceBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder fenceBuilder(ItemLike result, Ingredient base) { return super.fenceBuilder(result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder fenceBuilder(ItemLike fence, Ingredient material) { return RecipeProvider.fenceBuilder(fence, material); } /** Generated override to expose protected method: {@link RecipeProvider#fenceGateBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder fenceGateBuilder(ItemLike result, Ingredient planks) { return super.fenceGateBuilder(result, planks); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder fenceGateBuilder(ItemLike fenceGate, Ingredient material) { return RecipeProvider.fenceGateBuilder(fenceGate, material); } /** Generated override to expose protected method: {@link RecipeProvider#pressurePlate} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void pressurePlate(ItemLike result, ItemLike base) { super.pressurePlate(result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void pressurePlate(RecipeOutput recipeOutput, ItemLike pressurePlate, ItemLike material) { RecipeProvider.pressurePlate(recipeOutput, pressurePlate, material); } /** Generated override to expose protected method: {@link RecipeProvider#pressurePlateBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder pressurePlateBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.pressurePlateBuilder(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder pressurePlateBuilder(RecipeCategory category, ItemLike pressurePlate, Ingredient material) { return RecipeProvider.pressurePlateBuilder(category, pressurePlate, material); } /** Generated override to expose protected method: {@link RecipeProvider#slab} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void slab(RecipeCategory category, ItemLike result, ItemLike base) { super.slab(category, result, base); } - - /** Generated override to expose protected method: {@link RecipeProvider#shelf} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void shelf(ItemLike result, ItemLike strippedLogs) { super.shelf(result, strippedLogs); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void slab(RecipeOutput recipeOutput, RecipeCategory category, ItemLike slab, ItemLike material) { RecipeProvider.slab(recipeOutput, category, slab, material); } /** Generated override to expose protected method: {@link RecipeProvider#slabBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder slabBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.slabBuilder(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder slabBuilder(RecipeCategory category, ItemLike slab, Ingredient material) { return RecipeProvider.slabBuilder(category, slab, material); } /** Generated override to expose protected method: {@link RecipeProvider#stairBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder stairBuilder(ItemLike result, Ingredient base) { return super.stairBuilder(result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder stairBuilder(ItemLike stairs, Ingredient material) { return RecipeProvider.stairBuilder(stairs, material); } /** Generated override to expose protected method: {@link RecipeProvider#trapdoorBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder trapdoorBuilder(ItemLike result, Ingredient base) { return super.trapdoorBuilder(result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder trapdoorBuilder(ItemLike trapdoor, Ingredient material) { return RecipeProvider.trapdoorBuilder(trapdoor, material); } /** Generated override to expose protected method: {@link RecipeProvider#signBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder signBuilder(ItemLike result, Ingredient planks) { return super.signBuilder(result, planks); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder signBuilder(ItemLike sign, Ingredient material) { return RecipeProvider.signBuilder(sign, material); } /** Generated override to expose protected method: {@link RecipeProvider#hangingSign} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void hangingSign(ItemLike result, ItemLike ingredient) { super.hangingSign(result, ingredient); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void hangingSign(RecipeOutput recipeOutput, ItemLike sign, ItemLike material) { RecipeProvider.hangingSign(recipeOutput, sign, material); } - /** Generated override to expose protected method: {@link RecipeProvider#colorItemWithDye} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void colorItemWithDye(List dyes, List items, String groupName, RecipeCategory category) { super.colorItemWithDye(dyes, items, groupName, category); } + /** Generated override to expose protected method: {@link RecipeProvider#colorBlockWithDye} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void colorBlockWithDye(RecipeOutput recipeOutput, List dyes, List dyeableItems, String group) { RecipeProvider.colorBlockWithDye(recipeOutput, dyes, dyeableItems, group); } /** Generated override to expose protected method: {@link RecipeProvider#carpet} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void carpet(ItemLike result, ItemLike sourceItem) { super.carpet(result, sourceItem); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void carpet(RecipeOutput recipeOutput, ItemLike carpet, ItemLike material) { RecipeProvider.carpet(recipeOutput, carpet, material); } /** Generated override to expose protected method: {@link RecipeProvider#bedFromPlanksAndWool} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void bedFromPlanksAndWool(ItemLike result, ItemLike wool) { super.bedFromPlanksAndWool(result, wool); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void bedFromPlanksAndWool(RecipeOutput recipeOutput, ItemLike bed, ItemLike wool) { RecipeProvider.bedFromPlanksAndWool(recipeOutput, bed, wool); } /** Generated override to expose protected method: {@link RecipeProvider#banner} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void banner(ItemLike result, ItemLike wool) { super.banner(result, wool); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void banner(RecipeOutput recipeOutput, ItemLike banner, ItemLike material) { RecipeProvider.banner(recipeOutput, banner, material); } /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassFromGlassAndDye} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void stainedGlassFromGlassAndDye(ItemLike result, ItemLike dye) { super.stainedGlassFromGlassAndDye(result, dye); } - - /** Generated override to expose protected method: {@link RecipeProvider#dryGhast} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void dryGhast(ItemLike result) { super.dryGhast(result); } - - /** Generated override to expose protected method: {@link RecipeProvider#harness} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void harness(ItemLike result, ItemLike wool) { super.harness(result, wool); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void stainedGlassFromGlassAndDye(RecipeOutput recipeOutput, ItemLike stainedGlass, ItemLike dye) { RecipeProvider.stainedGlassFromGlassAndDye(recipeOutput, stainedGlass, dye); } /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassPaneFromStainedGlass} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void stainedGlassPaneFromStainedGlass(ItemLike result, ItemLike stainedGlass) { super.stainedGlassPaneFromStainedGlass(result, stainedGlass); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void stainedGlassPaneFromStainedGlass(RecipeOutput recipeOutput, ItemLike stainedGlassPane, ItemLike stainedGlass) { RecipeProvider.stainedGlassPaneFromStainedGlass(recipeOutput, stainedGlassPane, stainedGlass); } /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassPaneFromGlassPaneAndDye} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void stainedGlassPaneFromGlassPaneAndDye(ItemLike result, ItemLike dye) { super.stainedGlassPaneFromGlassPaneAndDye(result, dye); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void stainedGlassPaneFromGlassPaneAndDye(RecipeOutput recipeOutput, ItemLike stainedGlassPane, ItemLike dye) { RecipeProvider.stainedGlassPaneFromGlassPaneAndDye(recipeOutput, stainedGlassPane, dye); } /** Generated override to expose protected method: {@link RecipeProvider#coloredTerracottaFromTerracottaAndDye} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void coloredTerracottaFromTerracottaAndDye(ItemLike result, ItemLike dye) { super.coloredTerracottaFromTerracottaAndDye(result, dye); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void coloredTerracottaFromTerracottaAndDye(RecipeOutput recipeOutput, ItemLike terracotta, ItemLike dye) { RecipeProvider.coloredTerracottaFromTerracottaAndDye(recipeOutput, terracotta, dye); } /** Generated override to expose protected method: {@link RecipeProvider#concretePowder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void concretePowder(ItemLike result, ItemLike dye) { super.concretePowder(result, dye); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void concretePowder(RecipeOutput recipeOutput, ItemLike concretePowder, ItemLike dye) { RecipeProvider.concretePowder(recipeOutput, concretePowder, dye); } /** Generated override to expose protected method: {@link RecipeProvider#candle} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void candle(ItemLike result, ItemLike dye) { super.candle(result, dye); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void candle(RecipeOutput recipeOutput, ItemLike candle, ItemLike dye) { RecipeProvider.candle(recipeOutput, candle, dye); } /** Generated override to expose protected method: {@link RecipeProvider#wall} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void wall(RecipeCategory category, ItemLike result, ItemLike base) { super.wall(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void wall(RecipeOutput recipeOutput, RecipeCategory category, ItemLike wall, ItemLike material) { RecipeProvider.wall(recipeOutput, category, wall, material); } /** Generated override to expose protected method: {@link RecipeProvider#wallBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder wallBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.wallBuilder(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder wallBuilder(RecipeCategory category, ItemLike wall, Ingredient material) { return RecipeProvider.wallBuilder(category, wall, material); } /** Generated override to expose protected method: {@link RecipeProvider#polished} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void polished(RecipeCategory category, ItemLike result, ItemLike base) { super.polished(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void polished(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material) { RecipeProvider.polished(recipeOutput, category, result, material); } /** Generated override to expose protected method: {@link RecipeProvider#polishedBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public RecipeBuilder polishedBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.polishedBuilder(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static RecipeBuilder polishedBuilder(RecipeCategory category, ItemLike result, Ingredient material) { return RecipeProvider.polishedBuilder(category, result, material); } /** Generated override to expose protected method: {@link RecipeProvider#cut} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void cut(RecipeCategory category, ItemLike result, ItemLike base) { super.cut(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void cut(RecipeOutput recipeOutput, RecipeCategory category, ItemLike cutResult, ItemLike material) { RecipeProvider.cut(recipeOutput, category, cutResult, material); } /** Generated override to expose protected method: {@link RecipeProvider#cutBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapedRecipeBuilder cutBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.cutBuilder(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static ShapedRecipeBuilder cutBuilder(RecipeCategory category, ItemLike cutResult, Ingredient material) { return RecipeProvider.cutBuilder(category, cutResult, material); } /** Generated override to expose protected method: {@link RecipeProvider#chiseled} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void chiseled(RecipeCategory category, ItemLike result, ItemLike base) { super.chiseled(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void chiseled(RecipeOutput recipeOutput, RecipeCategory category, ItemLike chiseledResult, ItemLike material) { RecipeProvider.chiseled(recipeOutput, category, chiseledResult, material); } /** Generated override to expose protected method: {@link RecipeProvider#mosaicBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void mosaicBuilder(RecipeCategory category, ItemLike result, ItemLike base) { super.mosaicBuilder(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void mosaicBuilder(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material) { RecipeProvider.mosaicBuilder(recipeOutput, category, result, material); } /** Generated override to expose protected method: {@link RecipeProvider#chiseledBuilder} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapedRecipeBuilder chiseledBuilder(RecipeCategory category, ItemLike result, Ingredient base) { return super.chiseledBuilder(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static ShapedRecipeBuilder chiseledBuilder(RecipeCategory category, ItemLike chiseledResult, Ingredient material) { return RecipeProvider.chiseledBuilder(category, chiseledResult, material); } /** Generated override to expose protected method: {@link RecipeProvider#stonecutterResultFromBase} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void stonecutterResultFromBase(RecipeCategory category, ItemLike result, ItemLike base) { super.stonecutterResultFromBase(category, result, base); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void stonecutterResultFromBase(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material) { RecipeProvider.stonecutterResultFromBase(recipeOutput, category, result, material); } /** Generated override to expose protected method: {@link RecipeProvider#stonecutterResultFromBase} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void stonecutterResultFromBase(RecipeCategory category, ItemLike result, ItemLike base, int count) { super.stonecutterResultFromBase(category, result, base, count); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void stonecutterResultFromBase(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material, int resultCount) { RecipeProvider.stonecutterResultFromBase(recipeOutput, category, result, material, resultCount); } /** Generated override to expose protected method: {@link RecipeProvider#smeltingResultFromBase} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void smeltingResultFromBase(ItemLike result, ItemLike base) { super.smeltingResultFromBase(result, base); } - - /** Generated override to expose protected method: {@link RecipeProvider#nineBlockStorageRecipes} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void nineBlockStorageRecipes(RecipeCategory unpackedFormCategory, ItemLike unpackedForm, RecipeCategory packedFormCategory, ItemLike packedForm) { super.nineBlockStorageRecipes(unpackedFormCategory, unpackedForm, packedFormCategory, packedForm); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void smeltingResultFromBase(RecipeOutput recipeOutput, ItemLike result, ItemLike ingredient) { RecipeProvider.smeltingResultFromBase(recipeOutput, result, ingredient); } /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void copySmithingTemplate(ItemLike smithingTemplate, ItemLike baseMaterial) { super.copySmithingTemplate(smithingTemplate, baseMaterial); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void copySmithingTemplate(RecipeOutput recipeOutput, ItemLike template, TagKey baseMaterial) { RecipeProvider.copySmithingTemplate(recipeOutput, template, baseMaterial); } /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void copySmithingTemplate(ItemLike smithingTemplate, Ingredient baseMaterials) { super.copySmithingTemplate(smithingTemplate, baseMaterials); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void copySmithingTemplate(RecipeOutput recipeOutput, ItemLike template, ItemLike baseItem) { RecipeProvider.copySmithingTemplate(recipeOutput, template, baseItem); } - /** Generated override to expose protected method: {@link RecipeProvider#cookRecipes} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void cookRecipes(String source, AbstractCookingRecipe.Factory factory, int cookingTime) { super.cookRecipes(source, factory, cookingTime); } + /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void copySmithingTemplate(RecipeOutput recipeOutput, ItemLike template, Ingredient baseItem) { RecipeProvider.copySmithingTemplate(recipeOutput, template, baseItem); } /** Generated override to expose protected method: {@link RecipeProvider#waxRecipes} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void waxRecipes(FeatureFlagSet flagSet) { super.waxRecipes(flagSet); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void waxRecipes(RecipeOutput recipeOutput, FeatureFlagSet requiredFeatures) { RecipeProvider.waxRecipes(recipeOutput, requiredFeatures); } /** Generated override to expose protected method: {@link RecipeProvider#grate} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void grate(Block grateBlock, Block material) { super.grate(grateBlock, material); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void grate(RecipeOutput recipeOutput, Block grateBlock, Block material) { RecipeProvider.grate(recipeOutput, grateBlock, material); } /** Generated override to expose protected method: {@link RecipeProvider#copperBulb} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void copperBulb(Block copperBulb, Block copperMaterial) { super.copperBulb(copperBulb, copperMaterial); } - - /** Generated override to expose protected method: {@link RecipeProvider#waxedChiseled} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void waxedChiseled(Block result, Block material) { super.waxedChiseled(result, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#suspiciousStew} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void suspiciousStew(Item item, SuspiciousEffectHolder effectHolder) { super.suspiciousStew(item, effectHolder); } - - /** Generated override to expose protected method: {@link RecipeProvider#dyedItem} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void dyedItem(Item target, String group) { super.dyedItem(target, group); } - - /** Generated override to expose protected method: {@link RecipeProvider#dyedShulkerBoxRecipe} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void dyedShulkerBoxRecipe(Item dye, Item dyedResult) { super.dyedShulkerBoxRecipe(dye, dyedResult); } - - /** Generated override to expose protected method: {@link RecipeProvider#dyedBundleRecipe} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void dyedBundleRecipe(Item dye, Item dyedResult) { super.dyedBundleRecipe(dye, dyedResult); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void copperBulb(RecipeOutput recipeOutput, Block bulbBlock, Block material) { RecipeProvider.copperBulb(recipeOutput, bulbBlock, material); } /** Generated override to expose protected method: {@link RecipeProvider#generateRecipes} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public void generateRecipes(BlockFamily family, FeatureFlagSet flagSet) { super.generateRecipes(family, flagSet); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static void generateRecipes(RecipeOutput recipeOutput, BlockFamily blockFamily, FeatureFlagSet requiredFeatures) { RecipeProvider.generateRecipes(recipeOutput, blockFamily, requiredFeatures); } - /** Generated override to expose protected method: {@link RecipeProvider#getBaseBlockForCrafting} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public Block getBaseBlockForCrafting(BlockFamily family, BlockFamily.Variant variant) { return super.getBaseBlockForCrafting(family, variant); } + /** Generated override to expose protected method: {@link RecipeProvider#getBaseBlock} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static Block getBaseBlock(BlockFamily family, BlockFamily.Variant variant) { return RecipeProvider.getBaseBlock(family, variant); } /** Generated override to expose protected method: {@link RecipeProvider#insideOf} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") public static Criterion insideOf(Block block) { return RecipeProvider.insideOf(block); } /** Generated override to expose protected method: {@link RecipeProvider#has} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public Criterion has(MinMaxBounds.Ints count, ItemLike item) { return super.has(count, item); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static Criterion has(MinMaxBounds.Ints count, ItemLike item) { return RecipeProvider.has(count, item); } /** Generated override to expose protected method: {@link RecipeProvider#has} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public Criterion has(ItemLike item) { return super.has(item); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static Criterion has(ItemLike itemLike) { return RecipeProvider.has(itemLike); } /** Generated override to expose protected method: {@link RecipeProvider#has} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public Criterion has(TagKey tag) { return super.has(tag); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static Criterion has(TagKey tag) { return RecipeProvider.has(tag); } /** Generated override to expose protected method: {@link RecipeProvider#inventoryTrigger} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public static Criterion inventoryTrigger(ItemPredicate.Builder... predicates) { return RecipeProvider.inventoryTrigger(predicates); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static Criterion inventoryTrigger(ItemPredicate.Builder... items) { return RecipeProvider.inventoryTrigger(items); } /** Generated override to expose protected method: {@link RecipeProvider#inventoryTrigger} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") public static Criterion inventoryTrigger(ItemPredicate... predicates) { return RecipeProvider.inventoryTrigger(predicates); } /** Generated override to expose protected method: {@link RecipeProvider#getHasName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public static String getHasName(ItemLike baseBlock) { return RecipeProvider.getHasName(baseBlock); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static String getHasName(ItemLike itemLike) { return RecipeProvider.getHasName(itemLike); } /** Generated override to expose protected method: {@link RecipeProvider#getItemName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") public static String getItemName(ItemLike itemLike) { return RecipeProvider.getItemName(itemLike); } /** Generated override to expose protected method: {@link RecipeProvider#getSimpleRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") public static String getSimpleRecipeName(ItemLike itemLike) { return RecipeProvider.getSimpleRecipeName(itemLike); } /** Generated override to expose protected method: {@link RecipeProvider#getConversionRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public static String getConversionRecipeName(ItemLike product, ItemLike material) { return RecipeProvider.getConversionRecipeName(product, material); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static String getConversionRecipeName(ItemLike result, ItemLike ingredient) { return RecipeProvider.getConversionRecipeName(result, ingredient); } /** Generated override to expose protected method: {@link RecipeProvider#getSmeltingRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public static String getSmeltingRecipeName(ItemLike product) { return RecipeProvider.getSmeltingRecipeName(product); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static String getSmeltingRecipeName(ItemLike itemLike) { return RecipeProvider.getSmeltingRecipeName(itemLike); } /** Generated override to expose protected method: {@link RecipeProvider#getBlastingRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public static String getBlastingRecipeName(ItemLike product) { return RecipeProvider.getBlastingRecipeName(product); } - - /** Generated override to expose protected method: {@link RecipeProvider#tag} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public Ingredient tag(TagKey id) { return super.tag(id); } - - /** Generated override to expose protected method: {@link RecipeProvider#shaped} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapedRecipeBuilder shaped(RecipeCategory category, ItemStackTemplate stack) { return super.shaped(category, stack); } - - /** Generated override to expose protected method: {@link RecipeProvider#shaped} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike item) { return super.shaped(category, item); } - - /** Generated override to expose protected method: {@link RecipeProvider#shaped} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike item, int count) { return super.shaped(category, item, count); } - - /** Generated override to expose protected method: {@link RecipeProvider#shapeless} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemStackTemplate result) { return super.shapeless(category, result); } - - /** Generated override to expose protected method: {@link RecipeProvider#shapeless} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike item) { return super.shapeless(category, item); } - - /** Generated override to expose protected method: {@link RecipeProvider#shapeless} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Sun, 19 Apr 2026 10:13:58 GMT") - public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike item, int count) { return super.shapeless(category, item, count); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") + public static String getBlastingRecipeName(ItemLike itemLike) { return RecipeProvider.getBlastingRecipeName(itemLike); } // GENERATED END - } diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java deleted file mode 100644 index 3f68dfb..0000000 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeRunner.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.modularmc.registrate.providers.generators; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.RegistrateProvider; - -import net.minecraft.core.HolderLookup; -import net.minecraft.data.PackOutput; -import net.minecraft.data.recipes.RecipeOutput; -import net.minecraft.data.recipes.RecipeProvider; -import net.neoforged.fml.LogicalSide; - -import java.util.concurrent.CompletableFuture; - -public class RegistrateRecipeRunner extends RecipeProvider.Runner implements RegistrateProvider { - - final AbstractRegistrate owner; - - @org.jetbrains.annotations.Nullable - RegistrateRecipeProvider provider; - - public RegistrateRecipeRunner(AbstractRegistrate owner, PackOutput p_365369_, CompletableFuture p_361563_) { - super(p_365369_, p_361563_); - this.owner = owner; - } - - @Override - protected RecipeProvider createRecipeProvider(HolderLookup.Provider p_362946_, RecipeOutput p_365274_) { - return new RegistrateRecipeProvider(this, p_362946_, p_365274_); - } - - @Override - public String getName() { - return ""; - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } - - public RegistrateRecipeProvider getRecipeProvider() { - if (provider == null) throw new IllegalStateException("Recipe Provider is not available now"); - return provider; - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java index 1a2ee60..8880c2f 100644 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java @@ -73,230 +73,210 @@ public HolderLookup> entityLookup() { /** Generated override to expose protected method: {@link BlockLootSubProvider#applyExplosionDecay} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public > T applyExplosionDecay(ItemLike type, FunctionUserBuilder builder) { return super.applyExplosionDecay(type, builder); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public > T applyExplosionDecay(ItemLike item, FunctionUserBuilder functionBuilder) { return super.applyExplosionDecay(item, functionBuilder); } /** Generated override to expose protected method: {@link BlockLootSubProvider#applyExplosionCondition} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public > T applyExplosionCondition(ItemLike type, ConditionUserBuilder builder) { return super.applyExplosionCondition(type, builder); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSelfDropDispatchTable} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public static LootTable.Builder createSelfDropDispatchTable(Block original, LootItemCondition.Builder condition, LootPoolEntryContainer.Builder entry) { return BlockLootSubProvider.createSelfDropDispatchTable(original, condition, entry); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public > T applyExplosionCondition(ItemLike item, ConditionUserBuilder conditionBuilder) { return super.applyExplosionCondition(item, conditionBuilder); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchDispatchTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createSilkTouchDispatchTable(Block original, LootPoolEntryContainer.Builder entry) { return super.createSilkTouchDispatchTable(original, entry); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createSilkTouchDispatchTable(Block block, LootPoolEntryContainer.Builder builder) { return super.createSilkTouchDispatchTable(block, builder); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsDispatchTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createShearsDispatchTable(Block original, LootPoolEntryContainer.Builder entry) { return super.createShearsDispatchTable(original, entry); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createShearsDispatchTable(Block block, LootPoolEntryContainer.Builder builder) { return super.createShearsDispatchTable(block, builder); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchOrShearsDispatchTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createSilkTouchOrShearsDispatchTable(Block original, LootPoolEntryContainer.Builder entry) { return super.createSilkTouchOrShearsDispatchTable(original, entry); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createSilkTouchOrShearsDispatchTable(Block block, LootPoolEntryContainer.Builder builder) { return super.createSilkTouchOrShearsDispatchTable(block, builder); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTableWithSilkTouch} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createSingleItemTableWithSilkTouch(Block original, ItemLike drop) { return super.createSingleItemTableWithSilkTouch(original, drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createSingleItemTableWithSilkTouch(Block block, ItemLike item) { return super.createSingleItemTableWithSilkTouch(block, item); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createSingleItemTable(ItemLike drop, NumberProvider count) { return super.createSingleItemTable(drop, count); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createSingleItemTable(ItemLike item, NumberProvider count) { return super.createSingleItemTable(item, count); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTableWithSilkTouch} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createSingleItemTableWithSilkTouch(Block original, ItemLike drop, NumberProvider count) { return super.createSingleItemTableWithSilkTouch(original, drop, count); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createSingleItemTableWithSilkTouch(Block block, ItemLike item, NumberProvider count) { return super.createSingleItemTableWithSilkTouch(block, item, count); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchOnlyTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createSilkTouchOnlyTable(ItemLike drop) { return super.createSilkTouchOnlyTable(drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createSilkTouchOnlyTable(ItemLike item) { return super.createSilkTouchOnlyTable(item); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createPotFlowerItemTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createPotFlowerItemTable(ItemLike flower) { return super.createPotFlowerItemTable(flower); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createPotFlowerItemTable(ItemLike item) { return super.createPotFlowerItemTable(item); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createSlabItemTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createSlabItemTable(Block slab) { return super.createSlabItemTable(slab); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createSlabItemTable(Block block) { return super.createSlabItemTable(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createNameableBlockEntityTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createNameableBlockEntityTable(Block drop) { return super.createNameableBlockEntityTable(drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createNameableBlockEntityTable(Block block) { return super.createNameableBlockEntityTable(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createShulkerBoxDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createShulkerBoxDrop(Block shulkerBox) { return super.createShulkerBoxDrop(shulkerBox); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createShulkerBoxDrop(Block block) { return super.createShulkerBoxDrop(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createCopperOreDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public LootTable.Builder createCopperOreDrops(Block block) { return super.createCopperOreDrops(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createLapisOreDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public LootTable.Builder createLapisOreDrops(Block block) { return super.createLapisOreDrops(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createRedstoneOreDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public LootTable.Builder createRedstoneOreDrops(Block block) { return super.createRedstoneOreDrops(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createBannerDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createBannerDrop(Block original) { return super.createBannerDrop(original); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createBannerDrop(Block block) { return super.createBannerDrop(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createBeeNestDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createBeeNestDrop(Block original) { return super.createBeeNestDrop(original); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createBeeNestDrop(Block block) { return super.createBeeNestDrop(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createBeeHiveDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createBeeHiveDrop(Block original) { return super.createBeeHiveDrop(original); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createBeeHiveDrop(Block block) { return super.createBeeHiveDrop(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createCaveVinesDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createCaveVinesDrop(Block original) { return super.createCaveVinesDrop(original); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createCopperGolemStatueBlock} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createCopperGolemStatueBlock(Block block) { return super.createCopperGolemStatueBlock(block); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createCaveVinesDrop(Block block) { return super.createCaveVinesDrop(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createOreDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createOreDrop(Block original, Item drop) { return super.createOreDrop(original, drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createOreDrop(Block block, Item item) { return super.createOreDrop(block, item); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createMushroomBlockDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createMushroomBlockDrop(Block original, ItemLike drop) { return super.createMushroomBlockDrop(original, drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createMushroomBlockDrop(Block block, ItemLike item) { return super.createMushroomBlockDrop(block, item); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createGrassDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createGrassDrops(Block original) { return super.createGrassDrops(original); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createGrassDrops(Block block) { return super.createGrassDrops(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsOnlyDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createShearsOnlyDrop(ItemLike drop) { return super.createShearsOnlyDrop(drop); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsOrSilkTouchOnlyDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createShearsOrSilkTouchOnlyDrop(ItemLike drop) { return super.createShearsOrSilkTouchOnlyDrop(drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public static LootTable.Builder createShearsOnlyDrop(ItemLike item) { return BlockLootSubProvider.createShearsOnlyDrop(item); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createMultifaceBlockDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createMultifaceBlockDrops(Block block, LootItemCondition.Builder condition) { return super.createMultifaceBlockDrops(block, condition); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createMultifaceBlockDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createMultifaceBlockDrops(Block block) { return super.createMultifaceBlockDrops(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createMossyCarpetBlockDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createMossyCarpetBlockDrops(Block block) { return super.createMossyCarpetBlockDrops(block); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createMultifaceBlockDrops(Block block, LootItemCondition.Builder builder) { return super.createMultifaceBlockDrops(block, builder); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createLeavesDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createLeavesDrops(Block original, Block sapling, float... saplingChances) { return super.createLeavesDrops(original, sapling, saplingChances); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createLeavesDrops(Block leavesBlock, Block saplingBlock, float... chances) { return super.createLeavesDrops(leavesBlock, saplingBlock, chances); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createOakLeavesDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createOakLeavesDrops(Block original, Block sapling, float... saplingChances) { return super.createOakLeavesDrops(original, sapling, saplingChances); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createOakLeavesDrops(Block oakLeavesBlock, Block saplingBlock, float... chances) { return super.createOakLeavesDrops(oakLeavesBlock, saplingBlock, chances); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createMangroveLeavesDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public LootTable.Builder createMangroveLeavesDrops(Block block) { return super.createMangroveLeavesDrops(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createCropDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createCropDrops(Block original, Item cropDrop, Item seedDrop, LootItemCondition.Builder isMaxAge) { return super.createCropDrops(original, cropDrop, seedDrop, isMaxAge); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createCropDrops(Block cropBlock, Item grownCropItem, Item seedsItem, LootItemCondition.Builder dropGrownCropCondition) { return super.createCropDrops(cropBlock, grownCropItem, seedsItem, dropGrownCropCondition); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoublePlantShearsDrop} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createDoublePlantShearsDrop(Block block) { return super.createDoublePlantShearsDrop(block); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createDoublePlantShearsDrop(Block sheared) { return super.createDoublePlantShearsDrop(sheared); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoublePlantWithSeedDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createDoublePlantWithSeedDrops(Block block, Block drop) { return super.createDoublePlantWithSeedDrops(block, drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createDoublePlantWithSeedDrops(Block block, Block sheared) { return super.createDoublePlantWithSeedDrops(block, sheared); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createCandleDrops} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createCandleDrops(Block block) { return super.createCandleDrops(block); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createCandleDrops(Block candleBlock) { return super.createCandleDrops(candleBlock); } + + /** Generated override to expose protected method: {@link BlockLootSubProvider#createPetalsDrops} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createPetalsDrops(Block petalBlock) { return super.createPetalsDrops(petalBlock); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createCandleCakeDrops} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public static LootTable.Builder createCandleCakeDrops(Block candle) { return BlockLootSubProvider.createCandleCakeDrops(candle); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public static LootTable.Builder createCandleCakeDrops(Block candleCakeBlock) { return BlockLootSubProvider.createCandleCakeDrops(candleCakeBlock); } /** Generated override to expose protected method: {@link BlockLootSubProvider#addNetherVinesDropTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public void addNetherVinesDropTable(Block vineBlock, Block plantBlock) { super.addNetherVinesDropTable(vineBlock, plantBlock); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public void addNetherVinesDropTable(Block vines, Block plant) { super.addNetherVinesDropTable(vines, plant); } /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoorTable} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public LootTable.Builder createDoorTable(Block block) { return super.createDoorTable(block); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public LootTable.Builder createDoorTable(Block doorBlock) { return super.createDoorTable(doorBlock); } /** Generated override to expose protected method: {@link BlockLootSubProvider#dropPottedContents} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public void dropPottedContents(Block potted) { super.dropPottedContents(potted); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public void dropPottedContents(Block flowerPot) { super.dropPottedContents(flowerPot); } /** Generated override to expose protected method: {@link BlockLootSubProvider#otherWhenSilkTouch} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public void otherWhenSilkTouch(Block block, Block other) { super.otherWhenSilkTouch(block, other); } /** Generated override to expose protected method: {@link BlockLootSubProvider#dropOther} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") - public void dropOther(Block block, ItemLike drop) { super.dropOther(block, drop); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") + public void dropOther(Block block, ItemLike item) { super.dropOther(block, item); } /** Generated override to expose protected method: {@link BlockLootSubProvider#dropWhenSilkTouch} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public void dropWhenSilkTouch(Block block) { super.dropWhenSilkTouch(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#dropSelf} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public void dropSelf(Block block) { super.dropSelf(block); } /** Generated override to expose protected method: {@link BlockLootSubProvider#add} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Sun, 19 Apr 2026 10:15:02 GMT") + @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") public void add(Block block, LootTable.Builder builder) { super.add(block, builder); } // GENERATED END diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java index 2c64de1..592dfdb 100644 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java @@ -2,14 +2,15 @@ import com.modularmc.registrate.AbstractRegistrate; -import net.minecraft.core.HolderGetter; import net.minecraft.core.HolderLookup; import net.minecraft.core.registries.Registries; import net.minecraft.data.loot.EntityLootSubProvider; import net.minecraft.resources.ResourceKey; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.animal.FrogVariant; import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.item.Item; +import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; @@ -67,20 +68,29 @@ public HolderLookup> entityLookup() { // @formatter:off // GENERATED START - DO NOT EDIT BELOW THIS LINE - /** Generated override to expose protected method: {@link EntityLootSubProvider#killedByFrog} */ + /** Generated override to expose protected method: {@link EntityLootSubProvider#createSheepTable} */ + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") + public static LootTable.Builder createSheepTable(ItemLike woolItem) { return EntityLootSubProvider.createSheepTable(woolItem); } + + /** Generated override to expose protected method: {@link EntityLootSubProvider#canHaveLootTable} */ + @Override + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") + public boolean canHaveLootTable(EntityType p_249029_) { return super.canHaveLootTable(p_249029_); } + + /** Generated override to expose protected method: {@link EntityLootSubProvider#killedByFrogVariant} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Sun, 19 Apr 2026 10:15:16 GMT") - public LootItemCondition.Builder killedByFrog(HolderGetter> entityTypes) { return super.killedByFrog(entityTypes); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") + public LootItemCondition.Builder killedByFrogVariant(ResourceKey frogVariant) { return super.killedByFrogVariant(frogVariant); } /** Generated override to expose protected method: {@link EntityLootSubProvider#add} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Sun, 19 Apr 2026 10:15:16 GMT") - public void add(EntityType type, LootTable.Builder builder) { super.add(type, builder); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") + public void add(EntityType entityType, LootTable.Builder builder) { super.add(entityType, builder); } /** Generated override to expose protected method: {@link EntityLootSubProvider#add} */ @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Sun, 19 Apr 2026 10:15:16 GMT") - public void add(EntityType type, ResourceKey lootTable, LootTable.Builder builder) { super.add(type, lootTable, builder); } + @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") + public void add(EntityType entityType, ResourceKey defaultLootTable, LootTable.Builder builder) { super.add(entityType, defaultLootTable, builder); } // GENERATED END } diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java index a966df8..decd171 100644 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java @@ -11,18 +11,14 @@ import net.minecraft.data.PackOutput; import net.minecraft.data.loot.LootTableProvider; import net.minecraft.data.loot.LootTableSubProvider; -import net.minecraft.data.loot.packs.VanillaLootTableProvider; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; import net.minecraft.util.ProblemReporter; -import net.minecraft.util.context.ContextKeySet; import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.ValidationContextSource; +import net.minecraft.world.level.storage.loot.ValidationContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet; import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.neoforged.fml.LogicalSide; -import net.neoforged.fml.util.ObfuscationReflectionHelper; -import com.google.common.collect.BiMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; @@ -42,9 +38,9 @@ public interface LootType { T getLootCreator(HolderLookup.Provider provider, AbstractRegistrate parent, Consumer callback); - ContextKeySet getLootSet(); + LootContextParamSet getLootSet(); - static LootType register(String name, ContextKeySet set, TriFunction, Consumer, T> factory) { + static LootType register(String name, LootContextParamSet set, TriFunction, Consumer, T> factory) { LootType type = new LootType() { @Override @@ -53,7 +49,7 @@ public T getLootCreator(HolderLookup.Provider provider, AbstractRegistrate pa } @Override - public ContextKeySet getLootSet() { + public LootContextParamSet getLootSet() { return set; } }; @@ -67,19 +63,19 @@ public ContextKeySet getLootSet() { private final AbstractRegistrate parent; private final Multimap, Consumer> specialLootActions = HashMultimap.create(); - private final Multimap, LootTable.Builder>>> lootActions = HashMultimap.create(); + private final Multimap, LootTable.Builder>>> lootActions = HashMultimap.create(); private final Set currentLootCreators = new HashSet<>(); - private CompletableFuture provider; + private final CompletableFuture provider; public RegistrateLootTableProvider(AbstractRegistrate parent, PackOutput packOutput, CompletableFuture provider) { - super(packOutput, Set.of(), VanillaLootTableProvider.create(packOutput, provider).getTables(), provider); + super(packOutput, Set.of(), List.of(), provider); this.parent = parent; this.provider = provider; } public HolderLookup.Provider getProvider() { - return provider.getNow(null); + return Objects.requireNonNull(provider.getNow(null), "Loot table registry lookup is not ready"); } public Holder resolve(ResourceKey key) { @@ -92,7 +88,8 @@ public LogicalSide getSide() { } @Override - protected void validate(WritableRegistry tables, ValidationContextSource validationContext, ProblemReporter.Collector problems) { + protected void validate(WritableRegistry tables, ValidationContext validationContext, ProblemReporter.Collector problems) { + super.validate(tables, validationContext, problems); currentLootCreators.forEach(c -> c.validate(tables, validationContext)); } @@ -101,7 +98,7 @@ public void addLootAction(LootType type, Non this.specialLootActions.put(type, (Consumer) action); } - public void addLootAction(ContextKeySet set, Consumer, LootTable.Builder>> action) { + public void addLootAction(LootContextParamSet set, Consumer, LootTable.Builder>> action) { this.lootActions.put(set, action); } @@ -111,8 +108,6 @@ private LootTableSubProvider getLootCreator(HolderLookup.Provider provider, Abst return creator; } - private static final BiMap SET_REGISTRY = ObfuscationReflectionHelper.getPrivateValue(LootContextParamSets.class, null, "REGISTRY"); - @Override public List getTables() { parent.genData(ProviderType.LOOT, this); @@ -121,9 +116,8 @@ public List getTables() { for (LootType type : LOOT_TYPES.values()) { builder.add(new SubProviderEntry(provider -> getLootCreator(provider, parent, type), type.getLootSet())); } - for (ContextKeySet set : SET_REGISTRY.values()) { - builder.add(new SubProviderEntry((provider) -> callback -> lootActions.get(set).forEach(a -> a.accept(callback)), set)); - } + lootActions.asMap().forEach((set, actions) -> builder.add( + new SubProviderEntry(provider -> callback -> actions.forEach(action -> action.accept(callback)), set))); return builder.build(); } } diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java index dee7c21..1b5a5e3 100644 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java @@ -3,9 +3,14 @@ import net.minecraft.core.WritableRegistry; import net.minecraft.data.loot.LootTableSubProvider; import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.ValidationContextSource; +import net.minecraft.world.level.storage.loot.ValidationContext; +/** + * A loot subprovider with an optional validation step after all tables are collected. + * Implementations generate and validate tables during the same datagen run. + */ public interface RegistrateLootTables extends LootTableSubProvider { - default void validate(WritableRegistry tables, ValidationContextSource validationContext) {} + /** Validates generated tables and reports problems into the supplied context. */ + default void validate(WritableRegistry tables, ValidationContext validationContext) {} } diff --git a/src/main/java/com/modularmc/registrate/util/DataIngredient.java b/src/main/java/com/modularmc/registrate/util/DataIngredient.java index 0829219..0a507e8 100644 --- a/src/main/java/com/modularmc/registrate/util/DataIngredient.java +++ b/src/main/java/com/modularmc/registrate/util/DataIngredient.java @@ -4,11 +4,11 @@ import com.modularmc.registrate.util.nullness.NonNullSupplier; import net.minecraft.advancements.Criterion; -import net.minecraft.advancements.criterion.InventoryChangeTrigger; -import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.advancements.critereon.InventoryChangeTrigger; +import net.minecraft.advancements.critereon.ItemPredicate; import net.minecraft.core.HolderSet; import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.crafting.Ingredient; @@ -26,7 +26,7 @@ * It remembers the name of the primary ingredient for use in creating recipe names/criteria. *

* Create an instance of this class with the various factory methods such as {@link #items(ItemLike, ItemLike...)} and - * {@link #tag(HolderSet.Named)} )}. + * {@link #tag(TagKey)}. *

* This class should not be used for any purpose other than data generation, it will throw an exception * if it is serialized to a packet buffer. @@ -35,22 +35,22 @@ public final class DataIngredient { private final Ingredient parent; @Getter - private final Identifier id; + private final ResourceLocation id; private final Function> criteriaFactory; private DataIngredient(Ingredient parent, ItemLike item) { this.parent = parent; this.id = BuiltInRegistries.ITEM.getKey(item.asItem()); - this.criteriaFactory = prov -> prov.has(item); + this.criteriaFactory = ignored -> RegistrateRecipeProvider.has(item); } private DataIngredient(Ingredient parent, TagKey tag) { this.parent = parent; this.id = tag.location(); - this.criteriaFactory = prov -> prov.has(tag); + this.criteriaFactory = ignored -> RegistrateRecipeProvider.has(tag); } - private DataIngredient(Ingredient parent, Identifier id, ItemPredicate... predicates) { + private DataIngredient(Ingredient parent, ResourceLocation id, ItemPredicate... predicates) { this.parent = parent; this.id = id; this.criteriaFactory = ignored -> RegistrateRecipeProvider.inventoryTrigger(predicates); @@ -72,7 +72,11 @@ public static DataIngredient items(T first, T... others) { } public static DataIngredient tag(HolderSet.Named tag) { - return ingredient(Ingredient.of(tag), tag.key()); + return tag(tag.key()); + } + + public static DataIngredient tag(TagKey tag) { + return ingredient(Ingredient.of(tag), tag); } public static DataIngredient ingredient(Ingredient parent, ItemLike required) { @@ -83,7 +87,7 @@ public static DataIngredient ingredient(Ingredient parent, TagKey required return new DataIngredient(parent, required); } - public static DataIngredient ingredient(Ingredient parent, Identifier id, ItemPredicate... criteria) { + public static DataIngredient ingredient(Ingredient parent, ResourceLocation id, ItemPredicate... criteria) { return new DataIngredient(parent, id, criteria); } diff --git a/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java b/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java index cab5ebd..64cd3cb 100644 --- a/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java +++ b/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java @@ -3,7 +3,6 @@ import com.modularmc.registrate.AbstractRegistrate; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.EntityType; import net.minecraft.world.level.Level; import net.neoforged.neoforge.registries.DeferredHolder; @@ -16,8 +15,8 @@ public EntityEntry(AbstractRegistrate owner, DeferredHolder, En super(owner, delegate); } - public @Nullable T create(Level world, EntitySpawnReason reason) { - return get().create(world, reason); + public @Nullable T create(Level world) { + return get().create(world); } public boolean is(Entity t) { diff --git a/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java b/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java index 8aab3b4..c30816b 100644 --- a/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java +++ b/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java @@ -4,7 +4,6 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.ItemStackTemplate; import net.minecraft.world.level.ItemLike; import net.neoforged.neoforge.registries.DeferredHolder; @@ -22,14 +21,6 @@ public ItemStack asStack(int count) { return new ItemStack(this, count); } - public ItemStackTemplate asStackTemplate() { - return new ItemStackTemplate(asItem(), 1); - } - - public ItemStackTemplate asStackTemplate(int count) { - return new ItemStackTemplate(asItem(), count); - } - public boolean isIn(ItemStack stack) { return is(stack.getItem()); } diff --git a/src/test/generated/resources/assets/testmod/items/magic_item_model.json b/src/test/generated/resources/assets/testmod/items/magic_item_model.json deleted file mode 100644 index 8f0f7e8..0000000 --- a/src/test/generated/resources/assets/testmod/items/magic_item_model.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "testmod:block/subfolder/magic_item_model" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testblock.json b/src/test/generated/resources/assets/testmod/items/testblock.json deleted file mode 100644 index 0f2f576..0000000 --- a/src/test/generated/resources/assets/testmod/items/testblock.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "minecraft:item/egg", - "tints": [ - { - "type": "minecraft:constant", - "value": -65536 - } - ] - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json b/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json deleted file mode 100644 index b48ce41..0000000 --- a/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "model": { - "type": "neoforge:fluid_container", - "flip_gas": true, - "fluid": "testmod:testbucketfluid", - "textures": { - "base": "minecraft:item/bucket", - "fluid": "neoforge:item/mask/bucket_fluid", - "particle": "minecraft:item/bucket" - } - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json b/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json deleted file mode 100644 index ec7ccbb..0000000 --- a/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "testmod:item/testentity_spawn_egg" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testitem.json b/src/test/generated/resources/assets/testmod/items/testitem.json deleted file mode 100644 index f5c9f2a..0000000 --- a/src/test/generated/resources/assets/testmod/items/testitem.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "minecraft:block/stone" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/item/magic_item_model.json b/src/test/generated/resources/assets/testmod/models/item/magic_item_model.json new file mode 100644 index 0000000..86a0872 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/item/magic_item_model.json @@ -0,0 +1,3 @@ +{ + "parent": "testmod:block/subfolder/magic_item_model" +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/item/testblock.json b/src/test/generated/resources/assets/testmod/models/item/testblock.json new file mode 100644 index 0000000..0d9a36d --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/item/testblock.json @@ -0,0 +1,3 @@ +{ + "parent": "minecraft:item/egg" +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/item/testbucketfluid_bucket.json b/src/test/generated/resources/assets/testmod/models/item/testbucketfluid_bucket.json new file mode 100644 index 0000000..2873075 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/item/testbucketfluid_bucket.json @@ -0,0 +1,11 @@ +{ + "apply_fluid_luminosity": true, + "flip_gas": true, + "fluid": "testmod:testbucketfluid", + "loader": "neoforge:fluid_container", + "textures": { + "base": "minecraft:item/bucket", + "fluid": "neoforge:item/mask/bucket_fluid", + "particle": "minecraft:item/bucket" + } +} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/item/testitem.json b/src/test/generated/resources/assets/testmod/models/item/testitem.json new file mode 100644 index 0000000..37f27f1 --- /dev/null +++ b/src/test/generated/resources/assets/testmod/models/item/testitem.json @@ -0,0 +1,3 @@ +{ + "parent": "minecraft:block/stone" +} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json b/src/test/generated/resources/data/minecraft/tags/block/bamboo_plantable_on.json similarity index 100% rename from src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json rename to src/test/generated/resources/data/minecraft/tags/block/bamboo_plantable_on.json diff --git a/src/test/generated/resources/data/testmod/advancement/root.json b/src/test/generated/resources/data/testmod/advancement/root.json index 28d1f62..dbfcf07 100644 --- a/src/test/generated/resources/data/testmod/advancement/root.json +++ b/src/test/generated/resources/data/testmod/advancement/root.json @@ -17,6 +17,7 @@ "translate": "advancements.testmod.root.description" }, "icon": { + "count": 1, "id": "minecraft:egg" }, "title": { diff --git a/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json b/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json index ff1f490..f147a12 100644 --- a/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json +++ b/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json @@ -1,45 +1,10 @@ { "ambient_light": 0.0, - "attributes": { - "minecraft:audio/ambient_sounds": { - "mood": { - "block_search_extent": 8, - "offset": 2.0, - "sound": "minecraft:ambient.cave", - "tick_delay": 6000 - } - }, - "minecraft:audio/background_music": { - "creative": { - "max_delay": 24000, - "min_delay": 12000, - "sound": "minecraft:music.creative" - }, - "default": { - "max_delay": 24000, - "min_delay": 12000, - "sound": "minecraft:music.game" - } - }, - "minecraft:gameplay/bed_rule": { - "can_set_spawn": "always", - "can_sleep": "when_dark", - "error_message": { - "translate": "block.minecraft.bed.no_sleep" - } - }, - "minecraft:gameplay/nether_portal_spawns_piglin": true, - "minecraft:gameplay/respawn_anchor_works": false, - "minecraft:visual/ambient_light_color": "#0a0a0a", - "minecraft:visual/cloud_color": "#ccffffff", - "minecraft:visual/cloud_height": 192.33, - "minecraft:visual/fog_color": "#c0d8ff", - "minecraft:visual/sky_color": "#78a7ff" - }, + "bed_works": true, "coordinate_scale": 1.0, - "default_clock": "minecraft:overworld", + "effects": "minecraft:overworld", "has_ceiling": false, - "has_ender_dragon_fight": false, + "has_raids": true, "has_skylight": true, "height": 384, "infiniburn": "#minecraft:infiniburn_overworld", @@ -51,5 +16,8 @@ "max_inclusive": 7, "min_inclusive": 0 }, - "timelines": "#minecraft:in_overworld" + "natural": true, + "piglin_safe": false, + "respawn_anchor_works": false, + "ultrawarm": false } \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json index 66c260d..94fc105 100644 --- a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json +++ b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json @@ -1,10 +1,13 @@ { "type": "minecraft:campfire_cooking", - "category": "misc", + "category": "food", "cookingtime": 600, "experience": 1.0, - "ingredient": "testmod:testblock", + "ingredient": { + "item": "testmod:testblock" + }, "result": { + "count": 1, "id": "minecraft:diamond_block" } } \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json index 4b5e4df..0dafccf 100644 --- a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json +++ b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json @@ -1,10 +1,13 @@ { "type": "minecraft:smelting", - "category": "misc", + "category": "blocks", "cookingtime": 200, "experience": 1.0, - "ingredient": "testmod:testblock", + "ingredient": { + "item": "testmod:testblock" + }, "result": { + "count": 1, "id": "minecraft:diamond_block" } } \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json index 69eed99..acb8e47 100644 --- a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json +++ b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json @@ -1,10 +1,13 @@ { "type": "minecraft:smoking", - "category": "misc", + "category": "food", "cookingtime": 100, "experience": 1.0, - "ingredient": "testmod:testblock", + "ingredient": { + "item": "testmod:testblock" + }, "result": { + "count": 1, "id": "minecraft:diamond_block" } } \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/testblock.json b/src/test/generated/resources/data/testmod/recipe/testblock.json index 6e325d8..a66f80e 100644 --- a/src/test/generated/resources/data/testmod/recipe/testblock.json +++ b/src/test/generated/resources/data/testmod/recipe/testblock.json @@ -2,8 +2,12 @@ "type": "minecraft:crafting_shaped", "category": "misc", "key": { - "D": "minecraft:diamond", - "E": "minecraft:egg" + "D": { + "item": "minecraft:diamond" + }, + "E": { + "item": "minecraft:egg" + } }, "pattern": [ "DDD", @@ -11,6 +15,7 @@ "DDD" ], "result": { + "count": 1, "id": "testmod:testblock" } } \ No newline at end of file diff --git a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java b/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java index 9e7e6b4..d297010 100644 --- a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java +++ b/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java @@ -2,11 +2,11 @@ import com.modularmc.registrate.test.mod.TestMod; +import net.minecraft.gametest.framework.GameTest; import net.neoforged.testframework.DynamicTest; import net.neoforged.testframework.annotation.ForEachTest; import net.neoforged.testframework.annotation.TestHolder; import net.neoforged.testframework.gametest.EmptyTemplate; -import net.neoforged.testframework.gametest.GameTest; @ForEachTest(groups = "custom-item") @SuppressWarnings("unused") diff --git a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java b/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java index 95e5eb3..7481b16 100644 --- a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java +++ b/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java @@ -2,12 +2,11 @@ import com.modularmc.registrate.test.mod.TestMod; -import net.minecraft.world.item.SpawnEggItem; +import net.minecraft.gametest.framework.GameTest; import net.neoforged.testframework.DynamicTest; import net.neoforged.testframework.annotation.ForEachTest; import net.neoforged.testframework.annotation.TestHolder; import net.neoforged.testframework.gametest.EmptyTemplate; -import net.neoforged.testframework.gametest.GameTest; @ForEachTest(groups = "registrate-runtime") @SuppressWarnings("unused") @@ -34,7 +33,7 @@ public static void ensureAuxiliaryRegistrations(final DynamicTest test) { .thenExecute(menuId -> { helper.assertValueEqual("testmenu", menuId, "Menu registration path"); helper.assertValueEqual("entity.testmod.testentity", TestMod.instance().testentity.get().getDescriptionId(), "Entity translation key"); - helper.assertValueEqual(TestMod.instance().testentity.get(), SpawnEggItem.getType(TestMod.instance().testentitySpawnEgg.asStack()), "Spawn egg should resolve to the registered entity type"); + helper.assertValueEqual(TestMod.instance().testentity.get(), TestMod.instance().testentitySpawnEgg.get().getType(TestMod.instance().testentitySpawnEgg.asStack()), "Spawn egg should resolve to the registered entity type"); helper.assertValueEqual("testitem", TestMod.instance().testduplicatename.getId().getPath(), "Duplicate-name entity registration path"); helper.assertValueEqual("testblockentity", TestMod.instance().testblockentity.getId().getPath(), "Standalone block entity registration path"); helper.assertValueEqual("testcustom", TestMod.instance().testcustom.getId().getPath(), "Custom registry entry path"); diff --git a/src/test/java/com/modularmc/registrate/test/mod/TestMod.java b/src/test/java/com/modularmc/registrate/test/mod/TestMod.java index 4c3c3fb..3cb66e8 100644 --- a/src/test/java/com/modularmc/registrate/test/mod/TestMod.java +++ b/src/test/java/com/modularmc/registrate/test/mod/TestMod.java @@ -2,32 +2,19 @@ import com.modularmc.registrate.Registrate; import com.modularmc.registrate.builders.BlockBuilder; -import com.modularmc.registrate.providers.DataGenContext; import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator; import com.modularmc.registrate.util.DataIngredient; import com.modularmc.registrate.util.entry.*; import net.minecraft.advancements.Advancement; import net.minecraft.advancements.AdvancementType; -import net.minecraft.advancements.criterion.InventoryChangeTrigger; -import net.minecraft.client.color.block.BlockTintSources; -import net.minecraft.client.color.item.Constant; -import net.minecraft.client.data.models.model.ModelTemplates; -import net.minecraft.client.data.models.model.TextureMapping; +import net.minecraft.advancements.critereon.InventoryChangeTrigger; import net.minecraft.client.gui.screens.inventory.ContainerScreen; -import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; -import net.minecraft.client.renderer.blockentity.state.BlockEntityRenderState; +import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.renderer.entity.PigRenderer; -import net.minecraft.client.renderer.entity.state.EntityRenderState; -import net.minecraft.client.renderer.feature.ModelFeatureRenderer; -import net.minecraft.client.renderer.item.ItemModelResolver; -import net.minecraft.client.renderer.item.ItemStackRenderState; -import net.minecraft.client.renderer.state.level.CameraRenderState; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.client.resources.model.sprite.Material; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.core.BlockPos; @@ -35,26 +22,21 @@ import net.minecraft.core.RegistrySetBuilder; import net.minecraft.core.registries.Registries; import net.minecraft.data.recipes.RecipeCategory; -import net.minecraft.data.worldgen.biome.OverworldBiomes; import net.minecraft.network.chat.Component; -import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.EntityTypeTags; import net.minecraft.tags.ItemTags; -import net.minecraft.tags.TimelineTags; -import net.minecraft.util.ARGB; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.InteractionResult; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleContainer; -import net.minecraft.world.attribute.*; -import net.minecraft.world.clock.WorldClocks; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.entity.SpawnPlacementTypes; import net.minecraft.world.entity.animal.Animal; -import net.minecraft.world.entity.animal.pig.Pig; +import net.minecraft.world.entity.animal.Pig; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.food.FoodProperties; @@ -62,8 +44,6 @@ import net.minecraft.world.inventory.ChestMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.*; -import net.minecraft.world.item.crafting.CookingBookCategory; -import net.minecraft.world.level.CardinalLighting; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.level.biome.FixedBiomeSource; @@ -77,6 +57,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition.Builder; import net.minecraft.world.level.block.state.properties.BlockStateProperties; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.levelgen.Heightmap; @@ -90,7 +71,6 @@ import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator; import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.Vec3; import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.ModContainer; import net.neoforged.fml.common.Mod; @@ -112,9 +92,8 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import org.lwjgl.glfw.GLFW; -import java.util.List; import java.util.Objects; -import java.util.Optional; +import java.util.OptionalLong; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; @@ -169,37 +148,22 @@ public TestBlockEntity(BlockEntityType type, BlockPos } } - private static class TestBlockEntityRenderer implements BlockEntityRenderer { + private static class TestBlockEntityRenderer implements BlockEntityRenderer { - private final ItemModelResolver itemModelResolver; + private final ItemRenderer itemRenderer; - public TestBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { - itemModelResolver = ctx.itemModelResolver(); + public TestBlockEntityRenderer(BlockEntityRendererProvider.Context context) { + itemRenderer = context.getItemRenderer(); } @Override - public RenderState createRenderState() { - return new RenderState(); - } - - @Override - public void extractRenderState(TestBlockEntity blockEntity, RenderState state, float partialTicks, Vec3 cameraPosition, @Nullable ModelFeatureRenderer.CrumblingOverlay breakProgress) { - BlockEntityRenderer.super.extractRenderState(blockEntity, state, partialTicks, cameraPosition, breakProgress); - itemModelResolver.updateForTopItem(state.item, new ItemStack(Items.DIAMOND), ItemDisplayContext.GROUND, blockEntity.getLevel(), null, 0); - } - - @Override - public void submit(RenderState state, PoseStack poseStack, SubmitNodeCollector submitNodeCollector, CameraRenderState camera) { + public void render(TestBlockEntity blockEntity, float partialTicks, PoseStack poseStack, MultiBufferSource buffers, int light, int overlay) { poseStack.pushPose(); poseStack.translate(0.5, 0.5, 0.5); - state.item.submit(poseStack, submitNodeCollector, state.lightCoords, OverlayTexture.NO_OVERLAY, EntityRenderState.NO_OUTLINE); + itemRenderer.renderStatic(new ItemStack(Items.DIAMOND), ItemDisplayContext.GROUND, + light, overlay, poseStack, buffers, blockEntity.getLevel(), 0); poseStack.popPose(); } - - private static class RenderState extends BlockEntityRenderState { - - private final ItemStackRenderState item = new ItemStackRenderState(); - } } public static final class TestDummyBlockEntity extends BlockEntity { @@ -259,13 +223,14 @@ public static final class TestCustomRegistryEntry {} .unlockedBy("has_egg", prov.has(Items.EGG)) .save(prov); - prov.food(DataIngredient.items(ctx), RecipeCategory.MISC, CookingBookCategory.MISC, () -> Blocks.DIAMOND_BLOCK, 1f); + prov.food(DataIngredient.items(ctx), RecipeCategory.MISC, () -> Blocks.DIAMOND_BLOCK, 1f); }) - .tag(BlockTags.SUPPORTS_BAMBOO, BlockTags.DRAGON_IMMUNE) + .tag(BlockTags.BAMBOO_PLANTABLE_ON, BlockTags.DRAGON_IMMUNE) .tag(BlockTags.WITHER_IMMUNE) - .color(() -> () -> List.of(BlockTintSources.constant(0xFFFF0000))) + .color(() -> () -> (state, level, pos, tintIndex) -> 0xFFFF0000) .item() - .model(() -> Client::testBlockModel) + .model(() -> (ctx, prov) -> prov.createWithExistingModel(ctx.get(), prov.mcLoc("item/egg"))) + .color(() -> () -> (stack, tintIndex) -> 0xFFFF0000) .build() .blockEntity(TestBlockEntity::new) .renderer(() -> TestBlockEntityRenderer::new) @@ -277,10 +242,7 @@ public static final class TestCustomRegistryEntry {} .block(Block::new) .blockstate(() -> (ctx, prov) -> prov.create( ctx.getEntry(), - ModelTemplates.CUBE_ALL.create( - prov.modLoc("block/subfolder/" + ctx.getName()), - TextureMapping.cube(prov.mcBlockTexture("gold_block")), - prov.modelOutput))) + prov.models().cubeAll("block/subfolder/" + ctx.getName(), prov.mcBlockTexture("gold_block")).getLocation())) .simpleItem() .register(); @@ -295,7 +257,7 @@ public static final class TestCustomRegistryEntry {} .attributes(Pig::createAttributes) .renderer(() -> PigRenderer::new) .spawnPlacement(SpawnPlacementTypes.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules, RegisterSpawnPlacementsEvent.Operation.OR) - .spawnEgg(egg -> egg.model(() -> (ctx, prov) -> prov.generateFlatItem(ctx.getEntry(), new Material(Identifier.fromNamespaceAndPath(MOD_ID, "item/testentity_spawn_egg"))))) + .spawnEgg(egg -> egg.model(() -> (ctx, prov) -> prov.generateFlatItem(ctx.getEntry(), prov.modItemTexture(ctx.getName())))) .loot((prov, type) -> prov.add(type, LootTable.lootTable() .withPool(LootPool.lootPool() .setRolls(ConstantValue.exactly(1)) @@ -316,8 +278,8 @@ public static final class TestCustomRegistryEntry {} @VisibleForTesting public final FluidEntry testfluid = registrate.object("testfluid") .fluid( - Identifier.withDefaultNamespace("block/water_flow"), - Identifier.withDefaultNamespace("block/lava_still"), + ResourceLocation.withDefaultNamespace("block/water_flow"), + ResourceLocation.withDefaultNamespace("block/lava_still"), FluidType::new) .properties(p -> p.lightLevel(15).canConvertToSource(true)) .noBucket() @@ -326,8 +288,8 @@ public static final class TestCustomRegistryEntry {} @VisibleForTesting public final FluidEntry testbucketfluid = registrate.object("testbucketfluid") .fluid( - Identifier.withDefaultNamespace("block/water_still"), - Identifier.withDefaultNamespace("block/water_flow"), + ResourceLocation.withDefaultNamespace("block/water_still"), + ResourceLocation.withDefaultNamespace("block/water_flow"), FluidType::new) .properties(p -> p.lightLevel(7).canConvertToSource(true)) .register(); @@ -363,7 +325,7 @@ public TestMod(IEventBus eventBus, ModContainer container) { .addCriterion("has_egg", InventoryChangeTrigger.TriggerInstance.hasItems(Items.EGG)) .display(Items.EGG, adv.title(registrate.getModid(), "root", "Test Advancement"), adv.desc(registrate.getModid(), "root", "Get an egg."), - Identifier.withDefaultNamespace("textures/gui/advancements/backgrounds/stone.png"), AdvancementType.TASK, true, true, false) + ResourceLocation.withDefaultNamespace("textures/gui/advancements/backgrounds/stone.png"), AdvancementType.TASK, true, true, false) .save(adv, registrate.getModid() + ":root")); registrate.addDataGenerator(ProviderType.GENERIC_SERVER, provider -> provider.add(data -> { // generic server side provider to generate custom dimension @@ -371,7 +333,7 @@ public TestMod(IEventBus eventBus, ModContainer container) { // /execute as @s in testmod:test_dimension run tp @s 0 64 0 // you can validate you are in this dimension by checking the debug screen // right underneath the `Chunks[C]` and `Chunk[S]` should be the dimension name - var testDimensionTypeKey = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.fromNamespaceAndPath("testmod", "test_dimension_type")); + var testDimensionTypeKey = ResourceKey.create(Registries.DIMENSION_TYPE, ResourceLocation.fromNamespaceAndPath("testmod", "test_dimension_type")); return new DatapackBuiltinEntriesProvider( data.output(), @@ -381,35 +343,10 @@ public TestMod(IEventBus eventBus, ModContainer container) { .add(Registries.DIMENSION_TYPE, context -> context.register( testDimensionTypeKey, new DimensionType( - /* hasFixedTime */ false, - /* hasSky */ true, - /* hasCeiling */ false, - /* hasEnderDragonFight */ false, - /* coordinateScale */ 1D, - /* minY */ -64, - /* height */ 384, - /* localHeight */ 384, - /* infiniBurn */ BlockTags.INFINIBURN_OVERWORLD, - /* ambientLight */ 0F, - new DimensionType.MonsterSettings( - /* monsterSpawnLightTest */ UniformInt.of(0, 7), - /* monsterSpawnBlockLightLimit */ 0), - DimensionType.Skybox.OVERWORLD, - CardinalLighting.Type.DEFAULT, - EnvironmentAttributeMap.builder() - .set(EnvironmentAttributes.FOG_COLOR, 0xffc0d8ff) - .set(EnvironmentAttributes.SKY_COLOR, OverworldBiomes.calculateSkyColor(0.8F)) - .set(EnvironmentAttributes.AMBIENT_LIGHT_COLOR, 0xff0a0a0a) - .set(EnvironmentAttributes.CLOUD_COLOR, ARGB.white(0.8F)) - .set(EnvironmentAttributes.CLOUD_HEIGHT, 192.33f) - .set(EnvironmentAttributes.BACKGROUND_MUSIC, BackgroundMusic.OVERWORLD) - .set(EnvironmentAttributes.BED_RULE, BedRule.CAN_SLEEP_WHEN_DARK) - .set(EnvironmentAttributes.RESPAWN_ANCHOR_WORKS, false) - .set(EnvironmentAttributes.NETHER_PORTAL_SPAWNS_PIGLINS, true) - .set(EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.LEGACY_CAVE_SETTINGS) - .build(), - context.lookup(Registries.TIMELINE).getOrThrow(TimelineTags.IN_OVERWORLD), - Optional.of(context.lookup(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD))))) + OptionalLong.empty(), true, false, false, true, 1D, true, false, + -64, 384, 384, BlockTags.INFINIBURN_OVERWORLD, + BuiltinDimensionTypes.OVERWORLD_EFFECTS, 0F, + new DimensionType.MonsterSettings(false, true, UniformInt.of(0, 7), 0)))) // register custom dimension for the dimension type // simple single biome (plains) dimension .add(Registries.LEVEL_STEM, context -> { @@ -418,7 +355,7 @@ public TestMod(IEventBus eventBus, ModContainer container) { var overworldNoiseSettings = context.lookup(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD); context.register( - ResourceKey.create(Registries.LEVEL_STEM, Identifier.fromNamespaceAndPath("testmod", "test_dimension")), + ResourceKey.create(Registries.LEVEL_STEM, ResourceLocation.fromNamespaceAndPath("testmod", "test_dimension")), new LevelStem( testDimensionType, new NoiseBasedChunkGenerator( @@ -432,7 +369,7 @@ public TestMod(IEventBus eventBus, ModContainer container) { // Setup gametests for normal run config final MutableTestFramework framework = FrameworkConfiguration - .builder(Identifier.fromNamespaceAndPath(MOD_ID, "tests")) + .builder(ResourceLocation.fromNamespaceAndPath(MOD_ID, "tests")) .clientConfiguration(() -> ClientConfiguration.builder() .toggleOverlayKey(GLFW.GLFW_KEY_O) .openManagerKey(GLFW.GLFW_KEY_M) @@ -455,7 +392,6 @@ private void onCommonSetup(FMLCommonSetupEvent event) { throw new IllegalStateException("Register callback not fired!"); } - testblock.asStackTemplate(); testitem.is(Items.SNOWBALL); testblockitem.is(Items.STONE); testblockbe.is(BlockEntityType.CHEST); @@ -467,13 +403,6 @@ private void onCommonSetup(FMLCommonSetupEvent event) { if (testbucketfluid.getBucket().isEmpty()) throw new IllegalStateException("Expected a generated bucket entry for test bucket fluid"); } - private static class Client { - - private static void testBlockModel(DataGenContext ctx, RegistrateItemModelGenerator prov) { - prov.generateTintedModel(ctx.get(), prov.mcLoc("item/egg"), new Constant(0xFFFF0000)); - } - } - public static TestMod instance() { Objects.requireNonNull(INSTANCE, "Attempting to get mod instance before mod construction"); return INSTANCE; diff --git a/src/test/resources/pack.mcmeta b/src/test/resources/pack.mcmeta index ca3a103..766f0ee 100644 --- a/src/test/resources/pack.mcmeta +++ b/src/test/resources/pack.mcmeta @@ -1,9 +1,7 @@ { "pack": { - "description": "examplemod resources", - "pack_format": 12, - "forge:resource_pack_format": 12, - "forge:data_pack_format": 10, - "_comment": "A pack_format of 4 requires json lang files. Note: we require v4 pack meta for all mods." + "description": "RegistrateLib test resources", + "pack_format": 34, + "supported_formats": [34, 48] } } From 6066217dc02459203ec9815ce33fb137672786d4 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Fri, 20 Nov 2026 16:02:37 +0800 Subject: [PATCH 3/7] =?UTF-8?q?=E6=8C=89=E5=AE=A2=E6=88=B7=E7=AB=AF?= =?UTF-8?q?=E5=92=8C=E6=9C=8D=E5=8A=A1=E7=AB=AF=E9=80=89=E9=A1=B9=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E6=95=B0=E6=8D=AE=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../providers/core/RegistrateDataProvider.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java index dd15529..d942a5e 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java @@ -10,6 +10,7 @@ import net.minecraft.data.CachedOutput; import net.minecraft.data.DataProvider; import net.minecraft.resources.ResourceKey; +import net.neoforged.fml.LogicalSide; import net.neoforged.neoforge.data.event.GatherDataEvent; import com.google.common.collect.BiMap; @@ -61,12 +62,14 @@ public RegistrateDataProvider(AbstractRegistrate parent, String modid, Gather throw new IllegalStateException("Tag providers must be registered through ProviderType::registerTag"); } known.put(type, prov); - LOGGER.debug( - DebugMarkers.DATA, - RegistrateLogger.modMessage("Added datagen provider {}"), - mod, - sorted.id()); - subProviders.put(type, prov); + if (prov.getSide() == LogicalSide.CLIENT ? event.includeClient() : event.includeServer()) { + LOGGER.debug( + DebugMarkers.DATA, + RegistrateLogger.modMessage("Added datagen provider {}"), + mod, + sorted.id()); + subProviders.put(type, prov); + } } } From 9644201ed4961e65b462e65d7efaae2e30274989 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Fri, 20 Nov 2026 16:02:37 +0800 Subject: [PATCH 4/7] =?UTF-8?q?=E6=9B=B4=E6=96=B0=201.21.1=20=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 13 ++++++------- docs/advanced.md | 7 +++---- docs/architecture.md | 4 ++-- docs/builders.md | 19 +++++++++---------- docs/entries.md | 11 ++++++----- docs/providers.md | 19 ++++++++----------- 6 files changed, 34 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index c935c6a..ce3a426 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# RegistrateLib [![License](https://img.shields.io/github/license/ModularMCLib/RegistrateLib?cacheSeconds=36000)](https://www.tldrlegal.com/l/mpl-2.0) ![Minecraft Version](https://img.shields.io/badge/minecraft-26.1.1-blue) +# RegistrateLib [![License](https://img.shields.io/github/license/ModularMCLib/RegistrateLib?cacheSeconds=36000)](https://www.tldrlegal.com/l/mpl-2.0) ![Minecraft Version](https://img.shields.io/badge/minecraft-1.21.1-blue) @@ -13,8 +13,8 @@ A powerful wrapper for creating and registering objects in your mod. ## 分支状态 / Fork Status -本仓库是 `com.modularmc.registrate` 命名空间下的 Registrate 分支,为 ModularMCLib 生态维护。它追踪上游 Registrate 的设计,同时面向现代 NeoForge + Minecraft `26.1` 工具链,并保留可安全嵌入下游项目的包命名空间。 -This repository is the `com.modularmc.registrate` fork maintained for the ModularMCLib ecosystem. It tracks the upstream Registrate design while targeting the modern NeoForge + Minecraft `26.1` toolchain and preserving a package namespace that can be safely embedded in downstream projects. +本仓库是 `com.modularmc.registrate` 命名空间下的 Registrate 分支,为 ModularMCLib 生态维护。当前分支面向 Minecraft `1.21.1`、NeoForge `21.1` 和 Java `21`。 +This repository is the `com.modularmc.registrate` fork maintained for the ModularMCLib ecosystem. This branch targets Minecraft `1.21.1`, NeoForge `21.1`, and Java `21`. --- @@ -108,11 +108,10 @@ Registrate 会创建一个方块,并生成默认的简单方块状态、模型 Registrate will create a block, with a default simple blockstate, model, loot table, and lang entry. However, all of these facets can be configured easily to use whatever custom data you may want. Example: ```java -public static final RegistryEntry MY_STAIRS = REGISTRATE.block("my_block", MyStairsBlock::new) - .defaultItem() +public static final BlockEntry MY_STAIRS = REGISTRATE.block("my_stairs", MyStairsBlock::new) + .simpleItem() .tag(BlockTags.STAIRS) - .blockstate(ctx -> ctx.getProvider() - .stairsBlock(ctx.getEntry(), ctx.getProvider().modLoc(ctx.getName()))) + .blockstate(() -> (ctx, prov) -> prov.stairsBlock(ctx.getEntry(), prov.modBlockTexture(ctx.getName()))) .lang("Special Stairs") .register(); ``` diff --git a/docs/advanced.md b/docs/advanced.md index 2aaeab5..868469b 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -270,14 +270,13 @@ REGISTRATE.fluid("my_fluid", still, flow, FluidType::new) ```java // 方块着色 / Block tinting REGISTRATE.block("my_block", MyBlock::new) - .color(() -> () -> List.of( - BlockTintSources.constant(0xFFFF0000) // 红色着色 / Red tint - )) + .color(() -> () -> (state, level, pos, tintIndex) -> 0xFF0000) .register(); // 物品模型着色(通过 ItemBuilder)/ Item model tinting (via ItemBuilder) REGISTRATE.item("my_item", Item::new) - .defaultModel(new ItemTintSource("layer0", Constant.create(0xFFFF0000))) + .defaultModel() + .color(() -> () -> (stack, tintIndex) -> tintIndex == 0 ? 0xFF0000 : -1) .register(); ``` diff --git a/docs/architecture.md b/docs/architecture.md index a7db278..1050ab7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -86,5 +86,5 @@ Treat the root package plus `builders` and `util.entry` as the main downstream-f Keep public entrypoints small and push complexity into focused layers - 对下游模组预期集成的扩展点进行文档化 Document extension points where downstream mods are expected to integrate -- 在此开发分支上,优先采用 26.1 原生结构而非保持遗留兼容性 - Favor 26.1-native structure over preserving legacy compatibility on this dev branch +- 使用 Minecraft 1.21.1 和 NeoForge 的模型、配方与注册 API + Use the Minecraft 1.21.1 and NeoForge model, recipe, and registry APIs diff --git a/docs/builders.md b/docs/builders.md index 1f350fa..27ffaed 100644 --- a/docs/builders.md +++ b/docs/builders.md @@ -84,7 +84,7 @@ registrate.block("my_block", MyBlock::new) | `item(NonNullBiFunction)` | 使用自定义工厂创建 BlockItem / Create BlockItem with a custom factory | | `simpleBlockEntity(BlockEntityFactory)` | 快速创建没有额外配置的方块实体 / Quickly create a block entity without extra configuration | | `blockEntity(BlockEntityFactory)` | 返回 `BlockEntityBuilder` 用于完全配置方块实体 / Return BlockEntityBuilder for full BE configuration | -| `color(NonNullSupplier>>)` | 设置方块着色器 / Set block tint sources | +| `color(NonNullSupplier>)` | 注册方块着色器 / Register a block color handler | | `defaultBlockstate()` | 使用默认方块状态生成 / Use default blockstate generation | | `blockstate(NonNullSupplier)` | 自定义方块状态生成 / Custom blockstate generation | | `defaultLang()` | 自动生成语言条目 / Auto-generate lang entry | @@ -101,10 +101,9 @@ registrate.block("my_block", MyBlock::new) ```java public static final BlockEntry MY_STAIRS = REGISTRATE .block("my_stairs", MyStairsBlock::new) - .defaultItem() // 或 .item() 进行自定义 / or .item() for custom + .simpleItem() // 或 .item() 进行自定义 / or .item() for custom .tag(BlockTags.STAIRS) - .blockstate(ctx -> ctx.getProvider() - .stairsBlock(ctx.getEntry(), ctx.getProvider().modLoc(ctx.getName()))) + .blockstate(() -> (ctx, prov) -> prov.stairsBlock(ctx.getEntry(), prov.modBlockTexture(ctx.getName()))) .lang("Special Stairs") .register(); ``` @@ -130,6 +129,7 @@ public class ItemBuilder | `tab(ResourceKey, ...)` | 添加到创造模式标签页 / Add to creative mode tab | | `removeTab(ResourceKey)` | 从标签页移除 / Remove from tab | | `defaultModel()` | 使用默认物品模型 / Use default item model | +| `color(NonNullSupplier>)` | 注册物品着色器 / Register an item color handler | | `model(NonNullSupplier)` | 自定义物品模型 / Custom item model | | `defaultLang()` | 自动生成语言条目 / Auto-generate lang entry | | `lang(String)` | 自定义语言名称 / Custom lang name | @@ -247,8 +247,8 @@ public class FluidBuilder ```java // 基本创建(默认 FluidType)/ Basic creation (default FluidType) registrate.fluid("my_fluid", - Identifier.of("minecraft:block/water_still"), - Identifier.of("minecraft:block/water_flow"), + ResourceLocation.withDefaultNamespace("block/water_still"), + ResourceLocation.withDefaultNamespace("block/water_flow"), FluidType::new) ``` @@ -270,8 +270,7 @@ registrate.fluid("my_fluid", | `bucket()` | 返回 `ItemBuilder` 配置流体桶 / Return ItemBuilder for bucket | | `bucket(NonNullBiFunction)` | 自定义桶 / Custom bucket | | `noBucket()` | 不生成桶 / Skip bucket generation | -| `model(Identifier, Identifier)` | 设置静态和流动纹理 / Set still and flowing textures | -| `model(NonNullSupplier)` | 自定义模型 / Custom model | +| `model(ResourceLocation, ResourceLocation)` | 设置静态和流动纹理 / Set still and flowing textures | | `clientExtension(NonNullSupplier)` | 添加客户端流体类型扩展 / Add client fluid type extensions | | `tag(TagKey...)` | 添加流体标签 / Add fluid tags | | `removeTag(TagKey...)` | 移除流体标签 / Remove fluid tags | @@ -282,8 +281,8 @@ registrate.fluid("my_fluid", ```java public static final FluidEntry MY_FLUID = REGISTRATE .fluid("my_fluid", - Identifier.of("minecraft:block/water_still"), - Identifier.of("minecraft:block/water_flow"), + ResourceLocation.withDefaultNamespace("block/water_still"), + ResourceLocation.withDefaultNamespace("block/water_flow"), FluidType::new) .properties(p -> p.lightLevel(15).canConvertToSource(true)) .register(); diff --git a/docs/entries.md b/docs/entries.md index 9fbb5c8..797454c 100644 --- a/docs/entries.md +++ b/docs/entries.md @@ -59,7 +59,6 @@ public class ItemProviderEntry |---------------------|-------------------------------------------------------------------------| | `asStack()` | 创建包含此物品的 `ItemStack`(数量 1)/ Create an ItemStack (count 1) | | `asStack(int)` | 创建指定数量的 `ItemStack` / Create an ItemStack with specified count | -| `asStackTemplate()` | 创建 `ItemStackTemplate`(用于配方)/ Create an ItemStackTemplate (for recipes) | | `isIn(ItemStack)` | 检查物品栈是否包含此物品 / Check if a stack contains this item | | `is(Item)` | 检查是否特定物品 / Check if specific item | | `asItem()` | 获取 `Item` 对象 / Get the Item object | @@ -161,7 +160,7 @@ public class EntityEntry | 方法 / Method | 描述 / Description | |------------------------------------|-----------------------------------------------| -| `create(Level, EntitySpawnReason)` | 创建实体实例 / Create an entity instance | +| `create(Level)` | 创建实体实例 / Create an entity instance | | `is(Entity)` | 检查实体是否属于此类型 / Check if entity is of this type | | `cast(RegistryEntry)` | 静态转换方法 / Static cast method | @@ -170,9 +169,11 @@ public class EntityEntry ```java // 生成实体 // Spawn entity -MyEntity entity = MY_ENTITY.create(level, EntitySpawnReason.SPAWN_EGG); -entity.setPos(x, y, z); -level.addFreshEntity(entity); +MyEntity entity = MY_ENTITY.create(level); +if (entity != null) { + entity.setPos(x, y, z); + level.addFreshEntity(entity); +} ``` --- diff --git a/docs/providers.md b/docs/providers.md index e7a8970..858ab62 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -14,14 +14,14 @@ RegistrateLib has a built-in automatic data generation system. When you register |--------------------|-------------------------------------------------------|----------------------------------------| | `DYNAMIC` | `RegistrateDatapackProvider` | 动态数据包注册表 / Dynamic datapack registries | | `DATA_MAP` | `RegistrateDataMapProvider` | 数据映射 / Data maps | -| `RECIPE_RUNNER` | `RegistrateRecipeRunner` | 配方(入口点)/ Recipes (entry point) | +| `RECIPE` | `RegistrateRecipeProvider` | 配方 / Recipes | | `ADVANCEMENT` | `RegistrateAdvancementProvider` | 进度 / Advancements | | `LOOT` | `RegistrateLootTableProvider` | 战利品表 / Loot tables | -| `BLOCK_TAGS` | `RegistrateTagsProvider.IntrinsicImpl` | 方块标签 / Block tags | +| `BLOCK_TAGS` | `RegistrateTagsProvider.IntrinsicTags` | 方块标签 / Block tags | | `ITEM_TAGS` | `RegistrateItemTagsProvider` | 物品标签 / Item tags | -| `FLUID_TAGS` | `RegistrateTagsProvider.IntrinsicImpl` | 流体标签 / Fluid tags | -| `ENTITY_TAGS` | `RegistrateTagsProvider.IntrinsicImpl>` | 实体标签 / Entity type tags | -| `ENCHANTMENT_TAGS` | `RegistrateTagsProvider.Impl` | 附魔标签 / Enchantment tags | +| `FLUID_TAGS` | `RegistrateTagsProvider.IntrinsicTags` | 流体标签 / Fluid tags | +| `ENTITY_TAGS` | `RegistrateTagsProvider.IntrinsicTags>` | 实体标签 / Entity type tags | +| `ENCHANTMENT_TAGS` | `RegistrateTagsProvider.KeyTags` | 附魔标签 / Enchantment tags | | `GENERIC_SERVER` | `RegistrateGenericProvider` | 通用服务端提供者 / Generic server provider | ### 客户端提供者 / Client Providers @@ -41,7 +41,6 @@ These are finer-grained generator keys, typically used in builder `.setData()`. | 生成器 / Generator | 所属提供者 / Parent Provider | 用途 / Purpose | |-----------------|-------------------------|------------------------------------------------| -| `RECIPE` | `RECIPE_RUNNER` | 单个对象的配方生成 / Per-object recipe generation | | `BLOCKSTATE` | `MODEL` | 单个对象的方块状态生成 / Per-object blockstate generation | | `ITEM_MODEL` | `MODEL` | 单个对象的物品模型生成 / Per-object item model generation | @@ -56,11 +55,10 @@ Most builders provide direct methods to configure data generation: // 方块 — 方块状态、模型、战利品、配方、语言 // Block — blockstate, model, loot, recipe, lang REGISTRATE.block("my_block", MyBlock::new) - .blockstate(ctx -> { /* ... */ }) // 方块状态 / blockstate + .blockstate(() -> (ctx, prov) -> prov.simpleBlock(ctx.getEntry())) .loot((prov, block) -> { /* ... */ }) // 战利品表 / loot .recipe((ctx, prov) -> { /* ... */ }) // 配方 / recipe .lang("My Block") // 语言 / lang - .defaultBlockstate() // 使用默认值 / use defaults .defaultLoot() .register(); ``` @@ -149,8 +147,7 @@ REGISTRATE.block("my_block", MyBlock::new) .unlockedBy("has_egg", prov.has(Items.EGG)) .save(prov); - prov.food(DataIngredient.items(ctx), RecipeCategory.MISC, - CookingBookCategory.MISC, () -> Blocks.DIAMOND_BLOCK, 1f); + prov.food(DataIngredient.items(ctx), RecipeCategory.MISC, () -> Blocks.DIAMOND_BLOCK, 1f); }) .register(); ``` @@ -228,7 +225,7 @@ REGISTRATE.addDataGenerator(ProviderType.ADVANCEMENT, adv -> { .display(Items.EGG, adv.title(MOD_ID, "root", "Test Advancement"), adv.desc(MOD_ID, "root", "Get an egg."), - Identifier.withDefaultNamespace( + ResourceLocation.withDefaultNamespace( "textures/gui/advancements/backgrounds/stone.png"), AdvancementType.TASK, true, true, false) .save(adv, MOD_ID + ":root"); From e81c4740b626a81ef7f445654acd0856e22cf125 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:21:26 +0800 Subject: [PATCH 5/7] Sync Workflows with 26.1 [no-snapshot] (#8) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .github/actions/build_setup/action.yml | 6 +-- .github/json/config-1.21.json | 45 +++++++++++++++++++++++ .github/json/config-latest-1.21.json | 35 ++++++++++++++++++ .github/workflows/auto-build.yml | 9 +++-- .github/workflows/publish-on-release.yml | 22 +++++++++-- .github/workflows/publish.yml | 14 +++---- .github/workflows/sync.yml | 6 ++- .github/workflows/update-gradle-cache.yml | 4 +- 8 files changed, 118 insertions(+), 23 deletions(-) create mode 100644 .github/json/config-1.21.json create mode 100644 .github/json/config-latest-1.21.json diff --git a/.github/actions/build_setup/action.yml b/.github/actions/build_setup/action.yml index cda90ea..c852a0c 100644 --- a/.github/actions/build_setup/action.yml +++ b/.github/actions/build_setup/action.yml @@ -19,14 +19,14 @@ runs: - name: Set up JDK uses: actions/setup-java@v4 env: - REF: ${{ inputs.ref || github.ref }} + REF: ${{ inputs.ref || github.base_ref || github.ref }} with: distribution: temurin - java-version: 21 + java-version: ${{ contains(env.REF, '1.21') && '21' || '25' }} - name: Setup Gradle uses: gradle/actions/setup-gradle@v4 with: cache-write-only: ${{ inputs.update-cache }} - cache-read-only: ${{ github.ref != 'refs/heads/26.1' }} + cache-read-only: ${{ github.ref != 'refs/heads/26.1' && github.ref != 'refs/heads/1.21' }} add-job-summary: 'on-failure' diff --git a/.github/json/config-1.21.json b/.github/json/config-1.21.json new file mode 100644 index 0000000..a726d5d --- /dev/null +++ b/.github/json/config-1.21.json @@ -0,0 +1,45 @@ +{ + "categories": [ + { + "title": "### Added", + "labels": ["type: feature"] + }, + { + "title": "### Fixed", + "labels": ["type: bugfix"] + }, + { + "title": "### Changed", + "labels": ["type: refactor", "type: translation"] + } + ], + "sort": "ASC", + "template": "## Version [v#{{VERSION}}](#{{RELEASE_DIFF}})\n#{{CHANGELOG}} ", + "pr_template": "- #{{TITLE}} by @#{{AUTHOR}} in [##{{NUMBER}}](#{{URL}})", + "custom_placeholders": [ + { + "name": "VERSION", + "source": "TO_TAG", + "transformer": { + "pattern": "v?([0-9\\.]+)(-[0-9\\.]+)?", + "target": "$1" + } + } + ], + "empty_template": "", + "ignore_labels": ["ignore changelog"], + "tag_resolver": { + "method": "semver", + "filter": { + "pattern": "^(?!v?[0-9\\.]+(-1\\.21)$).+$", + "flags": "gu" + }, + "transformer": { + "pattern": "v?([0-9\\.]+)(-[0-9\\.]+)?", + "target": "$1" + } + }, + "max_pull_requests": 1000, + "max_back_track_time_days": 365, + "base_branches": ["1.21"] +} diff --git a/.github/json/config-latest-1.21.json b/.github/json/config-latest-1.21.json new file mode 100644 index 0000000..3ebbf9f --- /dev/null +++ b/.github/json/config-latest-1.21.json @@ -0,0 +1,35 @@ +{ + "categories": [ + { + "title": "### Added", + "labels": ["type: feature"] + }, + { + "title": "### Fixed", + "labels": ["type: bugfix"] + }, + { + "title": "### Changed", + "labels": ["type: refactor", "type: translation"] + } + ], + "sort": "ASC", + "template": "## What's Changed since #{{FROM_TAG}}\n#{{CHANGELOG}}\n#{{UNCATEGORIZED}}\n#{{CHANGES}} lines changed - see the [full diff here](#{{RELEASE_DIFF}})", + "pr_template": "- #{{TITLE}} by @#{{AUTHOR}} in [##{{NUMBER}}](#{{URL}})", + "empty_template": "", + "ignore_labels": ["ignore changelog"], + "tag_resolver": { + "method": "semver", + "filter": { + "pattern": "^(?!v?[0-9\\.]+(-1\\.21)$).+$", + "flags": "gu" + }, + "transformer": { + "pattern": "v?([0-9\\.]+)(-[0-9\\.]+)?", + "target": "$1" + } + }, + "max_pull_requests": 1000, + "max_back_track_time_days": 365, + "base_branches": ["1.21"] +} diff --git a/.github/workflows/auto-build.yml b/.github/workflows/auto-build.yml index 11a480b..dcf9748 100644 --- a/.github/workflows/auto-build.yml +++ b/.github/workflows/auto-build.yml @@ -2,7 +2,7 @@ name: Latest Build on: push: - branches: ['26.1'] + branches: ['26.1', '1.21'] paths: ['src/**', '**/*.gradle', 'gradle.properties'] concurrency: @@ -27,8 +27,6 @@ jobs: fetch-depth: 0 # do a full checkout instead of a shallow clone of HEAD so spotless's ratchetFrom works - name: Setup Build uses: ./.github/actions/build_setup - - name: Grant execute permission for gradlew - run: chmod +x gradlew - name: Get Mod Version id: ver run: echo "version=$(./gradlew -q printVersion)" >> $GITHUB_OUTPUT @@ -37,6 +35,9 @@ jobs: run: echo "VERSION_SUFFIX=$(echo "${{ github.sha }}" | cut -c 1-7)" >> $GITHUB_ENV - name: Build run: ./gradlew build + - name: Publish to Maven + if: ${{ github.repository_owner == 'ModularMCLib' && env.PUBLISH == 'true' }} + run: ./gradlew publish - name: Rename Jars if: ${{ env.PUBLISH == 'true' }} run: for file in build/libs/*; do mv "$file" "${file/SHOT/SHOT+$(date --utc '+%Y%m%d-%H%M%S')-${{ env.VERSION_SUFFIX }}}"; done; @@ -53,7 +54,7 @@ jobs: if: ${{ env.PUBLISH == 'true' }} uses: mikepenz/release-changelog-builder-action@v5 with: - configuration: "./.github/json/config-latest.json" + configuration: "./.github/json/config-latest${{ contains(github.ref_name, '1.21') && '-1.21' || '' }}.json" toTag: ${{ github.ref }} fetchViaCommits: true failOnError: false diff --git a/.github/workflows/publish-on-release.yml b/.github/workflows/publish-on-release.yml index ecd72fb..cf1ed07 100644 --- a/.github/workflows/publish-on-release.yml +++ b/.github/workflows/publish-on-release.yml @@ -23,17 +23,18 @@ jobs: id: changelog env: GITHUB_TOKEN: ${{ github.token }} + CONFIG: ${{ contains(github.ref_name, '1.21') && '-1.21' || '' }} uses: mikepenz/release-changelog-builder-action@v5 with: - configuration: './.github/json/config.json' + configuration: './.github/json/config${{ env.CONFIG }}.json' ignorePreReleases: true fetchViaCommits: true failOnError: true publish-26: - name: '26.1' + name: 26.1 needs: [ meta ] - if: ${{ contains(github.ref_name, '26.1') }} + if: ${{ contains(github.ref_name, '26.1') || !contains(github.ref_name, '1.21') }} secrets: inherit uses: ./.github/workflows/publish.yml with: @@ -41,4 +42,17 @@ jobs: tag-name: ${{ github.ref_name }} version: '26.1' release-body: ${{ github.event.release.body }} - changelog-body: ${{ needs.meta.outputs.CHANGELOG }} \ No newline at end of file + changelog-body: ${{ needs.meta.outputs.CHANGELOG }} + + publish-21: + name: 1.21.1 + needs: [ meta ] + if: ${{ contains(github.ref_name, '1.21') || !contains(github.ref_name, '26.1') }} + secrets: inherit + uses: ./.github/workflows/publish.yml + with: + simulate: ${{ startsWith(github.event.release.name, 'simulate') || github.repository_owner != 'ModularMCLib' }} + tag-name: ${{ github.ref_name }} + version: '1.21' + release-body: ${{ github.event.release.body }} + changelog-body: ${{ needs.meta.outputs.CHANGELOG }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c822ec7..5b05ad7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -11,7 +11,7 @@ on: required: true type: string version: - description: 'Version identifier;' + description: 'Version identifier; 26.1 or 1.21' required: true type: string release-body: @@ -36,13 +36,11 @@ jobs: steps: - uses: actions/checkout@v4 with: - ref: ${{ inputs.branch }} + ref: ${{ inputs.tag-name }} - name: Setup Build uses: ./.github/actions/build_setup with: - ref: ${{ inputs.branch }} - - name: Grant execute permission for gradlew - run: chmod +x gradlew + ref: ${{ inputs.tag-name }} - name: Get Version id: ver run: echo "version=$(./gradlew -q printVersion)" >> $GITHUB_OUTPUT @@ -158,7 +156,7 @@ jobs: steps: - uses: actions/checkout@v4 with: - ref: ${{ inputs.branch }} + ref: ${{ inputs.version }} - name: Bump Version run: | git config user.name 'github-actions[bot]' @@ -169,8 +167,10 @@ jobs: git commit -am "Bump version to ${BUMPED}" - name: Prepend to CHANGELOG if: inputs.changelog-body + env: + CHANGELOG_BODY: ${{ inputs.changelog-body }} run: | - { head -n 2 CHANGELOG.md; echo -e "${{ inputs.changelog-body }}"; tail -n +3 CHANGELOG.md; } > temp.md && mv temp.md CHANGELOG.md + { head -n 2 CHANGELOG.md; printf '%s\n' "$CHANGELOG_BODY"; tail -n +3 CHANGELOG.md; } > temp.md && mv temp.md CHANGELOG.md git commit -am "Updated CHANGELOG" - name: Push and PR env: diff --git a/.github/workflows/sync.yml b/.github/workflows/sync.yml index 4890463..f3debe9 100644 --- a/.github/workflows/sync.yml +++ b/.github/workflows/sync.yml @@ -12,12 +12,14 @@ jobs: GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v4 + with: + ref: '1.21' - run: | git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' git switch -C gh/workflow-sync git fetch origin git checkout origin/26.1 -- .github - git add .github - git commit --allow-empty -m "Sync Workflows" + git commit -am "Sync Workflows" git push --force --set-upstream origin gh/workflow-sync + gh pr create -B 1.21 -H gh/workflow-sync --title "Sync Workflows with 26.1 [no-snapshot]" --body "Created by GH Workflow" --label "ignore changelog" diff --git a/.github/workflows/update-gradle-cache.yml b/.github/workflows/update-gradle-cache.yml index 1146b6b..b2716fd 100644 --- a/.github/workflows/update-gradle-cache.yml +++ b/.github/workflows/update-gradle-cache.yml @@ -3,7 +3,7 @@ name: Update Gradle Cache on: push: - branches: ['26.1'] + branches: ['26.1', '1.21'] paths: ['gradle/**', '**/*.gradle', 'gradle.properties', 'gradlew*', 'src/main/resources/META-INF/accesstransformer.cfg'] workflow_dispatch: @@ -22,7 +22,5 @@ jobs: uses: ./.github/actions/build_setup with: update-cache: true - - name: Grant execute permission for gradlew - run: chmod +x gradlew - name: Build Project with Gradle run: ./gradlew assemble --warning-mode all From 726063633bb9e989dacb86e7de9f2290b49f6ce0 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Sat, 21 Nov 2026 14:28:21 +0800 Subject: [PATCH 6/7] =?UTF-8?q?=E9=87=8D=E5=86=99=20RegistrateLib=201.21.1?= =?UTF-8?q?=20=E5=B9=B6=E8=BF=81=E7=A7=BB=E5=88=B0=20Kotlin=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- README.md | 7 +- build.gradle | 20 +- dependencies.gradle | 9 + docs/getting-started.md | 4 +- docs/index.md | 3 +- docs/localization.md | 68 + docs/providers.md | 5 +- gradle.properties | 2 +- gradle/libs.versions.toml | 12 +- gradle/scripts/jars.gradle | 12 +- gradle/scripts/moddevgradle.gradle | 7 +- gradle/scripts/repositories.gradle | 3 +- gradle/scripts/spotless.gradle | 12 +- gradle/wrapper/gradle-wrapper.properties | 2 +- localization-processor/build.gradle | 48 + .../processor/TranslationProcessor.kt | 78 + .../LocalizationSymbolProcessorProvider.kt | 107 ++ .../gradle/incremental.annotation.processors | 1 + ...ols.ksp.processing.SymbolProcessorProvider | 1 + .../javax.annotation.processing.Processor | 1 + lombok.config | 16 - settings.gradle | 6 +- .../registrate/AbstractRegistrate.java | 1322 ---------------- .../registrate/AbstractRegistrate.kt | 1405 +++++++++++++++++ .../com/modularmc/registrate/Registrate.java | 43 - .../com/modularmc/registrate/Registrate.kt | 24 + .../registrate/builders/BlockBuilder.java | 386 ----- .../registrate/builders/BlockBuilder.kt | 407 +++++ .../builders/BlockEntityBuilder.java | 168 -- .../registrate/builders/BlockEntityBuilder.kt | 179 +++ .../registrate/builders/EntityBuilder.java | 300 ---- .../registrate/builders/EntityBuilder.kt | 326 ++++ .../registrate/builders/FluidBuilder.java | 647 -------- .../registrate/builders/FluidBuilder.kt | 680 ++++++++ .../registrate/builders/ItemBuilder.java | 369 ----- .../registrate/builders/ItemBuilder.kt | 324 ++++ .../registrate/builders/MenuBuilder.java | 80 - .../registrate/builders/MenuBuilder.kt | 86 + .../builders/base/AbstractBuilder.java | 183 --- .../builders/base/AbstractBuilder.kt | 133 ++ .../registrate/builders/base/Builder.java | 282 ---- .../registrate/builders/base/Builder.kt | 96 ++ .../builders/base/BuilderCallback.java | 62 - .../builders/base/BuilderCallback.kt | 25 + .../builders/base/NoConfigBuilder.java | 22 - .../builders/base/NoConfigBuilder.kt | 18 + .../internal/RegistrationTracker.java | 243 --- .../internal/RegistrationTracker.kt | 173 ++ .../internal/event/OneTimeEventReceiver.java | 111 -- .../internal/event/OneTimeEventReceiver.kt | 74 + .../lifecycle/RegistrateLifecycle.java | 75 - .../internal/lifecycle/RegistrateLifecycle.kt | 54 + .../internal/util/DebugMarkers.java | 19 - .../registrate/internal/util/DebugMarkers.kt | 16 + .../internal/util/RegistrateDistExecutor.java | 17 - .../internal/util/RegistrateDistExecutor.kt | 15 + .../internal/util/RegistrateLogger.java | 40 - .../internal/util/RegistrateLogger.kt | 30 + .../localization/EntryLocalization.kt | 8 + .../localization/LocalizationDeclaration.kt | 47 + .../localization/LocalizationProfile.kt | 12 + .../localization/MinecraftLocale.kt | 147 ++ .../registrate/localization/TextType.kt | 19 + .../registrate/localization/TranslationKey.kt | 5 + .../localization/TranslationSource.kt | 10 + .../localization/annotation/Trans.kt | 6 + .../localization/annotation/TransVariants.kt | 6 + .../localization/annotation/Translation.kt | 8 + .../localization/annotation/Variant.kt | 6 + .../localization/index/IndexedTranslations.kt | 41 + .../localization/index/LocalizationIndex.kt | 90 ++ .../resolution/MinecraftTextFormat.kt | 90 ++ .../resolution/TranslationRegistry.kt | 111 ++ .../localization/terminology/Domain.kt | 19 + .../terminology/LocalizationCatalog.kt | 39 + .../registrate/providers/DataGenContext.java | 47 - .../registrate/providers/DataGenContext.kt | 29 + .../RegistrateAdvancementProvider.java | 122 -- .../RegistrateAdvancementProvider.kt | 77 + .../providers/RegistrateDataMapProvider.java | 48 - .../providers/RegistrateDataMapProvider.kt | 31 + .../providers/RegistrateDatapackProvider.java | 30 - .../providers/RegistrateDatapackProvider.kt | 20 + .../providers/RegistrateGenericProvider.java | 72 - .../providers/RegistrateGenericProvider.kt | 47 + .../providers/RegistrateItemTagsProvider.java | 52 - .../providers/RegistrateItemTagsProvider.kt | 46 + .../providers/RegistrateLangProvider.java | 204 --- .../providers/RegistrateLangProvider.kt | 128 ++ .../providers/RegistrateTagsProvider.java | 140 -- .../providers/RegistrateTagsProvider.kt | 96 ++ .../registrate/providers/core/DataGenBatch.kt | 48 + .../core/DataProviderInitializer.java | 57 - .../providers/core/DataProviderInitializer.kt | 52 + .../providers/core/GeneratorType.java | 3 - .../providers/core/GeneratorType.kt | 4 + .../providers/core/LanguageOutput.kt | 30 + .../providers/core/ProviderType.java | 159 -- .../registrate/providers/core/ProviderType.kt | 190 +++ .../core/RegistrateDataProvider.java | 111 -- .../providers/core/RegistrateDataProvider.kt | 106 ++ .../core/RegistrateLookupFillerProvider.java | 10 - .../core/RegistrateLookupFillerProvider.kt | 10 + .../providers/core/RegistrateProvider.java | 9 - .../providers/core/RegistrateProvider.kt | 9 + .../core/RegistrateProviderDelegate.java | 13 - .../core/RegistrateProviderDelegate.kt | 13 + .../RegistrateBlockModelGenerator.java | 86 - .../RegistrateBlockModelGenerator.kt | 57 + .../RegistrateItemModelGenerator.java | 106 -- .../RegistrateItemModelGenerator.kt | 75 + .../generators/RegistrateModelProvider.java | 25 - .../generators/RegistrateModelProvider.kt | 16 + .../generators/RegistrateRecipeProvider.java | 636 -------- .../generators/RegistrateRecipeProvider.kt | 810 ++++++++++ .../loot/RegistrateBlockLootTables.java | 283 ---- .../loot/RegistrateBlockLootTables.kt | 225 +++ .../loot/RegistrateEntityLootTables.java | 96 -- .../loot/RegistrateEntityLootTables.kt | 91 ++ .../loot/RegistrateLootTableProvider.java | 123 -- .../loot/RegistrateLootTableProvider.kt | 108 ++ .../providers/loot/RegistrateLootTables.java | 16 - .../providers/loot/RegistrateLootTables.kt | 15 + .../util/CreativeModeTabModifier.java | 53 - .../util/CreativeModeTabModifier.kt | 39 + .../registrate/util/DataIngredient.java | 97 -- .../registrate/util/DataIngredient.kt | 57 + .../util/entry/BlockEntityEntry.java | 74 - .../registrate/util/entry/BlockEntityEntry.kt | 33 + .../registrate/util/entry/BlockEntry.java | 26 - .../registrate/util/entry/BlockEntry.kt | 19 + .../registrate/util/entry/EntityEntry.java | 29 - .../registrate/util/entry/EntityEntry.kt | 20 + .../registrate/util/entry/EntryMetadata.kt | 19 + .../registrate/util/entry/FluidEntry.java | 53 - .../registrate/util/entry/FluidEntry.kt | 31 + .../registrate/util/entry/ItemEntry.java | 17 - .../registrate/util/entry/ItemEntry.kt | 14 + .../util/entry/ItemProviderEntry.java | 36 - .../util/entry/ItemProviderEntry.kt | 22 + .../util/entry/LazyRegistryEntry.java | 25 - .../util/entry/LazyRegistryEntry.kt | 9 + .../registrate/util/entry/MenuEntry.java | 46 - .../registrate/util/entry/MenuEntry.kt | 37 + .../registrate/util/entry/RegistryEntry.java | 81 - .../registrate/util/entry/RegistryEntry.kt | 37 + .../nullness/FieldsAreNonnullByDefault.java | 25 - .../util/nullness/NonNullBiConsumer.java | 14 - .../util/nullness/NonNullBiConsumer.kt | 14 + .../util/nullness/NonNullBiFunction.java | 10 - .../util/nullness/NonNullBiFunction.kt | 9 + .../util/nullness/NonNullConsumer.java | 23 - .../util/nullness/NonNullConsumer.kt | 19 + .../util/nullness/NonNullFunction.java | 16 - .../util/nullness/NonNullFunction.kt | 11 + .../util/nullness/NonNullSupplier.java | 33 - .../util/nullness/NonNullSupplier.kt | 30 + .../util/nullness/NonNullUnaryOperator.java | 16 - .../util/nullness/NonNullUnaryOperator.kt | 12 + .../registrate/util/nullness/NonnullType.java | 18 - .../registrate/util/nullness/NonnullType.kt | 18 + .../util/nullness/NullableSupplier.java | 32 - .../util/nullness/NullableType.java | 18 - .../util/nullness/package-info.java | 4 +- .../resources/assets/testmod/lang/en_ud.json | 3 +- .../resources/assets/testmod/lang/en_us.json | 1 + .../resources/assets/testmod/lang/zh_cn.json | 4 + .../test/gametests/CustomItemTests.java | 24 - .../test/gametests/CustomItemTests.kt | 24 + .../test/gametests/LocalizationTests.kt | 145 ++ .../gametests/RegistrationRuntimeTests.java | 44 - .../gametests/RegistrationRuntimeTests.kt | 96 ++ .../registrate/test/meta/MethodGenerator.java | 103 -- .../registrate/test/meta/MethodGenerator.kt | 122 ++ .../test/meta/ProtectedMethodScraper.java | 127 -- .../test/meta/ProtectedMethodScraper.kt | 89 ++ .../test/meta/UpdateBlockLootTables.java | 12 - .../test/meta/UpdateBlockLootTables.kt | 13 + .../test/meta/UpdateEntityLootTables.java | 13 - .../test/meta/UpdateEntityLootTables.kt | 14 + .../test/meta/UpdateRecipeProvider.java | 13 - .../test/meta/UpdateRecipeProvider.kt | 12 + .../test/mod/KotlinRegistrations.kt | 37 + .../registrate/test/mod/TestMod.java | 76 +- .../mod/localization/ChineseLocaleTestMod.kt | 37 + .../test/mod/localization/EnglishLabels.kt | 26 + .../resources/META-INF/neoforge.mods.toml | 13 + 188 files changed, 8564 insertions(+), 7985 deletions(-) create mode 100644 docs/localization.md create mode 100644 localization-processor/build.gradle create mode 100644 localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt create mode 100644 localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt create mode 100644 localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors create mode 100644 localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider create mode 100644 localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor delete mode 100644 lombok.config delete mode 100644 src/main/java/com/modularmc/registrate/AbstractRegistrate.java create mode 100644 src/main/java/com/modularmc/registrate/AbstractRegistrate.kt delete mode 100644 src/main/java/com/modularmc/registrate/Registrate.java create mode 100644 src/main/java/com/modularmc/registrate/Registrate.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/BlockBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/EntityBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/FluidBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/ItemBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/MenuBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/base/Builder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/Builder.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt delete mode 100644 src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java create mode 100644 src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt delete mode 100644 src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java create mode 100644 src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt delete mode 100644 src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java create mode 100644 src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt delete mode 100644 src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java create mode 100644 src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt delete mode 100644 src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java create mode 100644 src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt delete mode 100644 src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java create mode 100644 src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt delete mode 100644 src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java create mode 100644 src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/LocalizationProfile.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/TextType.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/TranslationKey.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/TranslationSource.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt create mode 100644 src/main/java/com/modularmc/registrate/localization/terminology/LocalizationCatalog.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/DataGenContext.java create mode 100644 src/main/java/com/modularmc/registrate/providers/DataGenContext.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.kt create mode 100644 src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/GeneratorType.kt create mode 100644 src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/core/ProviderType.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java create mode 100644 src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.kt delete mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java create mode 100644 src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java create mode 100644 src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/DataIngredient.java create mode 100644 src/main/java/com/modularmc/registrate/util/DataIngredient.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/BlockEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/EntityEntry.kt create mode 100644 src/main/java/com/modularmc/registrate/util/entry/EntryMetadata.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/FluidEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/ItemEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/MenuEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java create mode 100644 src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java create mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NonnullType.kt delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java delete mode 100644 src/main/java/com/modularmc/registrate/util/nullness/NullableType.java create mode 100644 src/test/generated/resources/assets/testmod/lang/zh_cn.json delete mode 100644 src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java create mode 100644 src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.kt create mode 100644 src/test/java/com/modularmc/registrate/test/gametests/LocalizationTests.kt delete mode 100644 src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java create mode 100644 src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.kt delete mode 100644 src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.kt delete mode 100644 src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.kt delete mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.kt delete mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.kt delete mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java create mode 100644 src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.kt create mode 100644 src/test/java/com/modularmc/registrate/test/mod/KotlinRegistrations.kt create mode 100644 src/test/java/com/modularmc/registrate/test/mod/localization/ChineseLocaleTestMod.kt create mode 100644 src/test/java/com/modularmc/registrate/test/mod/localization/EnglishLabels.kt diff --git a/.gitignore b/.gitignore index 01a89a8..ab1c4d8 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,7 @@ classes/ .settings *.launch .architectury-transformer/debug.log -**/resources/.cache/ +**/resources/ *.patch *.DS_Store diff --git a/README.md b/README.md index ce3a426..0ac669f 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ This repository is the `com.modularmc.registrate` fork maintained for the Modula First, create a `Registrate` object which will be used across your entire project. ```java -public static final Registrate REGISTRATE = Registrate.create(MOD_ID); +public static final Registrate REGISTRATE = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); ``` 不一定要使用常量字段,可以在注册设置完成后传递或丢弃。 @@ -77,7 +77,8 @@ Using a constant field is not necessary, it can be passed around and thrown away If declared static in your `@Mod` class, you must create the `Registrate` object lazily so it is not created too early during loading. This can be done easily like so: ```java -public static final NonNullSupplier REGISTRATE = NonNullSupplier.lazy(() -> Registrate.create(MOD_ID)); +public static final NonNullSupplier REGISTRATE = + NonNullSupplier.lazy(() -> Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US)); ``` 接下来,开始添加对象。 @@ -119,6 +120,8 @@ public static final BlockEntry MY_STAIRS = REGISTRATE.block("my_s 这个自定义版本会创建 BlockItem(含默认模型和语言条目)、将方块添加到标签、配置楼梯属性方块状态,并添加自定义本地化。 This customized version will create a BlockItem (with its own default model and lang entry), add the block to a tag, configure the blockstate for stair properties, and add a custom localization. +源语言、译文和注解处理器的接入方式见 [本地化与迁移](docs/localization.md)。 + 有关不同 API 和方法的概述,请查阅 Javadocs(待定)。更高级的用法请阅读 [维基](https://github.com/ModularMCLib/RegistrateLib/wiki)(编写中)。 diff --git a/build.gradle b/build.gradle index 5499a08..6fd234e 100644 --- a/build.gradle +++ b/build.gradle @@ -1,13 +1,15 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmDefaultMode + plugins { id 'java-library' - id 'org.jetbrains.kotlin.jvm' id 'eclipse' id 'idea' id 'maven-publish' alias libs.plugins.modDevGradle //alias libs.plugins.shadow alias libs.plugins.spotless - alias libs.plugins.lombok + alias libs.plugins.kotlin.jvm + alias libs.plugins.ksp } group = maven_group @@ -20,6 +22,13 @@ java { toolchain.languageVersion = JavaLanguageVersion.of(21) } +kotlin { + jvmToolchain(21) + compilerOptions { + jvmDefault = JvmDefaultMode.NO_COMPATIBILITY + } +} + sourceSets { // Include resources generated by data generators. main.resources { @@ -78,16 +87,13 @@ apply from: "$rootDir/gradle/scripts/resources.gradle" apply from: "$rootDir/gradle/scripts/publishing.gradle" apply from: "$rootDir/gradle/scripts/spotless.gradle" - tasks.withType(JavaCompile).configureEach { options.encoding = "UTF-8" + options.compilerArgs << '-Xmaxerrs' << '2000' options.compilerArgs << "-Xlint:-removal" } tasks.named('test') { + // The test source set is exercised by NeoForge's GameTest server. failOnNoDiscoveredTests = false } - -lombok { - version = "1.18.38" -} \ No newline at end of file diff --git a/dependencies.gradle b/dependencies.gradle index 35602b2..70a5865 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -2,7 +2,16 @@ dependencies { compileOnly(libs.jetbrains.annotations) compileOnly(libs.jspecify) + jarJar(api(libs.kotlin.stdlib.get())) { + exclude group: 'org.jetbrains', module: 'annotations' + } + additionalRuntimeClasspath(libs.kotlin.stdlib.get()) { + exclude group: 'org.jetbrains', module: 'annotations' + } + testImplementation(libs.testframework.get()) + testAnnotationProcessor(project(':localization-processor')) + kspTest(project(':localization-processor')) // Standard runtime mods // localRuntime(libs.testframework) diff --git a/docs/getting-started.md b/docs/getting-started.md index 13405d3..39cd0c5 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -39,7 +39,7 @@ public class MyMod { // 简单方式(注意:需确保不在构造之前访问) // Simple approach (ensure it's not accessed before construction) - public static final Registrate REGISTRATE = Registrate.create(MOD_ID); + public static final Registrate REGISTRATE = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); public MyMod(IEventBus modEventBus) { // 在此处注册事件监听器 @@ -55,7 +55,7 @@ If you need lazy initialization to avoid creating too early during class loading ```java public static final NonNullSupplier REGISTRATE = - NonNullSupplier.lazy(() -> Registrate.create(MOD_ID)); + NonNullSupplier.lazy(() -> Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US)); ``` ## 注册你的第一个对象 / Registering Your First Object diff --git a/docs/index.md b/docs/index.md index e46d845..1234203 100644 --- a/docs/index.md +++ b/docs/index.md @@ -19,7 +19,7 @@ RegistrateLib is a powerful fluent registration API wrapper for creating and reg ```java // 创建 Registrate 实例 / Create a Registrate instance -public static final Registrate REGISTRATE = Registrate.create(MOD_ID); +public static final Registrate REGISTRATE = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); // 注册一个简单的方块 / Register a simple block public static final BlockEntry MY_BLOCK = REGISTRATE.block("my_block", Block::new) @@ -38,6 +38,7 @@ public static final ItemEntry MY_ITEM = REGISTRATE.item("my_item", Item::n 3. [注册条目](entries.md) — 注册返回的强类型句柄 / Strongly-typed registry entry handles 4. [数据提供者](providers.md) — 数据生成系统详解 / Data generation system in detail 5. [高级用法](advanced.md) — 自定义注册表、生命周期钩子等 / Custom registries, lifecycle hooks, and more +6. [本地化与迁移](localization.md) / Localization and migration ## 架构概述 / Architecture Overview diff --git a/docs/localization.md b/docs/localization.md new file mode 100644 index 0000000..311353b --- /dev/null +++ b/docs/localization.md @@ -0,0 +1,68 @@ +# 1.21.1 本地化与迁移 + +## 配置源语言 + +为每个生成语言数据的模组设置 `MinecraftLocale`。把原有 `.lang(String)` 和 `addRawLang` 文本实际使用的语言设为源语言。`defaultLang()` 从注册路径生成英文名称,适用于 `EN_US`。其他源语言的对象可用 `.lang(String)` 或 `.localization(...)` 声明源文本。 + +```java +import com.modularmc.registrate.Registrate; +import com.modularmc.registrate.localization.MinecraftLocale; + +Registrate registrate = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); +``` + +## 声明文本 + +物品、方块、实体和流体的 Builder 从注册对象取 Minecraft 原生翻译 Key。通用 Builder 可用 `.localization(keyFunction, text -> ...)` 指定取 Key 的方式。 + +```java +registrate.item("copper_ingot", Item::new) + .localization(text -> text + .source("Copper Ingot") + .domain(Domain.MATERIALS) + .type(TextType.MATERIAL) + .translation(MinecraftLocale.ZH_CN, "铜锭")) + .register(); + +var title = registrate.addLocalization(new TranslationKey(MOD_ID, "gui.mymod.voltage"), + text -> text.source("Voltage: %s V").translation(MinecraftLocale.ZH_CN, "电压:%1$s V")); +``` + +`addLocalization` 返回可用于 GUI 的翻译组件。进度标题等跨侧文本可在模组构造期间声明,在服务端 DataGen 的进度回调中引用组件。`addLang`、`addRawLang` 和 `ProviderType.LANG` 回调都使用同一个源 Locale。 + +在 `registrate.localizationCatalog()` 中登记 `Domain`、`GlossaryTerm` 和 `Unit`。Builder 的 `.profile(profile)` 可复用领域、文本类型和术语。条目的显式参数覆盖 Profile 的相应字段。 + +## 接入注解处理器 + +用 `./gradlew :localization-processor:jar` 构建与库版本对应的处理器。Java 源码使用 `annotationProcessor`,Kotlin 源码使用 KSP 插件和 `ksp`。混合项目可同时使用两项配置,主库作为模组依赖。 + +```groovy +dependencies { + def processor = files("libs/registratelib-1.21.1-${registratelib_version}-localization-processor.jar") + annotationProcessor(processor) + ksp(processor) +} +``` + +`@Trans` 和 `@TransVariants` 可以声明在类型或字段上。`modId` 选择声明归属的模组和源 Locale。省略 `namespace` 时,资源命名空间取 `modId`。 + +```java +@TransVariants(modId = "mymod", keyPrefix = "gui.mymod.power", value = { + @Variant(id = "low", source = "Low power"), + @Variant(id = "high", source = "High power") +}) +final class Labels { + @Trans(modId = "mymod", key = "gui.mymod.container", source = "Test Container", + translations = @Translation(locale = MinecraftLocale.ZH_CN, text = "测试容器")) + static final String CONTAINER = "gui.mymod.container"; +} +``` + +Kotlin 中在带有后备字段的属性上使用 `@field:Trans` 或 `@field:TransVariants`。两个处理器按 Mod ID 写入各自的版本化声明索引,DataGen 从所属模组读取并合并。变体的 Key 由前缀和 ID 拼接,例如 `gui.mymod.power.low`。同一命名空间、Key 和 Locale 下,同级异值声明会报告双方来源。`%s` 的隐式索引按出现顺序分配,译文可用 `%1$s` 等显式索引重排。 + +## 注册兼容性 + +- `RegistryEntry.metadata()` 提供条目的本地化声明和 DataGen 回调视图。读取本地化声明所引用的原生 Key 时,目标 Holder 需要已绑定。 +- 已有样例沿用原注册 ID 和原生翻译 Key。BlockItem 复用方块名称时,复用同一个 Key。 +- 混合源码项目可在 Java 的 `@Mod` 入口创建 `Registrate` 并把它传给 Kotlin 注册类。测试模组用同一实例注册 `testmod:magic_item_model`,GameTest 从 Java 入口的实例查找该方块,并核对 BlockItem 的 `block.testmod.magic_item_model`。 +- 同一个 Registrate 实例内,同一注册表的重复 ID 会在提交时失败。不同注册表可以使用相同的名称。 diff --git a/docs/providers.md b/docs/providers.md index 858ab62..f7e8894 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -67,8 +67,9 @@ REGISTRATE.block("my_block", MyBlock::new) ## RegistrateLangProvider —— 语言提供者 / Lang Provider -自动生成 `en_us` 和 `en_ud`(上下颠倒)语言文件。 -Automatically generates `en_us` and `en_ud` (upside-down) lang files. +按模组的源 Locale 和显式译文生成语言文件。由 `en_us` 条目派生 `en_ud`(上下颠倒)文本。 [本地化与迁移](localization.md) + +Generates language files from the mod's source locale and explicit translations. Derives upside-down text from `en_us` entries. ```java // 通过 Registrate 添加语言条目 / Add lang entries via Registrate diff --git a/gradle.properties b/gradle.properties index 890e56c..2045f95 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,7 +7,7 @@ org.gradle.caching = true # Mod Info mod_id = registratelib mod_name = RegistrateLib -mod_version = 2.0.1 +mod_version = 2.0.0 mod_description = mod_license = Mozilla Public License Version 2.0 mod_url = https://github.com/ModularMCLib/Registrate-Lib/ diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 63d131b..468b355 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,9 +4,10 @@ neoForge = "21.1.265" loader = "4" parchment = "2024.11.17" # https://parchmentmc.org/docs/getting-started shadow = "9.6.1" -spotless = "8.10.4" -modDevGradle = "2.0.147" -lombok = "9.8.2" +spotless = "8.11.0" +modDevGradle = "2.0.148" +kotlin = "2.4.21" +ksp = "2.3.14" jetbrains-annotations = "26.1.0" jspecify = "1.0.1" renderNurse = "0.0.26" @@ -16,6 +17,8 @@ mixin = "0.8.7" minecraft = { module = "com.mojang:minecraft", version.ref = "minecraft" } neoForge = { module = "net.neoforged:neoforge", version.ref = "neoForge" } testframework = { module = "net.neoforged:testframework", version.ref = "neoForge" } +kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } +ksp-api = { module = "com.google.devtools.ksp:symbol-processing-api", version.ref = "ksp" } renderNurse = { module = "net.neoforged:render-nurse", version.ref = "renderNurse" } mixin = { module = "org.spongepowered:mixin", version.ref = "mixin" } jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } @@ -25,4 +28,5 @@ jspecify = { module = "org.jspecify:jspecify", version.ref = "jsp modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGradle" } shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } -lombok = { id = "io.freefair.lombok", version.ref = "lombok" } \ No newline at end of file +kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } +ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index d95fbea..e60d0db 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -3,6 +3,10 @@ jar { exclude "**/SimplifiedToTraditional.properties" } +tasks.named('assemble') { + dependsOn(':localization-processor:jar') +} + tasks.register('slimJar', Jar) { dependsOn("classes") archiveClassifier = "slim" @@ -13,14 +17,6 @@ java { withSourcesJar() } -// Use delombok'd files for sources -sourcesJar { - exclude { - sourceSets.main.allSource.contains it.file - } - from delombok -} - base { archivesName = "${project.name}-${libs.versions.minecraft.get()}" } diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle index a70c044..c82b568 100644 --- a/gradle/scripts/moddevgradle.gradle +++ b/gradle/scripts/moddevgradle.gradle @@ -90,9 +90,10 @@ neoForge { gameDirectory.set(file('run/data')) // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - programArguments.addAll('--mod', devTestModId) - programArguments.addAll('--all') - programArguments.addAll('--output', file('src/test/generated/resources/').getAbsolutePath()) + programArguments.addAll('--mod', "${devTestModId},localetest", '--flat') + programArguments.add(providers.gradleProperty('testDataSide').orElse('all').map { "--${it}".toString() }) + programArguments.add('--output') + programArguments.add(providers.gradleProperty('testDataOutput').orElse('src/test/generated/resources').map { file(it).absolutePath }) programArguments.addAll('--existing', file('src/test/resources/').getAbsolutePath()) } diff --git a/gradle/scripts/repositories.gradle b/gradle/scripts/repositories.gradle index 792c1d0..ed998d0 100644 --- a/gradle/scripts/repositories.gradle +++ b/gradle/scripts/repositories.gradle @@ -1,13 +1,14 @@ repositories { mavenLocal() mavenCentral() - // force gradle to download FastUtil & LWJGL from the central maven so we can get source artifacts + // Resolve libraries hosted on Maven Central without querying mod repositories. exclusiveContent { // Force forRepository { mavenCentral() } filter { includeGroup("it.unimi.dsi") includeGroup("org.lwjgl") includeGroup("com.google.guava") + includeGroup("com.google.devtools.ksp") includeGroupAndSubgroups("io.netty") includeGroupAndSubgroups("org.jetbrains") } diff --git a/gradle/scripts/spotless.gradle b/gradle/scripts/spotless.gradle index 5ecb0f9..7f8f125 100644 --- a/gradle/scripts/spotless.gradle +++ b/gradle/scripts/spotless.gradle @@ -9,7 +9,7 @@ spotless { endWithNewline() } java { - target 'src/main/java/**/*.java', 'src/test/java/**/*.java' + target 'src/*/java/**/*.java', 'localization-processor/src/main/java/**/*.java' def orderFile = file("$rootDir/gradle/spotless/spotless.importorder") def formatFile = file("$rootDir/gradle/spotless/spotless.eclipseformat.xml") @@ -23,12 +23,20 @@ spotless { eclipse('4.31').configFile(formatFile) } kotlin { - target'src/main/java/**/*.kt', 'src/test/java/**/*.kt' + target 'src/*/java/**/*.kt', 'localization-processor/src/*/java/**/*.kt' def orderFile = file("$rootDir/gradle/spotless/spotless.ktlint") ktlint().setEditorConfigPath(orderFile) + .editorConfigOverride([ + 'ktlint_standard_no-unused-imports': 'enabled', + ]) toggleOffOn() + replaceRegex( + 'empty Kotlin function bodies', + /(?m)(fun[^\n{=]*\([^)]*\)(?:\s*:\s*[^\n{=]+)?\s*)\{\r?\n[ \t]*\}/, + '$1{}' + ) trimTrailingWhitespace() leadingSpacesToTabs() endWithNewline() diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 94c356a..04d7959 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip networkTimeout=10000 retries=0 retryBackOffMs=500 diff --git a/localization-processor/build.gradle b/localization-processor/build.gradle new file mode 100644 index 0000000..26605dd --- /dev/null +++ b/localization-processor/build.gradle @@ -0,0 +1,48 @@ +plugins { + alias libs.plugins.kotlin.jvm +} + +group = rootProject.group +version = rootProject.version + +java { + toolchain.languageVersion.set(rootProject.java.toolchain.languageVersion) +} + +kotlin { + jvmToolchain(rootProject.java.toolchain.languageVersion.get().asInt()) +} + +configurations { + processorKotlinRuntime { + canBeConsumed = false + } +} + +dependencies { + compileOnly(libs.ksp.api) + compileOnly(project(':')) { + transitive = false + } + processorKotlinRuntime(libs.kotlin.stdlib) { + transitive = false + } +} + +tasks.named('jar', Jar) { + archiveBaseName.set(rootProject.base.archivesName) + archiveClassifier = 'localization-processor' + destinationDirectory.set(rootProject.layout.buildDirectory.dir('libs')) + + // The processor needs these types on javac's isolated processor path. + from(rootProject.sourceSets.main.output.classesDirs) { + include 'com/modularmc/registrate/localization/annotation/**' + include 'com/modularmc/registrate/localization/MinecraftLocale.class' + include 'com/modularmc/registrate/localization/index/LocalizationIndex*.class' + } + + // Keep the standalone compiler path working for Java consumers. + from({ zipTree(configurations.processorKotlinRuntime.singleFile) }) { + include 'kotlin/**', 'META-INF/*.kotlin_module', 'META-INF/LICENSE*', 'META-INF/NOTICE*' + } +} diff --git a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt new file mode 100644 index 0000000..cce465d --- /dev/null +++ b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt @@ -0,0 +1,78 @@ +package com.modularmc.registrate.localization.processor + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.annotation.Trans +import com.modularmc.registrate.localization.annotation.TransVariants +import com.modularmc.registrate.localization.annotation.Translation +import com.modularmc.registrate.localization.index.LocalizationIndex +import com.modularmc.registrate.localization.index.LocalizationIndex.Entry + +import java.io.DataOutputStream +import java.io.IOException +import java.util.EnumMap +import javax.annotation.processing.AbstractProcessor +import javax.annotation.processing.RoundEnvironment +import javax.annotation.processing.SupportedSourceVersion +import javax.lang.model.SourceVersion +import javax.lang.model.element.Element +import javax.lang.model.element.TypeElement +import javax.tools.StandardLocation + +/** Collects the annotated declarations from all rounds of a downstream Java compilation. */ +@SupportedSourceVersion(SourceVersion.RELEASE_21) +class TranslationProcessor : AbstractProcessor() { + private val declarations = LinkedHashMap>() + + private data class Declaration(val element: Element, val entry: Entry) + + override fun getSupportedAnnotationTypes(): Set = setOf(Trans::class.java.name, TransVariants::class.java.name) + + override fun process(annotations: Set, round: RoundEnvironment): Boolean { + for (element in round.getElementsAnnotatedWith(Trans::class.java)) { + val trans = element.getAnnotation(Trans::class.java) + add(trans.modId, trans.namespace, trans.key, trans.source, trans.translations, element, "@Trans ${location(element)}") + } + for (element in round.getElementsAnnotatedWith(TransVariants::class.java)) { + val group = element.getAnnotation(TransVariants::class.java) + for (variant in group.value) { + val key = LocalizationIndex.variantKey(group.keyPrefix, variant.id) + add(group.modId, group.namespace, key, variant.source, variant.translations, element, "@TransVariants ${location(element)} [${variant.id}]") + } + } + if (round.processingOver() && !round.errorRaised()) { + declarations.forEach(::write) + } + return true + } + + private fun add(modId: String, namespace: String, key: String, source: String, translations: Array, element: Element, location: String) { + val texts = if (translations.isEmpty()) { + emptyMap() + } else { + EnumMap(MinecraftLocale::class.java).apply { + for (translation in translations) put(translation.locale, translation.text) + } + } + val entry = Entry(namespace.ifEmpty { modId }, key, source, location, texts) + declarations.getOrPut(modId, ::ArrayList).add(Declaration(element, entry)) + } + + private fun write(modId: String, declarations: List) { + val path = LocalizationIndex.path(modId) + val origins = declarations.mapTo(LinkedHashSet(), Declaration::element).toTypedArray() + try { + val resource = processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", path, *origins) + DataOutputStream(resource.openOutputStream().buffered()).use { output -> + LocalizationIndex.write(output, declarations.map(Declaration::entry)) + } + } catch (error: IOException) { + processingEnv.messager.printError("Cannot write localization index $path: ${error.message}") + } + } + + private fun location(element: Element): String { + if (element is TypeElement) return element.qualifiedName.toString() + val owner = element.enclosingElement as TypeElement + return "${owner.qualifiedName}#${element.simpleName}" + } +} diff --git a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt new file mode 100644 index 0000000..65b3194 --- /dev/null +++ b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt @@ -0,0 +1,107 @@ +package com.modularmc.registrate.localization.processor.ksp + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.annotation.Trans +import com.modularmc.registrate.localization.annotation.TransVariants +import com.modularmc.registrate.localization.index.LocalizationIndex +import com.modularmc.registrate.localization.index.LocalizationIndex.Entry +import com.modularmc.registrate.localization.index.LocalizationIndex.Frontend + +import com.google.devtools.ksp.processing.CodeGenerator +import com.google.devtools.ksp.processing.Dependencies +import com.google.devtools.ksp.processing.Resolver +import com.google.devtools.ksp.processing.SymbolProcessor +import com.google.devtools.ksp.processing.SymbolProcessorEnvironment +import com.google.devtools.ksp.processing.SymbolProcessorProvider +import com.google.devtools.ksp.symbol.FileLocation +import com.google.devtools.ksp.symbol.KSAnnotated +import com.google.devtools.ksp.symbol.KSAnnotation +import com.google.devtools.ksp.symbol.KSClassDeclaration +import com.google.devtools.ksp.symbol.KSDeclaration +import com.google.devtools.ksp.symbol.KSFile +import com.google.devtools.ksp.symbol.KSPropertyDeclaration +import com.google.devtools.ksp.symbol.Origin + +import java.io.DataOutputStream +import java.util.EnumMap + +class LocalizationSymbolProcessorProvider : SymbolProcessorProvider { + override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = LocalizationSymbolProcessor(environment.codeGenerator) +} + +/** Collects Kotlin declarations and writes one aggregating KSP resource per mod. */ +private class LocalizationSymbolProcessor(private val codeGenerator: CodeGenerator) : SymbolProcessor { + private class ModDeclarations { + val entries = ArrayList() + val files = LinkedHashSet() + } + + private val mods = LinkedHashMap() + + override fun process(resolver: Resolver): List { + collect(resolver, Trans::class.java.name) { annotation, location, group, namespace -> + group.entries.add(entry(namespace, annotation["key"] as String, annotation, "@Trans $location")) + } + collect(resolver, TransVariants::class.java.name) { annotation, location, group, namespace -> + val prefix = annotation["keyPrefix"] as String + for (variant in annotation["value"] as List<*>) { + variant as KSAnnotation + val id = variant["id"] as String + group.entries.add(entry(namespace, LocalizationIndex.variantKey(prefix, id), variant, "@TransVariants $location [$id]")) + } + } + return emptyList() + } + + override fun finish() { + for ((modId, group) in mods) { + val dependencies = Dependencies(aggregating = true, *group.files.toTypedArray()) + val path = LocalizationIndex.path(modId, Frontend.KSP).removeSuffix(".bin") + val resource = codeGenerator.createNewFileByPath(dependencies, path, "bin") + DataOutputStream(resource.buffered()).use { LocalizationIndex.write(it, group.entries) } + } + } + + private inline fun collect(resolver: Resolver, annotationName: String, consume: (KSAnnotation, String, ModDeclarations, String) -> Unit) { + for (symbol in resolver.getSymbolsWithAnnotation(annotationName)) { + if (symbol.origin != Origin.KOTLIN) continue + val declaration = symbol as KSDeclaration + val annotation = declaration.annotations.first { it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationName } + val modId = annotation["modId"] as String + val namespace = (annotation["namespace"] as String).ifEmpty { modId } + val file = declaration.containingFile!! + val group = mods.getOrPut(modId, ::ModDeclarations) + group.files.add(file) + consume(annotation, location(declaration, file), group, namespace) + } + } + + private fun entry(namespace: String, key: String, annotation: KSAnnotation, location: String): Entry { + val translations = annotation["translations"] as List<*> + val texts = if (translations.isEmpty()) { + emptyMap() + } else { + EnumMap(MinecraftLocale::class.java).apply { + for (value in translations) { + value as KSAnnotation + val locale = (value["locale"] as KSClassDeclaration).simpleName.asString() + put(MinecraftLocale.valueOf(locale), value["text"] as String) + } + } + } + return Entry(namespace, key, annotation["source"] as String, location, texts) + } + + private fun location(declaration: KSDeclaration, file: KSFile): String { + val owner = declaration.parentDeclaration + val name = if (declaration is KSPropertyDeclaration && owner != null) { + "${owner.qualifiedName?.asString()}#${declaration.simpleName.asString()}" + } else { + declaration.qualifiedName?.asString() ?: declaration.simpleName.asString() + } + val line = (declaration.location as FileLocation).lineNumber + return "$name (${file.fileName}:$line)" + } + + private operator fun KSAnnotation.get(name: String): Any? = arguments.first { it.name?.asString() == name }.value +} diff --git a/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors b/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors new file mode 100644 index 0000000..13c2ec4 --- /dev/null +++ b/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors @@ -0,0 +1 @@ +com.modularmc.registrate.localization.processor.TranslationProcessor,aggregating diff --git a/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider b/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider new file mode 100644 index 0000000..273c3e1 --- /dev/null +++ b/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider @@ -0,0 +1 @@ +com.modularmc.registrate.localization.processor.ksp.LocalizationSymbolProcessorProvider diff --git a/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor new file mode 100644 index 0000000..14f4a6f --- /dev/null +++ b/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor @@ -0,0 +1 @@ +com.modularmc.registrate.localization.processor.TranslationProcessor diff --git a/lombok.config b/lombok.config deleted file mode 100644 index 14fae36..0000000 --- a/lombok.config +++ /dev/null @@ -1,16 +0,0 @@ -# this is the highest directory lombok should search for config files -config.stopBubbling = true - -# use jetbrains nullability annotations -lombok.addNullAnnotations = jetbrains - -# add annotations that @Getter and @Setter should copy from the field -lombok.copyableAnnotations += dev.latvian.mods.rhino.util.HideFromJS -# all the api status annotations -lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.Experimental -lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.Internal -lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.Obsolete -lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.ScheduledForRemoval -lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.AvailableSince -lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.NonExtendable -lombok.copyableAnnotations += org.jetbrains.annotations.ApiStatus.OverrideOnly diff --git a/settings.gradle b/settings.gradle index 5c1624c..89aae22 100644 --- a/settings.gradle +++ b/settings.gradle @@ -5,13 +5,10 @@ pluginManagement { maven { url = 'https://maven.neoforged.net/releases' } maven { url = "https://maven.quiltmc.org/repository/release" } } - plugins { - id 'org.jetbrains.kotlin.jvm' version '2.3.20' - } } plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' + id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' } dependencyResolutionManagement { @@ -26,3 +23,4 @@ dependencyResolutionManagement { } rootProject.name = "${mod_id}" +include 'localization-processor' diff --git a/src/main/java/com/modularmc/registrate/AbstractRegistrate.java b/src/main/java/com/modularmc/registrate/AbstractRegistrate.java deleted file mode 100644 index 3bece30..0000000 --- a/src/main/java/com/modularmc/registrate/AbstractRegistrate.java +++ /dev/null @@ -1,1322 +0,0 @@ -package com.modularmc.registrate; - -import com.modularmc.registrate.builders.*; -import com.modularmc.registrate.builders.BlockEntityBuilder.BlockEntityFactory; -import com.modularmc.registrate.builders.MenuBuilder.ForgeMenuFactory; -import com.modularmc.registrate.builders.MenuBuilder.MenuFactory; -import com.modularmc.registrate.builders.MenuBuilder.ScreenFactory; -import com.modularmc.registrate.builders.base.*; -import com.modularmc.registrate.internal.RegistrationTracker; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; -import com.modularmc.registrate.internal.lifecycle.RegistrateLifecycle; -import com.modularmc.registrate.internal.util.DebugMarkers; -import com.modularmc.registrate.internal.util.RegistrateLogger; -import com.modularmc.registrate.providers.*; -import com.modularmc.registrate.providers.core.*; -import com.modularmc.registrate.util.CreativeModeTabModifier; -import com.modularmc.registrate.util.entry.ItemEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.*; - -import net.minecraft.Util; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.MenuAccess; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType.EntityFactory; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.item.*; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.neoforged.bus.api.EventPriority; -import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.loading.FMLEnvironment; -import net.neoforged.neoforge.data.event.GatherDataEvent; -import net.neoforged.neoforge.data.loading.DatagenModLoader; -import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; -import net.neoforged.neoforge.fluids.BaseFlowingFluid; -import net.neoforged.neoforge.fluids.FluidType; -import net.neoforged.neoforge.registries.*; - -import com.google.common.collect.*; -import com.mojang.serialization.Codec; -import lombok.Getter; -import lombok.Setter; -import lombok.experimental.Accessors; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.message.Message; -import org.jspecify.annotations.Nullable; - -import java.util.*; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.UnaryOperator; - -/** - * Manages all registrations and data generators for a mod. - *

- * Generally not thread-safe, as it holds the current name of the object being built statefully, and uses - * non-concurrent collections. - *

- * Begin a new object via {@link #object(String)}. This name will be used for all future entries until the next - * invocation of {@link #object(String)}. Alternatively, the methods that accept a name - * parameter (such as {@link #block(String, NonNullFunction)}) can be used. These do not affect the current name state. - *

- * A simple use may look like: - * - *

- * {@code
- *
- * public static final Registrate REGISTRATE = Registrate.create("mymod");
- *
- * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
- *         .block(MyBlock::new)
- *         .defaultItem()
- *         .register();
- * }
- * 
- * - * For specifics as to building different registry entries, read the documentation on their respective builders. - */ -public abstract class AbstractRegistrate> { - - private static final Logger LOGGER = RegistrateLogger.core(); - private static final Logger DATAGEN_LOGGER = RegistrateLogger.datagen(); - - /** - * Checks if Minecraft is running from a dev environment. Enables certain debug logging. - * - * @return {@code true} when {@link FMLEnvironment#production} is false - */ - public static boolean isDevEnvironment() { - return !FMLEnvironment.production; - } - - private final class LifecycleHooks implements RegistrateLifecycle.Hooks { - - @Override - public @Nullable IEventBus modEventBus() { - return modEventBus; - } - - @Override - public void setModEventBus(IEventBus bus) { - modEventBus = bus; - } - - @Override - public boolean doDatagen() { - return doDatagen.get(); - } - - @Override - public void onRegister(RegisterEvent event) { - AbstractRegistrate.this.onRegister(event); - } - - @Override - public void onRegisterLate(RegisterEvent event) { - AbstractRegistrate.this.onRegisterLate(event); - } - - @Override - public void onBuildCreativeModeTabContents(BuildCreativeModeTabContentsEvent event) { - AbstractRegistrate.this.onBuildCreativeModeTabContents(event); - } - - @Override - public void onData(GatherDataEvent event) { - AbstractRegistrate.this.onData(event); - } - } - - private final RegistrationTracker registrationTracker; - private final RegistrateLifecycle lifecycle; - - private final Table>>, GeneratorType, Consumer> datagensByEntry = HashBasedTable.create(); - private final ListMultimap, NonNullConsumer> datagens = ArrayListMultimap.create(); - private final Multimap, Consumer> creativeModeTabModifiers = ArrayListMultimap.create(); - private ResourceKey defaultCreativeModeTab = CreativeModeTabs.SEARCH; - - @Accessors(fluent = true) - @Getter - private final NonNullSupplier doDatagen = NonNullSupplier.lazy(DatagenModLoader::isRunningDataGen); - - /** - * The mod ID that this {@link AbstractRegistrate} is creating objects for - */ - @Getter - private final String modid; - - /** - * Get the mod event bus that event listeners will be registered to. Useful when Registrate is used in mods that use - * alternative language loaders, such as forgelin. - */ - @Getter - @Setter - private @Nullable IEventBus modEventBus; - - private @Nullable String currentName; - private boolean skipErrors; - - /** - * Construct a new Registrate for the given mod ID. - * - * @param modid - * The mod ID for which objects will be registered - */ - protected AbstractRegistrate(String modid) { - this.modid = modid; - this.registrationTracker = new RegistrationTracker(modid); - this.lifecycle = new RegistrateLifecycle(this, new LifecycleHooks()); - } - - /** - * Use this in custom implementations to hide unsafe casts to {@link S} when returning self. - * - * @return This {@link AbstractRegistrate} object, cast to {@link S} - */ - @SuppressWarnings("unchecked") - protected final S self() { - return (S) this; - } - - /** - * Called during {@link Registrate#create(String) creation} to initialize event listeners. Custom implementations - * may add their own event listeners by overriding this. - *

- * Always call {@code super} in your override unless you know what you are doing! - * - * @param bus - * The event bus - * @return This {@link AbstractRegistrate} object - */ - public S registerEventListeners(IEventBus bus) { - lifecycle.register(bus); - return self(); - } - - /** - * Called once per registry to gather collected registrations and add entries to the registry. May be overriden in - * custom implementations to perform additional actions upon entry registration, but - * must call {@code super}. - * - * @param event - * The {@link RegisterEvent} being fired, use {@link RegisterEvent#getRegistryKey()} to query the - * registry type - */ - protected void onRegister(RegisterEvent event) { - registrationTracker.onRegister(event, skipErrors, isDevEnvironment()); - } - - /** - * Called once per registry at the {@link EventPriority#LOWEST lowest priority} to perform any actions that must - * happen after all other entries have been registered, including from other mods. May - * be overriden in custom implementations to perform additional actions upon entry registration, but must - * call {@code super}. - * - * @param event - * The {@link RegisterEvent} being fired, use {@link RegisterEvent#getRegistryKey()} to query the - * registry type - */ - protected void onRegisterLate(RegisterEvent event) { - registrationTracker.onRegisterLate(event); - } - - /** - * Called when a {@link CreativeModeTab} is being populated to fill in any entries that belong there. Can be - * overriden in custom implementations. - * - * @param event - * The event - */ - protected void onBuildCreativeModeTabContents(BuildCreativeModeTabContentsEvent event) { - var modifier = new CreativeModeTabModifier(event::getFlags, event::hasPermissions, event::accept, event::getParameters); - - creativeModeTabModifiers.forEach((key, value) -> { - if (event.getTabKey().equals(key)) value.accept(modifier); - }); - } - - private @Nullable RegistrateDataProvider provider; - - /** - * Called when datagen begins to add our provider to the generator. Can be overriden in custom implementations. - * - * @param event - * The event - */ - protected void onData(GatherDataEvent event) { - event.getGenerator().addProvider(true, provider = new RegistrateDataProvider(this, modid, event)); - } - - /** - * Get the current name (from the last call to {@link #object(String)}), throwing an exception if it is not set. - * - * @return The current entry name - * @throws NullPointerException - * if {@link #currentName} is null - */ - protected String currentName() { - String name = currentName; - Objects.requireNonNull(name, "Current name not set"); - return name; - } - - /** - * Allows retrieval of a previously created entry, of the current name (from the last invocation of - * {@link #object(String)}. Useful to retrieve a different entry than the final state of your - * chain may produce, e.g. - * - *

-     * {@code
-     *
-     * public static final RegistryObject MY_BLOCK_ITEM = REGISTRATE.object("my_block")
-     *         .block(MyBlock::new)
-     *         .defaultItem()
-     *         .lang("My Special Block")
-     *         .build()
-     *         .get(Item.class);
-     * }
-     * 
- * - * @param - * The type of the registry for which to retrieve the entry - * @param - * The type of the entry to return - * @param type - * A {@link ResourceKey} for the registry - * @return A {@link RegistryEntry} which will supply the requested entry, if it exists - * @throws IllegalArgumentException - * if no such registration has been done - * @throws NullPointerException - * if current name has not been set via {@link #object(String)} - */ - public RegistryEntry get(ResourceKey> type) { - return this.get(currentName(), type); - } - - /** - * Allows retrieval of a previously created entry. Useful to retrieve arbitrary entries that may have been created - * as side-effects of earlier registrations. - * - *
-     * {@code
-     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
-     *         .block(MyBlock::new)
-     *             .defaultItem()
-     *             .register();
-     *
-     * ...
-     *
-     * public static final RegistryObject MY_BLOCK_ITEM = REGISTRATE.get("my_block", ForgeRegistries.ITEMS.getRegistryKey());
-     * }
-     * 
- * - * @param - * The type of the registry for which to retrieve the entry - * @param - * The type of the entry to return - * @param name - * The name of the registry entry to request - * @param type - * A {@link ResourceKey} for the registry - * @return A {@link RegistryEntry} which will supply the requested entry, if it exists - * @throws IllegalArgumentException - * if no such registration has been done - */ - public RegistryEntry get(String name, ResourceKey> type) { - return registrationTracker.get(name, type); - } - - /** - * Allows retrieval of a previously created entry that may or may not exist. Possibly useful in some very specific - * scenarios, internally used during fluid registration. - * - * @param - * The type of the registry for which to retrieve the entry - * @param - * The type of the entry to return - * @param name - * The name of the registry entry to request - * @param type - * A class representing the registry type - * @return A {@link RegistryEntry} which will supply the requested entry, if it exists - */ - public Optional> getOptional(String name, ResourceKey> type) { - return registrationTracker.getOptional(name, type); - } - - /** - * Gather a collection of all entries registered for a certain registry - *

- * Note that this can be called before registration is complete, but the {@link RegistryEntry entries} will be empty - * at that time. - * - * @param - * Registry type - * @param type - * A {@link ResourceKey} for the registry in question - * @return A collection of {@link RegistryEntry} objects representing all entries in the given registry which are - * known to this {@link AbstractRegistrate} object. - */ - @SuppressWarnings({ "null", "unchecked" }) - public Collection> getAll(ResourceKey> type) { - return registrationTracker.getAll(type); - } - - /** - * Add a callback to be invoked when a certain entry has been registered. This will be invoked immediately - * following registration, before further entries are registered. - * - * @param - * Registry type - * @param - * Entry type - * @param name - * The name of the entry to watch (implicitly within the {@link #getModid() modid} of this - * instance - * @param registryType - * A {@link ResourceKey} for the registry in question - * @param callback - * The callback to invoke, which will be passed the created entry object - * @return This {@link AbstractRegistrate} instance - */ - public S addRegisterCallback(String name, ResourceKey> registryType, NonNullConsumer callback) { - registrationTracker.addRegisterCallback(name, registryType, callback); - return self(); - } - - /** - * Add a callback to be invoked when a certain registry has fully completed registration, i.e. all objects of that - * type have been registered. - * - * @param - * The registry type - * @param registryType - * A {@link ResourceKey} for the registry in question - * @param callback - * The callback to invoke - * @return This {@link AbstractRegistrate} instance - */ - public S addRegisterCallback(ResourceKey> registryType, Runnable callback) { - registrationTracker.addAfterRegisterCallback(registryType, callback); - return self(); - } - - /** - * Check if a certain registry has completed registration. - * - * @param - * The registry type - * @param registryType - * A {@link ResourceKey} for the registry in question - * @return {@code true} iff the given registry has finished the registration step - */ - public boolean isRegistered(ResourceKey> registryType) { - return registrationTracker.isRegistered(registryType); - } - - /** - * Get the data provider instance for a given {@link GeneratorType}. Only works within datagen context, not during - * registration or init. - * - * @param

- * The type of the provider - * @param type - * A {@link GeneratorType} representing the desired provider - * @return An {@link Optional} holding the provider, or empty if this provider was not registered. This can happen - * if datagen is run only for client or server providers. - * @throws IllegalStateException - * if datagen has not started yet - */ - public

Optional

getDataProvider(GeneratorType

type) { - RegistrateDataProvider provider = this.provider; - if (provider != null) { - return provider.getSubProvider(type); - } - throw new IllegalStateException("Cannot get data provider before datagen is started"); - } - - /** - * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data - * gen callback if it exists. - * - * @param

- * The type of provider - * @param - * The registry type - * @param builder - * The builder for the entry - * @param type - * The {@link GeneratorType} to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this {@link AbstractRegistrate} - */ - public S setDataGenerator(Builder builder, GeneratorType type, NonNullConsumer cons) { - return this.setDataGenerator(builder.getName(), builder.getRegistryKey(), type, cons); - } - - /** - * Mostly internal, removes the data generator for a certain entry/type combination if one was previously - * registered. - * - * @param

- * The type of provider - * @param - * The registry type - * @param builder - * The builder for the entry - * @param type - * The {@link GeneratorType} to stop generating data for - * @return this {@link AbstractRegistrate} - */ - public S removeDataGenerator(Builder builder, GeneratorType type) { - return this.removeDataGenerator(builder.getName(), builder.getRegistryKey(), type); - } - - /** - * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data - * gen callback if it exists. - * - * @param

- * The type of provider - * @param - * The registry type - * @param entry - * The name of the entry which the provider is for - * @param registryType - * A {@link Class} representing the registry type of the entry - * @param type - * The {@link GeneratorType} to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this {@link AbstractRegistrate} - */ - public S setDataGenerator(String entry, ResourceKey> registryType, GeneratorType type, NonNullConsumer cons) { - if (!doDatagen.get()) return self(); - @SuppressWarnings("null") - Consumer existing = datagensByEntry.put(Pair.of(entry, registryType), type, cons); - if (existing != null) { - datagens.remove(type, existing); - } - return addDataGenerator(type, cons); - } - - /** - * Mostly internal, removes the data generator for a certain entry/type combination if one was previously - * registered. - * - * @param

- * The type of provider - * @param - * The registry type - * @param entry - * The name of the entry which the provider is for - * @param registryType - * The registry type of the entry - * @param type - * The {@link GeneratorType} to stop generating data for - * @return this {@link AbstractRegistrate} - */ - public S removeDataGenerator(String entry, ResourceKey> registryType, GeneratorType type) { - if (!doDatagen.get()) return self(); - @SuppressWarnings("null") - Consumer existing = datagensByEntry.remove(Pair.of(entry, registryType), type); - if (existing != null) { - datagens.remove(type, existing); - } - return self(); - } - - /** - * Add a data generator callback that is not associated with any entry, which can never replace an existing data - * generator. - *

- * This is useful to add data generator callbacks for miscellaneous data not strictly associated with an entry. - * - * @param - * The type of provider - * @param type - * The {@link GeneratorType} to generate data for - * @param cons - * A callback to be invoked during data generation - * @return this {@link AbstractRegistrate} - */ - public S addDataGenerator(GeneratorType type, NonNullConsumer cons) { - if (doDatagen.get()) { - if (provider != null) throw new IllegalStateException("Cannot add data generator after construction of root generator"); - datagens.put(type, cons); - } - return self(); - } - - private @Nullable DataProviderInitializer initializer; - - /** - * Access datapack registry and data provider dependency settings - */ - public DataProviderInitializer getDataGenInitializer() { - if (initializer == null) { - initializer = new DataProviderInitializer(); - } - return initializer; - } - - private final NonNullSupplier>> extraLang = NonNullSupplier.lazy(() -> { - final List> ret = new ArrayList<>(); - addDataGenerator(ProviderType.LANG, prov -> ret.forEach(p -> prov.add(p.getKey(), p.getValue()))); - return ret; - }); - - /** - * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. - * - * @param type - * Type of the object, this is used as a prefix (e.g. - * {@code ["block", "mymod:myblock"] -> "block.mymod.myblock"}) - * @param id - * ID of the object, which will be converted to a lang key via - * {@link Util#makeDescriptionId(String, ResourceLocation)} - * @param localizedName - * (English) translation value - * @return A {@link MutableComponent} representing the translated text - */ - public MutableComponent addLang(String type, ResourceLocation id, String localizedName) { - return addRawLang(Util.makeDescriptionId(type, id), localizedName); - } - - /** - * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. - * Also - * appends a suffix to the key. - * - * @param type - * Type of the object, this is used as a prefix (e.g. - * {@code ["block", "mymod:myblock"] -> "block.mymod.myblock"}) - * @param id - * ID of the object, which will be converted to a lang key via - * {@link Util#makeDescriptionId(String, ResourceLocation)} - * @param suffix - * A suffix which will be appended to the generated key (separated by a dot) - * @param localizedName - * (English) translation value - * @return A {@link MutableComponent} representing the translated text - */ - public MutableComponent addLang(String type, ResourceLocation id, String suffix, String localizedName) { - return addRawLang(Util.makeDescriptionId(type, id) + "." + suffix, localizedName); - } - - /** - * Add a custom translation mapping directly to the lang provider. - * - * @param key - * The translation key - * @param value - * The (English) translation value - * @return A {@link MutableComponent} representing the translated text - */ - public MutableComponent addRawLang(String key, String value) { - if (doDatagen.get()) { - extraLang.get().add(Pair.of(key, value)); - } - return Component.translatable(key); - } - - @SuppressWarnings("null") - private Optional>>> getEntryForGenerator(GeneratorType type, NonNullConsumer generator) { - for (Map.Entry>>, Consumer> e : datagensByEntry.column(type).entrySet()) { - if (e.getValue() == generator) { - return Optional.of(e.getKey()); - } - } - return Optional.empty(); - } - - /** - * For internal use, calls upon registered data generators to actually create their data. - * - * @param - * The type of the provider - * @param type - * The type of provider to run - * @param gen - * The provider - */ - @SuppressWarnings("unchecked") - public void genData(GeneratorType type, T gen) { - if (!doDatagen.get()) return; - if (provider != null) { - provider.putSubProvider(type, gen); - } - datagens.get(type).forEach(cons -> { - Optional>>> entry = Optional.empty(); - if (DATAGEN_LOGGER.isEnabled(Level.DEBUG, DebugMarkers.DATA)) { - entry = getEntryForGenerator(type, cons); - if (entry.isPresent()) { - DATAGEN_LOGGER.debug( - DebugMarkers.DATA, - RegistrateLogger.modMessage("Generating data of type {} for entry {} [{}]"), - modid, - RegistrateDataProvider.getTypeName(type), - entry.get().getLeft(), - entry.get().getRight().location()); - } else { - DATAGEN_LOGGER.debug( - DebugMarkers.DATA, - RegistrateLogger.modMessage("Generating unassociated data of type {} ({})"), - modid, - RegistrateDataProvider.getTypeName(type), - type); - } - } - try { - ((Consumer) cons).accept(gen); - } catch (Exception e) { - if (entry.isEmpty()) { - entry = getEntryForGenerator(type, cons); - } - Message err; - if (entry.isPresent()) { - err = DATAGEN_LOGGER.getMessageFactory().newMessage( - RegistrateLogger.modMessage("Unexpected error while running data generator of type {} for entry {} [{}]"), - modid, - RegistrateDataProvider.getTypeName(type), - entry.get().getLeft(), - entry.get().getRight().location()); - } else { - err = DATAGEN_LOGGER.getMessageFactory().newMessage( - RegistrateLogger.modMessage("Unexpected error while running unassociated data generator of type {} ({})"), - modid, - RegistrateDataProvider.getTypeName(type), - type); - } - if (skipErrors) { - DATAGEN_LOGGER.error(err); - } else { - throw new RuntimeException(err.getFormattedMessage(), e); - } - } - }); - } - - /** - * Enable skipping of registry entries and data generators that error during registration/generation. - *

- * Should only be used for debugging! {@code skipErrors(true)} will do nothing outside of a dev - * environment. - * - * @param skipErrors - * {@code true} to skip errors during registration/generation - * @return this {@link AbstractRegistrate} - */ - public S skipErrors(boolean skipErrors) { - if (skipErrors && !isDevEnvironment()) { - LOGGER.warn( - RegistrateLogger.modMessage("Ignoring skipErrors(true) because the runtime is not a development environment"), - modid); - } else { - this.skipErrors = skipErrors; - } - return self(); - } - - /** - * Begin a new object, this is typically used at the beginning of a builder chain. The given name will be used until - * this method is called again. This makes it simple to create multiple entries - * with the same name, as is often the case with blocks/items, items/entities, and blocks/TEs. - * - * @param name - * The name to use for future entries - * @return this {@link AbstractRegistrate} - */ - public S object(String name) { - this.currentName = name; - return self(); - } - - /** - * Set the default CreativeModeTab to be passed onto future builders. - *

- * This special case method should be used if your creative tab instance was not created by Registrate, otherwise - * use {@link #defaultCreativeTab()}. - * - * @param creativeModeTab - * The new default CreativeModeTab type - * @return This {@link AbstractRegistrate} instance - */ - public S defaultCreativeTab(ResourceKey creativeModeTab) { - defaultCreativeModeTab = creativeModeTab; - return self(); - } - - /** - * Registers a new modifier callback to be used to modify the given CreativeModeTab. - * - *

- * Registers a new callback to be invoked during the {@link BuildCreativeModeTabContentsEvent} event and - * used to modify what items are displayed on the given {@link CreativeModeTab}. - *

- * Calling this method multiple times will add additional callbacks. - * - * @param creativeModeTab The {@link CreativeModeTab} to register this callback for - * @param modifier The modifier callback to be registered - * @return This {@link AbstractRegistrate} instance - */ - public S modifyCreativeModeTab(ResourceKey creativeModeTab, Consumer modifier) { - creativeModeTabModifiers.put(creativeModeTab, modifier); - return self(); - } - - /** - * Apply a transformation to this {@link AbstractRegistrate}. Useful to apply helper methods within a fluent chain, - * e.g. - * - *

-     * {@code
-     *
-     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
-     *         .transform(Utils::createMyBlock)
-     *         .get(Block.class);
-     * }
-     * 
- * - * @param func - * The {@link UnaryOperator function} to apply - * @return this {@link AbstractRegistrate} - */ - public S transform(NonNullUnaryOperator func) { - return func.apply(self()); - } - - /** - * Apply a transformation to this {@link AbstractRegistrate}. Similar to {@link #transform(NonNullUnaryOperator)}, - * but for actions that return a builder in-progress. Useful to apply helper methods - * within a fluent chain, e.g. - * - *
-     * {@code
-     *
-     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
-     *         .transform(Utils::createMyBlock)
-     *         .lang("My Block") // Can modify the builder afterwards
-     *         .register();
-     * }
-     * 
- * - * @param - * Registry type - * @param - * Entry type - * @param

- * Parent type - * @param - * Self type - * @param func - * The {@link Function function} to apply - * @return the resultant {@link Builder} - */ - public > S2 transform(NonNullFunction func) { - return func.apply(self()); - } - - /** - * Create a builder for a new entry. This is typically not needed, unless you are implementing a - * custom builder type. - *

- * Uses the currently set name (via {@link #object(String)}) as the name for the new entry, and passes it to the - * factory as the first parameter. - * - * @param - * Registry type - * @param - * Entry type - * @param

- * Parent type - * @param - * Self type - * @param factory - * The factory to create the builder - * @return The {@link Builder} instance - */ - public > S2 entry(NonNullBiFunction factory) { - return entry(currentName(), callback -> factory.apply(currentName(), callback)); - } - - /** - * Create a builder for a new entry. This is typically not needed, unless you are implementing a - * custom builder type. - * - * @param - * Registry type - * @param - * Entry type - * @param

- * Parent type - * @param - * Self type - * @param name - * The name to use for the entry - * @param factory - * The factory to create the builder - * @return The {@link Builder} instance - */ - public > S2 entry(String name, NonNullFunction factory) { - return factory.apply(this::accept); - } - - /** - * Factory method to accept a completed builder and add it to the registration queue. - *

- * Satisfies the functional interface {@link BuilderCallback}, which is typically given to new builder instances - * when they are constructed. - * - * @param - * Registry type - * @param - * Entry type - * @param name - * Thename of the entry being created - * @param type - * The registry to add the entry to - * @param builder - * The builder instance that was used to create this entry. Not used by default implementation, - * but custom extensions may use it for some purpose - * @param creator - * Constructor for the new entry object - * @param entryFactory - * Optional custom factory to create special {@link RegistryEntry} types - * @return A {@link RegistryEntry} that will hold the created entry after registration is complete - */ - protected RegistryEntry accept(String name, ResourceKey> type, Builder builder, NonNullSupplier creator, NonNullFunction, ? extends RegistryEntry> entryFactory) { - return registrationTracker.track(name, type, creator, entryFactory); - } - - /** - * Helper to create a new registry for custom objects. The returned {@link ResourceKey} can be used immediately in - * methods like {@link #simple(ResourceKey, NonNullSupplier) simple} or - * {@link #generic(ResourceKey, NonNullSupplier) generic}. - *

- * Alternatively, a custom {@link Builder builder} can be created. - *

- * This method will automatically subscribe to the {@link NewRegistryEvent} and create the registry at the proper - * time. Thus, the new registry will not exist immediately after this is called. - * - * @param - * The type of object the new registry will contain - * @param name - * The ID of this registry - * @param builder - * A function to create the {@link RegistryBuilder} that defines the other properties/behaviors of - * the created registry - * @return A {@link ResourceKey resource key} referencing the to-be-created registry. - */ - public ResourceKey> makeRegistry(String name, Function>, RegistryBuilder> builder) { - final ResourceKey> registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(getModid(), name)); - OneTimeEventReceiver.addModListener(this, NewRegistryEvent.class, e -> e.register(builder.apply(registryId).create())); - return registryId; - } - - /** - * Registers the given registry key as an unsynced datapack registry, which will cause data to be loaded from - * a datapack folder based on the registry's name. The datapack registry is not required to be present - * on clients when connecting to servers with the mod/registry. - *

- * Data JSONs will be loaded from {@code data//modid/registryname/}, where {@code modid} is the - * namespace of the registry key. - * - * @param name The ID of this registry - * @param codec The codec to be used for loading data from datapacks on servers - * @see #makeDatapackRegistry(String, Codec, Codec) - */ - public ResourceKey> makeDatapackRegistry(String name, Codec codec) { - return makeDatapackRegistry(name, codec, null); - } - - /** - * Registers the registry key as a datapack registry, which will cause data to be loaded from - * a datapack folder based on the registry's name. - *

- * Data JSONs will be loaded from {@code data//modid/registryname/}, where {@code modid} is the - * namespace of the registry key. - * - * @param name The ID of this registry - * @param codec The codec to be used for loading data from datapacks on servers - * @param networkCodec The codec to be used for syncing loaded data to clients. - * If {@code networkCodec} is null, data will not be synced, and clients are not required to - * have this - * datapack registry to join a server. - *

- * If {@code networkCodec} is not null, clients must have this datapack registry/mod - * when joining a server that has this datapack registry/mod. - * The data will be synced using the network codec and accessible via - * {@link ClientPacketListener#registryAccess()}. - * @see #makeDatapackRegistry(String, Codec) - */ - public ResourceKey> makeDatapackRegistry(String name, Codec codec, @Nullable Codec networkCodec) { - final ResourceKey> registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(getModid(), name)); - OneTimeEventReceiver.addModListener(this, DataPackRegistryEvent.NewRegistry.class, event -> event.dataPackRegistry(registryId, codec, networkCodec)); - return registryId; - } - - /* === Builder helpers === */ - - // Generic - - public RegistryEntry simple(ResourceKey> registryType, NonNullSupplier factory) { - return simple(currentName(), registryType, factory); - } - - public RegistryEntry simple(String name, ResourceKey> registryType, NonNullSupplier factory) { - return simple(this, name, registryType, factory); - } - - public RegistryEntry simple(P parent, ResourceKey> registryType, NonNullSupplier factory) { - return simple(parent, currentName(), registryType, factory); - } - - public RegistryEntry simple(P parent, String name, ResourceKey> registryType, NonNullSupplier factory) { - return generic(parent, name, registryType, factory).register(); - } - - public NoConfigBuilder generic(ResourceKey> registryType, NonNullSupplier factory) { - return generic(self(), registryType, factory); - } - - public NoConfigBuilder generic(String name, ResourceKey> registryType, NonNullSupplier factory) { - return generic(self(), name, registryType, factory); - } - - public NoConfigBuilder generic(P parent, ResourceKey> registryType, NonNullSupplier factory) { - return generic(parent, currentName(), registryType, factory); - } - - public NoConfigBuilder generic(P parent, String name, ResourceKey> registryType, NonNullSupplier factory) { - return entry(name, callback -> new NoConfigBuilder<>(this, parent, name, callback, registryType, factory)); - } - - // Items - - public ItemBuilder item(NonNullFunction factory) { - return item(self(), factory); - } - - public ItemBuilder item(String name, NonNullFunction factory) { - return item(self(), name, factory); - } - - public ItemBuilder item(P parent, NonNullFunction factory) { - return item(parent, currentName(), factory); - } - - public ItemBuilder item(P parent, String name, NonNullFunction factory) { - return entry(name, callback -> ItemBuilder.create(this, parent, name, callback, factory) - .transform(builder -> this.defaultCreativeModeTab == null ? builder : builder.tab(this.defaultCreativeModeTab))); - } - - // Blocks - - public BlockBuilder block(NonNullFunction factory) { - return block(self(), factory); - } - - public BlockBuilder block(String name, NonNullFunction factory) { - return block(self(), name, factory); - } - - public BlockBuilder block(P parent, NonNullFunction factory) { - return block(parent, currentName(), factory); - } - - public BlockBuilder block(P parent, String name, NonNullFunction factory) { - return entry(name, callback -> BlockBuilder.create(this, parent, name, callback, factory)); - } - - // Entities - - public EntityBuilder entity(EntityFactory factory, MobCategory classification) { - return entity(self(), factory, classification); - } - - public EntityBuilder entity(String name, EntityFactory factory, MobCategory classification) { - return entity(self(), name, factory, classification); - } - - public EntityBuilder entity(P parent, EntityFactory factory, MobCategory classification) { - return entity(parent, currentName(), factory, classification); - } - - public EntityBuilder entity(P parent, String name, EntityFactory factory, MobCategory classification) { - return entry(name, callback -> EntityBuilder.create(this, parent, name, callback, factory, classification)); - } - - // Block Entities - - public BlockEntityBuilder blockEntity(BlockEntityFactory factory) { - return blockEntity(self(), factory); - } - - public BlockEntityBuilder blockEntity(String name, BlockEntityFactory factory) { - return blockEntity(self(), name, factory); - } - - public BlockEntityBuilder blockEntity(P parent, BlockEntityFactory factory) { - return blockEntity(parent, currentName(), factory); - } - - public BlockEntityBuilder blockEntity(P parent, String name, BlockEntityFactory factory) { - return entry(name, callback -> BlockEntityBuilder.create(this, parent, name, callback, factory)); - } - - // Fluids - - public FluidBuilder fluid() { - return fluid(self()); - } - - public FluidBuilder fluid(FluidBuilder.FluidTypeFactory typeFactory) { - return fluid(self(), typeFactory); - } - - public FluidBuilder fluid(NonNullSupplier fluidType) { - return fluid(self(), fluidType); - } - - public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture) { - return fluid(self(), stillTexture, flowingTexture); - } - - public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { - return fluid(self(), stillTexture, flowingTexture, typeFactory); - } - - public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { - return fluid(self(), stillTexture, flowingTexture, fluidType); - } - - public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidFactory fluidFactory) { - return fluid(self(), stillTexture, flowingTexture, fluidFactory); - } - - public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { - return fluid(self(), stillTexture, flowingTexture, typeFactory, fluidFactory); - } - - public FluidBuilder fluid(ResourceLocation stillTexture, ResourceLocation flowingTexture, - NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { - return fluid(self(), stillTexture, flowingTexture, fluidType, fluidFactory); - } - - public FluidBuilder fluid(String name) { - return fluid(self(), name); - } - - public FluidBuilder fluid(String name, FluidBuilder.FluidTypeFactory typeFactory) { - return fluid(self(), name, typeFactory); - } - - public FluidBuilder fluid(String name, NonNullSupplier fluidType) { - return fluid(self(), name, fluidType); - } - - public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture) { - return fluid(self(), name, stillTexture, flowingTexture); - } - - public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { - return fluid(self(), name, stillTexture, flowingTexture, typeFactory); - } - - public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { - return fluid(self(), name, stillTexture, flowingTexture, fluidType); - } - - public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidFactory fluidFactory) { - return fluid(self(), name, stillTexture, flowingTexture, fluidFactory); - } - - public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { - return fluid(self(), name, stillTexture, flowingTexture, typeFactory, fluidFactory); - } - - public FluidBuilder fluid(String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, - NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { - return fluid(self(), name, stillTexture, flowingTexture, fluidType, fluidFactory); - } - - public

FluidBuilder fluid(P parent) { - return fluid(parent, currentName()); - } - - public

FluidBuilder fluid(P parent, FluidBuilder.FluidTypeFactory typeFactory) { - return fluid(parent, currentName(), typeFactory); - } - - public

FluidBuilder fluid(P parent, NonNullSupplier fluidType) { - return fluid(parent, currentName(), fluidType); - } - - public

FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture) { - return fluid(parent, currentName(), stillTexture, flowingTexture); - } - - public

FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { - return fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory); - } - - public

FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { - return fluid(parent, currentName(), stillTexture, flowingTexture, fluidType); - } - - public FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidFactory fluidFactory) { - return fluid(parent, currentName(), stillTexture, flowingTexture, fluidFactory); - } - - public FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { - return fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory, fluidFactory); - } - - public FluidBuilder fluid(P parent, ResourceLocation stillTexture, ResourceLocation flowingTexture, - NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { - return fluid(parent, currentName(), stillTexture, flowingTexture, fluidType, fluidFactory); - } - - public

FluidBuilder fluid(P parent, String name) { - return fluid(parent, name, defaultStillTexture(), defaultFlowingTexture()); - } - - public

FluidBuilder fluid(P parent, String name, FluidBuilder.FluidTypeFactory typeFactory) { - return fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), typeFactory); - } - - public

FluidBuilder fluid(P parent, String name, NonNullSupplier fluidType) { - return fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), fluidType); - } - - private ResourceLocation defaultStillTexture() { - return ResourceLocation.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_still"); - } - - private ResourceLocation defaultFlowingTexture() { - return ResourceLocation.fromNamespaceAndPath(getModid(), "block/" + currentName() + "_flow"); - } - - public

FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture) { - return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, FluidType::new)).model(stillTexture, flowingTexture); - } - - public

FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, FluidBuilder.FluidTypeFactory typeFactory) { - return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, typeFactory)).model(stillTexture, flowingTexture); - } - - public

FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, NonNullSupplier fluidType) { - return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidType)).model(stillTexture, flowingTexture); - } - - public FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidFactory fluidFactory) { - return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidFactory)).model(stillTexture, flowingTexture); - } - - public FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, - FluidBuilder.FluidTypeFactory typeFactory, FluidBuilder.FluidFactory fluidFactory) { - return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, typeFactory, fluidFactory)).model(stillTexture, flowingTexture); - } - - public FluidBuilder fluid(P parent, String name, ResourceLocation stillTexture, ResourceLocation flowingTexture, - NonNullSupplier fluidType, FluidBuilder.FluidFactory fluidFactory) { - return entry(name, callback -> FluidBuilder.create(this, parent, name, callback, fluidType, fluidFactory)).model(stillTexture, flowingTexture); - } - - // Menu - - public > MenuBuilder menu(MenuFactory factory, NonNullSupplier> screenFactory) { - return menu(currentName(), factory, screenFactory); - } - - public > MenuBuilder menu(String name, MenuFactory factory, NonNullSupplier> screenFactory) { - return menu(self(), name, factory, screenFactory); - } - - public , P> MenuBuilder menu(P parent, MenuFactory factory, NonNullSupplier> screenFactory) { - return menu(parent, currentName(), factory, screenFactory); - } - - public , P> MenuBuilder menu(P parent, String name, MenuFactory factory, NonNullSupplier> screenFactory) { - return entry(name, callback -> new MenuBuilder<>(this, parent, name, callback, factory, screenFactory)); - } - - public > MenuBuilder menu(ForgeMenuFactory factory, NonNullSupplier> screenFactory) { - return menu(currentName(), factory, screenFactory); - } - - public > MenuBuilder menu(String name, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { - return menu(self(), name, factory, screenFactory); - } - - public , P> MenuBuilder menu(P parent, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { - return menu(parent, currentName(), factory, screenFactory); - } - - public , P> MenuBuilder menu(P parent, String name, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { - return entry(name, callback -> new MenuBuilder<>(this, parent, name, callback, factory, screenFactory)); - } - - // Creative Tab - - public NoConfigBuilder defaultCreativeTab() { - return defaultCreativeTab(self()); - } - - public NoConfigBuilder defaultCreativeTab(String name) { - return defaultCreativeTab(self(), name); - } - - public

NoConfigBuilder defaultCreativeTab(P parent) { - return defaultCreativeTab(parent, currentName()); - } - - public

NoConfigBuilder defaultCreativeTab(P parent, String name) { - return defaultCreativeTab(parent, name, tab -> {}); - } - - public NoConfigBuilder defaultCreativeTab(Consumer config) { - return defaultCreativeTab(self(), config); - } - - public NoConfigBuilder defaultCreativeTab(String name, Consumer config) { - return defaultCreativeTab(self(), name, config); - } - - public

NoConfigBuilder defaultCreativeTab(P parent, Consumer config) { - return defaultCreativeTab(parent, currentName(), config); - } - - public

NoConfigBuilder defaultCreativeTab(P parent, String name, Consumer config) { - this.defaultCreativeModeTab = ResourceKey.create(Registries.CREATIVE_MODE_TAB, ResourceLocation.fromNamespaceAndPath(this.modid, name)); - return this.generic(parent, name, Registries.CREATIVE_MODE_TAB, () -> { - var builder = CreativeModeTab.builder() - .icon(() -> getAll(Registries.ITEM).stream().findFirst().map(ItemEntry::cast).map(ItemEntry::asStack).orElse(new ItemStack(Items.AIR))) - .title(this.addLang("itemGroup", this.defaultCreativeModeTab.location(), RegistrateLangProvider.toEnglishName(name))); - config.accept(builder); - return builder.build(); - }); - } -} diff --git a/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt new file mode 100644 index 0000000..432c134 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt @@ -0,0 +1,1405 @@ +// KtLint folds forwarding overloads across the configured line limit during formatting. +@file:Suppress("ktlint:standard:max-line-length") + +package com.modularmc.registrate + +import com.modularmc.registrate.builders.BlockBuilder +import com.modularmc.registrate.builders.BlockEntityBuilder +import com.modularmc.registrate.builders.BlockEntityBuilder.BlockEntityFactory +import com.modularmc.registrate.builders.EntityBuilder +import com.modularmc.registrate.builders.FluidBuilder +import com.modularmc.registrate.builders.FluidBuilder.FluidFactory +import com.modularmc.registrate.builders.FluidBuilder.FluidTypeFactory +import com.modularmc.registrate.builders.ItemBuilder +import com.modularmc.registrate.builders.MenuBuilder +import com.modularmc.registrate.builders.MenuBuilder.ForgeMenuFactory +import com.modularmc.registrate.builders.MenuBuilder.MenuFactory +import com.modularmc.registrate.builders.MenuBuilder.ScreenFactory +import com.modularmc.registrate.builders.base.AbstractBuilder +import com.modularmc.registrate.builders.base.Builder +import com.modularmc.registrate.builders.base.BuilderCallback +import com.modularmc.registrate.builders.base.NoConfigBuilder +import com.modularmc.registrate.internal.RegistrationTracker +import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener +import com.modularmc.registrate.internal.lifecycle.RegistrateLifecycle +import com.modularmc.registrate.internal.util.DebugMarkers +import com.modularmc.registrate.internal.util.RegistrateLogger.core +import com.modularmc.registrate.internal.util.RegistrateLogger.datagen +import com.modularmc.registrate.internal.util.RegistrateLogger.modMessage +import com.modularmc.registrate.localization.EntryLocalization +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.LocalizationDeclaration.Companion.sourceText +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.resolution.TranslationRegistry +import com.modularmc.registrate.localization.terminology.LocalizationCatalog +import com.modularmc.registrate.providers.RegistrateLangProvider.Companion.toEnglishName +import com.modularmc.registrate.providers.core.DataProviderInitializer +import com.modularmc.registrate.providers.core.GeneratorType +import com.modularmc.registrate.providers.core.RegistrateDataProvider +import com.modularmc.registrate.providers.core.RegistrateDataProvider.Companion.getTypeName +import com.modularmc.registrate.util.CreativeModeTabModifier +import com.modularmc.registrate.util.entry.EntryMetadata +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.NonNullBiFunction +import com.modularmc.registrate.util.nullness.NonNullConsumer +import com.modularmc.registrate.util.nullness.NonNullFunction +import com.modularmc.registrate.util.nullness.NonNullSupplier +import com.modularmc.registrate.util.nullness.NonNullUnaryOperator + +import net.minecraft.Util +import net.minecraft.client.gui.screens.Screen +import net.minecraft.client.gui.screens.inventory.MenuAccess +import net.minecraft.core.Registry +import net.minecraft.core.registries.Registries +import net.minecraft.network.chat.Component +import net.minecraft.network.chat.MutableComponent +import net.minecraft.resources.ResourceKey +import net.minecraft.resources.ResourceLocation +import net.minecraft.world.entity.Entity +import net.minecraft.world.entity.EntityType +import net.minecraft.world.entity.EntityType.EntityFactory +import net.minecraft.world.entity.MobCategory +import net.minecraft.world.inventory.AbstractContainerMenu +import net.minecraft.world.inventory.MenuType +import net.minecraft.world.item.CreativeModeTab +import net.minecraft.world.item.CreativeModeTabs +import net.minecraft.world.item.Item +import net.minecraft.world.item.ItemStack +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.block.entity.BlockEntity +import net.minecraft.world.level.block.entity.BlockEntityType +import net.minecraft.world.level.block.state.BlockBehaviour +import net.minecraft.world.level.material.Fluid +import net.neoforged.bus.api.IEventBus +import net.neoforged.fml.loading.FMLEnvironment +import net.neoforged.neoforge.data.event.GatherDataEvent +import net.neoforged.neoforge.data.loading.DatagenModLoader +import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent +import net.neoforged.neoforge.fluids.BaseFlowingFluid +import net.neoforged.neoforge.fluids.BaseFlowingFluid.Flowing +import net.neoforged.neoforge.fluids.FluidType +import net.neoforged.neoforge.registries.DataPackRegistryEvent.NewRegistry +import net.neoforged.neoforge.registries.DeferredHolder +import net.neoforged.neoforge.registries.NewRegistryEvent +import net.neoforged.neoforge.registries.RegisterEvent +import net.neoforged.neoforge.registries.RegistryBuilder + +import com.google.common.collect.ArrayListMultimap +import com.google.common.collect.HashBasedTable +import com.mojang.serialization.Codec +import org.apache.commons.lang3.tuple.Pair +import org.apache.logging.log4j.Level + +import java.util.Optional +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.function.BiConsumer +import java.util.function.BooleanSupplier +import java.util.function.Consumer +import java.util.function.Function +import java.util.function.Supplier + +/** + * Manages all registrations and data generators for a mod. + * + * Generally *not* thread-safe, as it holds the current name of the object being built statefully, and uses + * non-concurrent collections. + * + * Begin a new object via [object]. This name will be used for all future entries until the next + * invocation of [object]. Alternatively, the methods that accept a name + * parameter (such as [block]) can be used. These do not affect the current name state. + * + * A simple use may look like: + * + * ```java + * public static final Registrate REGISTRATE = Registrate.create("mymod"); + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * .block(MyBlock::new) + * .defaultItem() + * .register(); + * ``` + * + * For specifics as to building different registry entries, read the documentation on their respective builders. + */ +abstract class AbstractRegistrate> protected constructor( + /** + * The mod ID that this [AbstractRegistrate] is creating objects for + */ + val modid: String, +) { + private inner class LifecycleHooks : RegistrateLifecycle.Hooks { + override fun modEventBus(): IEventBus? = modEventBus + + override fun setModEventBus(bus: IEventBus) { + modEventBus = bus + } + + override fun doDatagen(): Boolean = dataGeneration.get() + + override fun onRegister(event: RegisterEvent) { + this@AbstractRegistrate.onRegister(event) + } + + override fun onRegisterLate(event: RegisterEvent) { + this@AbstractRegistrate.onRegisterLate(event) + } + + override fun onBuildCreativeModeTabContents(event: BuildCreativeModeTabContentsEvent) { + this@AbstractRegistrate.onBuildCreativeModeTabContents(event) + } + + override fun onData(event: GatherDataEvent) { + this@AbstractRegistrate.onData(event) + } + } + + private val callback = object : BuilderCallback { + override fun accept( + name: String, + type: ResourceKey>, + builder: Builder, + factory: NonNullSupplier, + entryFactory: NonNullFunction, out RegistryEntry>, + ): RegistryEntry = this@AbstractRegistrate.accept(name, type, builder, factory, entryFactory) + } + + private val registrationTracker = RegistrationTracker(modid) + private val lifecycle = RegistrateLifecycle(this, LifecycleHooks()) + + private val datagensByEntry = HashBasedTable.create>>, GeneratorType<*>, EntryMetadata.DataGenerator<*>>() + private val datagens = ArrayListMultimap.create, NonNullConsumer<*>>() + private val creativeModeTabModifiers = ArrayListMultimap.create, Consumer>() + private var defaultCreativeModeTab: ResourceKey = CreativeModeTabs.SEARCH + + private val dataGeneration = NonNullSupplier.lazy(DatagenModLoader::isRunningDataGen) + + open fun doDatagen(): NonNullSupplier = dataGeneration + + /** + * Get the mod event bus that event listeners will be registered to. Useful when Registrate is used in mods that use + * alternative language loaders, such as forgelin. + */ + + var modEventBus: IEventBus? = null + + private lateinit var currentName: String + private var skipErrors = false + + /** + * Use this in custom implementations to hide unsafe casts to [S] when returning self. + * + * @return This [AbstractRegistrate] object, cast to [S] + */ + @Suppress("UNCHECKED_CAST") + protected fun self(): S = this as S + + /** + * Called during [creation][Registrate.create] to initialize event listeners. Custom implementations + * may add their own event listeners by overriding this. + * + * *Always* call `super` in your override unless you know what you are doing! + * + * @param bus + * The event bus + * @return This [AbstractRegistrate] object + */ + open fun registerEventListeners(bus: IEventBus): S { + lifecycle.register(bus) + return self() + } + + /** + * Called once per registry to gather collected registrations and add entries to the registry. May be overriden in + * custom implementations to perform additional actions upon entry registration, but + * *must* call `super`. + * + * @param event + * The [RegisterEvent] being fired, use [RegisterEvent.getRegistryKey] to query the + * registry type + */ + protected open fun onRegister(event: RegisterEvent) { + registrationTracker.onRegister(event, skipErrors, isDevEnvironment) + } + + /** + * Called once per registry at the [lowest priority][net.neoforged.bus.api.EventPriority.LOWEST] to perform any actions that must + * happen after all other entries have been registered, including from other mods. May + * be overriden in custom implementations to perform additional actions upon entry registration, but *must* + * call `super`. + * + * @param event + * The [RegisterEvent] being fired, use [RegisterEvent.getRegistryKey] to query the + * registry type + */ + protected open fun onRegisterLate(event: RegisterEvent) { + registrationTracker.onRegisterLate(event) + } + + /** + * Called when a [CreativeModeTab] is being populated to fill in any entries that belong there. Can be + * overriden in custom implementations. + * + * @param event + * The event + */ + protected open fun onBuildCreativeModeTabContents(event: BuildCreativeModeTabContentsEvent) { + val modifier = CreativeModeTabModifier( + Supplier(event::getFlags), + BooleanSupplier(event::hasPermissions), + BiConsumer(event::accept), + Supplier(event::getParameters), + ) + + for (callback in creativeModeTabModifiers[event.tabKey]) { + callback.accept(modifier) + } + } + + private var provider: RegistrateDataProvider? = null + + /** + * Called when datagen begins to add our provider to the generator. Can be overriden in custom implementations. + * + * @param event + * The event + */ + protected open fun onData(event: GatherDataEvent) { + if (event.mods.contains(modid)) { + val dataProvider = RegistrateDataProvider(this, modid, event) + provider = dataProvider + dataProvider.attach(event) + } + } + + /** + * Get the current name (from the last call to [object]), throwing an exception if it is not set. + * + * @return The current entry name + + */ + protected open fun currentName(): String = currentName + + /** + * Allows retrieval of a previously created entry, of the current name (from the last invocation of + * [object]. Useful to retrieve a different entry than the final state of your + * chain may produce, e.g. + * + * ```java + * public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.object("my_block") + * .block(MyBlock::new) + * .defaultItem() + * .lang("My Special Block") + * .build() + * .get(Item.class); + * ``` + * + * @param R + * The type of the registry for which to retrieve the entry + * @param T + * The type of the entry to return + * @param type + * A [ResourceKey] for the registry + * @return A [RegistryEntry] which will supply the requested entry, if it exists + * @throws IllegalArgumentException + * if no such registration has been done + * @throws NullPointerException + * if current name has not been set via [object] + */ + open fun get(type: ResourceKey>) = this.get(currentName(), type) + + /** + * Allows retrieval of a previously created entry. Useful to retrieve arbitrary entries that may have been created + * as side-effects of earlier registrations. + * + * ```java + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * .block(MyBlock::new) + * .defaultItem() + * .register(); + * ... public static final RegistryEntry MY_BLOCK_ITEM = REGISTRATE.get("my_block", Registries.ITEM); + * ``` + * + * @param R + * The type of the registry for which to retrieve the entry + * @param T + * The type of the entry to return + * @param name + * The name of the registry entry to request + * @param type + * A [ResourceKey] for the registry + * @return A [RegistryEntry] which will supply the requested entry, if it exists + * @throws IllegalArgumentException + * if no such registration has been done + */ + open fun get(name: String, type: ResourceKey>) = registrationTracker.get(name, type) + + /** + * Allows retrieval of a previously created entry that may or may not exist. Possibly useful in some very specific + * scenarios, internally used during fluid registration. + * + * @param R + * The type of the registry for which to retrieve the entry + * @param T + * The type of the entry to return + * @param name + * The name of the registry entry to request + * @param type + * A class representing the registry type + * @return A [RegistryEntry] which will supply the requested entry, if it exists + */ + open fun getOptional(name: String, type: ResourceKey>) = registrationTracker.getOptional(name, type) + + /** + * Gather a collection of all entries registered for a certain registry + * + * Note that this can be called before registration is complete, but the [entries][RegistryEntry] will be empty + * at that time. + * + * @param R + * Registry type + * @param type + * A [ResourceKey] for the registry in question + * @return A collection of [RegistryEntry] objects representing all entries in the given registry which are + * known to this [AbstractRegistrate] object. + */ + open fun getAll(type: ResourceKey>) = registrationTracker.getAll(type) + + /** + * Add a callback to be invoked when a certain entry has been registered. This will be invoked *immediately* + * following registration, before further entries are registered. + * + * @param R + * Registry type + * @param T + * Entry type + * @param name + * The name of the entry to watch (implicitly within the [modid][modid] of this + * instance + * @param registryType + * A [ResourceKey] for the registry in question + * @param callback + * The callback to invoke, which will be passed the created entry object + * @return This [AbstractRegistrate] instance + */ + open fun addRegisterCallback(name: String, registryType: ResourceKey>, callback: NonNullConsumer): S { + registrationTracker.addRegisterCallback(name, registryType, callback) + return self() + } + + /** + * Add a callback to be invoked when a certain registry has fully completed registration, i.e. all objects of that + * type have been registered. + * + * @param R + * The registry type + * @param registryType + * A [ResourceKey] for the registry in question + * @param callback + * The callback to invoke + * @return This [AbstractRegistrate] instance + */ + open fun addRegisterCallback(registryType: ResourceKey>, callback: Runnable): S { + registrationTracker.addAfterRegisterCallback(registryType, callback) + return self() + } + + /** + * Check if a certain registry has completed registration. + * + * @param R + * The registry type + * @param registryType + * A [ResourceKey] for the registry in question + * @return `true` iff the given registry has finished the registration step + */ + open fun isRegistered(registryType: ResourceKey>) = registrationTracker.isRegistered(registryType) + + /** + * Get the data provider instance for a given [GeneratorType]. Only works within datagen context, not during + * registration or init. + * + * @param P + * The type of the provider + * @param type + * A [GeneratorType] representing the desired provider + * @return An [Optional] holding the provider, or empty if this provider was not registered. This can happen + * if datagen is run only for client or server providers. + * @throws IllegalStateException + * if datagen has not started yet + */ + open fun

getDataProvider(type: GeneratorType

): Optional

{ + val provider = this.provider + if (provider != null) { + return provider.getSubProvider(type) + } + throw IllegalStateException("Cannot get data provider before datagen is started") + } + + /** + * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data + * gen callback if it exists. + * + * @param P + * The type of provider + * @param R + * The registry type + * @param builder + * The builder for the entry + * @param type + * The [GeneratorType] to generate data for + * @param cons + * A callback to be invoked during data generation + * @return this [AbstractRegistrate] + */ + open fun

setDataGenerator(builder: Builder, type: GeneratorType, cons: NonNullConsumer) = + this.setDataGenerator(builder.name, builder.registryKey, type, cons) + + /** + * Mostly internal, removes the data generator for a certain entry/type combination if one was previously + * registered. + * + * @param P + * The type of provider + * @param R + * The registry type + * @param builder + * The builder for the entry + * @param type + * The [GeneratorType] to stop generating data for + * @return this [AbstractRegistrate] + */ + open fun

removeDataGenerator(builder: Builder, type: GeneratorType): S = this.removeDataGenerator(builder.name, builder.registryKey, type) + + /** + * Mostly internal, sets the data generator for a certain entry/type combination. This will replace an existing data + * gen callback if it exists. + * + * @param P + * The type of provider + * @param R + * The registry type + * @param entry + * The name of the entry which the provider is for + * @param registryType + * A [Class] representing the registry type of the entry + * @param type + * The [GeneratorType] to generate data for + * @param cons + * A callback to be invoked during data generation + * @return this [AbstractRegistrate] + */ + open fun

setDataGenerator(entry: String, registryType: ResourceKey>, type: GeneratorType, cons: NonNullConsumer) = + setDataGenerator(entry, registryType, EntryMetadata.DataGenerator(type, cons)) + + private fun

setDataGenerator(entry: String, registryType: ResourceKey>, generator: EntryMetadata.DataGenerator

): S { + val existing = datagensByEntry.put(Pair.of(entry, registryType), generator.type, generator) + if (existing != null) { + datagens.remove(generator.type, existing.callback) + } + return addDataGenerator(generator.type, generator.callback) + } + + /** + * Mostly internal, removes the data generator for a certain entry/type combination if one was previously + * registered. + * + * @param P + * The type of provider + * @param R + * The registry type + * @param entry + * The name of the entry which the provider is for + * @param registryType + * The registry type of the entry + * @param type + * The [GeneratorType] to stop generating data for + * @return this [AbstractRegistrate] + */ + open fun

removeDataGenerator(entry: String, registryType: ResourceKey>, type: GeneratorType): S { + val existing = datagensByEntry.remove(Pair.of(entry, registryType), type) + if (existing != null) { + datagens.remove(type, existing.callback) + } + return self() + } + + /** + * Add a data generator callback that is not associated with any entry, which can never replace an existing data + * generator. + * + * This is useful to add data generator callbacks for miscellaneous data not strictly associated with an entry. + * + * @param T + * The type of provider + * @param type + * The [GeneratorType] to generate data for + * @param cons + * A callback to be invoked during data generation + * @return this [AbstractRegistrate] + */ + open fun addDataGenerator(type: GeneratorType, cons: NonNullConsumer): S { + if (dataGeneration.get()) { + check(provider == null) { "Cannot add data generator after construction of root generator" } + datagens.put(type, cons) + } + return self() + } + + open val dataGenInitializer: DataProviderInitializer by lazy(LazyThreadSafetyMode.NONE, ::DataProviderInitializer) + + @JvmRecord + private data class RawTranslation(val key: TranslationKey, val declaration: LocalizationDeclaration, val source: TranslationSource) + + private val extraLang = ArrayList() + private val generatedLang = ConcurrentLinkedQueue() + private var sourceLocale: MinecraftLocale? = null + private val localizationCatalog = LocalizationCatalog() + + /** Configures the source locale for this mod before data generation. */ + open fun sourceLocale(locale: MinecraftLocale): S { + sourceLocale = locale + return self() + } + + /** Returns the source locale after validating this mod's configuration. */ + open fun requireSourceLocale(): MinecraftLocale { + val locale = sourceLocale + requireNotNull(locale) { "[$modid] Configure sourceLocale before generating languages" } + return locale + } + + open fun localizationCatalog(): LocalizationCatalog = localizationCatalog + + open fun collectRawTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { + for (translation in extraLang) { + collectRawTranslation(registry, locale, translation) + } + while (true) { + val translation = generatedLang.poll() ?: break + collectRawTranslation(registry, locale, translation) + } + } + + private fun collectRawTranslation(registry: TranslationRegistry, locale: MinecraftLocale, translation: RawTranslation) { + if (translation.source.kind != TranslationSource.Kind.AUTOMATIC || locale == MinecraftLocale.EN_US) { + registry.add(translation.key, locale, translation.declaration, translation.source) + } + } + + /** + * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. + * + * @param type + * Type of the object, this is used as a prefix (e.g. + * `["block", "mymod:myblock"] -> "block.mymod.myblock"`) + * @param id + * ID of the object, which will be converted to a lang key via + * [Util.makeDescriptionId] + * @param localizedName + * (English) translation value + * @return A [MutableComponent] representing the translated text + */ + open fun addLang(type: String, id: ResourceLocation, localizedName: String): MutableComponent = addRawLang(Util.makeDescriptionId(type, id), localizedName) + + /** + * Add a custom translation mapping using the vanilla style of ResourceLocation -> translation key conversion. + * Also + * appends a suffix to the key. + * + * @param type + * Type of the object, this is used as a prefix (e.g. + * `["block", "mymod:myblock"] -> "block.mymod.myblock"`) + * @param id + * ID of the object, which will be converted to a lang key via + * [Util.makeDescriptionId] + * @param suffix + * A suffix which will be appended to the generated key (separated by a dot) + * @param localizedName + * (English) translation value + * @return A [MutableComponent] representing the translated text + */ + open fun addLang(type: String, id: ResourceLocation, suffix: String, localizedName: String): MutableComponent = addRawLang(Util.makeDescriptionId(type, id) + "." + suffix, localizedName) + + /** + * Add a custom translation mapping directly to the lang provider. + * + * @param key + * The translation key + * @param value + * The (English) translation value + * @return A [MutableComponent] representing the translated text + */ + open fun addRawLang(key: String, value: String): MutableComponent = addRawLang(key, value, TranslationSource.Kind.DECLARED) + + private fun addRawLang(key: String, value: String, kind: TranslationSource.Kind): MutableComponent { + if (dataGeneration.get()) { + addLocalization(TranslationKey(modid, key), sourceText(value), kind) + } + return Component.translatable(key) + } + + /** Declares independent text and returns a component that uses its exact translation key. */ + open fun addLocalization(key: TranslationKey, configure: Consumer): MutableComponent { + if (dataGeneration.get()) { + val builder = LocalizationDeclaration.Builder() + configure.accept(builder) + addLocalization(key, builder.build(), TranslationSource.Kind.DECLARED) + } + return Component.translatable(key.value) + } + + private fun addLocalization(key: TranslationKey, declaration: LocalizationDeclaration, kind: TranslationSource.Kind) { + val translation = RawTranslation( + key, + declaration, + TranslationSource(kind, "[" + modid + "] manual declaration of " + key.value), + ) + if (provider == null) { + extraLang.add(translation) + } else { + generatedLang.add(translation) + } + } + + open fun collectEntryTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { + registrationTracker.forEachLocalization { entry, localization -> + if (localization.kind == TranslationSource.Kind.AUTOMATIC && locale != MinecraftLocale.EN_US) { + return@forEachLocalization + } + val key = TranslationKey(modid, localization.key.get()) + val source = TranslationSource( + localization.kind, + "Builder ${entry.id} in ${entry.key!!.registry()}", + ) + registry.add(key, locale, localization.declaration.get(), source) + } + } + + private fun getEntryForGenerator(type: GeneratorType<*>, generator: NonNullConsumer<*>): Pair>>? { + for ((key, declaration) in datagensByEntry.column(type)) { + if (declaration.callback === generator) return key + } + return null + } + + /** Runs the registered callbacks for the supplied generator. */ + @Suppress("UNCHECKED_CAST") + open fun genData(type: GeneratorType, gen: T) { + if (!dataGeneration.get()) return + provider?.putSubProvider(type, gen) + val debug = DATAGEN_LOGGER.isEnabled(Level.DEBUG, DebugMarkers.DATA) + for (callback in datagens[type]) { + val entry = if (debug) getEntryForGenerator(type, callback) else null + if (debug) { + val name = getTypeName(type) + if (entry == null) { + DATAGEN_LOGGER.debug(DebugMarkers.DATA, modMessage("Generating unassociated data of type {} ({})"), modid, name, type) + } else { + DATAGEN_LOGGER.debug(DebugMarkers.DATA, modMessage("Generating data of type {} for entry {} [{}]"), modid, name, entry.left, entry.right.location()) + } + } + try { + (callback as NonNullConsumer).accept(gen) + } catch (error: Exception) { + val key = if (debug) entry else getEntryForGenerator(type, callback) + val message = "[$modid] Data generator ${getTypeName(type)} failed" + + if (key == null) " ($type)" else " for ${key.left} [${key.right.location()}]" + if (!skipErrors) throw IllegalStateException(message, error) + DATAGEN_LOGGER.error(DebugMarkers.DATA, message, error) + } + } + } + + /** + * Enable skipping of registry entries and data generators that error during registration/generation. + * + * **Should only be used for debugging!** `skipErrors(true)` will do nothing outside of a dev + * environment. + * + * @param skipErrors + * `true` to skip errors during registration/generation + * @return this [AbstractRegistrate] + */ + open fun skipErrors(skipErrors: Boolean): S { + if (skipErrors && !isDevEnvironment) { + LOGGER.warn( + modMessage("Ignoring skipErrors(true) because the runtime is not a development environment"), + modid, + ) + } else { + this.skipErrors = skipErrors + } + return self() + } + + /** + * Begin a new object, this is typically used at the beginning of a builder chain. The given name will be used until + * this method is called again. This makes it simple to create multiple entries + * with the same name, as is often the case with blocks/items, items/entities, and blocks/TEs. + * + * @param name + * The name to use for future entries + * @return this [AbstractRegistrate] + */ + open fun `object`(name: String): S { + this.currentName = name + return self() + } + + /** + * Set the default CreativeModeTab to be passed onto future builders. + * + * This special case method should be used if your creative tab instance was not created by Registrate, otherwise + * use [defaultCreativeTab]. + * + * @param creativeModeTab + * The new default CreativeModeTab type + * @return This [AbstractRegistrate] instance + */ + open fun defaultCreativeTab(creativeModeTab: ResourceKey): S { + defaultCreativeModeTab = creativeModeTab + return self() + } + + /** + * Registers a new modifier callback to be used to modify the given CreativeModeTab. + * + * + * Registers a new callback to be invoked during the [BuildCreativeModeTabContentsEvent] event and + * used to modify what items are displayed on the given [CreativeModeTab]. + * + * Calling this method multiple times will add additional callbacks. + * + * @param creativeModeTab The [CreativeModeTab] to register this callback for + * @param modifier The modifier callback to be registered + * @return This [AbstractRegistrate] instance + */ + open fun modifyCreativeModeTab(creativeModeTab: ResourceKey, modifier: Consumer): S { + creativeModeTabModifiers.put(creativeModeTab, modifier) + return self() + } + + /** + * Apply a transformation to this [AbstractRegistrate]. Useful to apply helper methods within a fluent chain, + * e.g. + * + * ```java + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * .transform(Utils::createMyBlock) + * .get(Block.class); + * ``` + * + * @param func + * The [function][java.util.function.UnaryOperator] to apply + * @return this [AbstractRegistrate] + */ + open fun transform(func: NonNullUnaryOperator): S = func.apply(self()) + + /** + * Apply a transformation to this [AbstractRegistrate]. Similar to [transform], + * but for actions that return a builder in-progress. Useful to apply helper methods + * within a fluent chain, e.g. + * + * ```java + * public static final RegistryEntry MY_BLOCK = REGISTRATE.object("my_block") + * .transform(Utils::createMyBlock) + * .lang("My Block") // Can modify the builder afterwards + * .register(); + * ``` + * + * @param R + * Registry type + * @param T + * Entry type + * @param P + * Parent type + * @param S2 + * Self type + * @param func + * The [function][Function] to apply + * @return the resultant [Builder] + */ + open fun > transform(func: NonNullFunction): S2 = func.apply(self()) + + /** + * Create a builder for a new entry. This is typically not needed, unless you are implementing a + * [custom builder type](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders). + * + * Uses the currently set name (via [object]) as the name for the new entry, and passes it to the + * factory as the first parameter. + * + * @param R + * Registry type + * @param T + * Entry type + * @param P + * Parent type + * @param S2 + * Self type + * @param factory + * The factory to create the builder + * @return The [Builder] instance + */ + open fun > entry(factory: NonNullBiFunction) = entry( + currentName(), + ) { callback: BuilderCallback -> factory.apply(currentName(), callback) } + + /** + * Create a builder for a new entry. This is typically not needed, unless you are implementing a + * [custom builder type](https://github.com/ModularMCLib/RegistrateLib/wiki/Custom-Builders). + * + * @param R + * Registry type + * @param T + * Entry type + * @param P + * Parent type + * @param S2 + * Self type + * @param name + * The name to use for the entry + * @param factory + * The factory to create the builder + * @return The [Builder] instance + */ + open fun > entry(name: String, factory: NonNullFunction): S2 = factory.apply(callback) + + /** + * Factory method to accept a completed builder and add it to the registration queue. + * + * Satisfies the functional interface [BuilderCallback], which is typically given to new builder instances + * when they are constructed. + * + * @param R + * Registry type + * @param T + * Entry type + * @param name + * Thename of the entry being created + * @param type + * The registry to add the entry to + * @param builder + * The builder instance that was used to create this entry. Not used by default implementation, + * but custom extensions may use it for some purpose + * @param creator + * Constructor for the new entry object + * @param entryFactory + * Optional custom factory to create special [RegistryEntry] types + * @return A [RegistryEntry] that will hold the created entry after registration is complete + */ + protected open fun accept( + name: String, + type: ResourceKey>, + builder: Builder, + creator: NonNullSupplier, + entryFactory: NonNullFunction, out RegistryEntry>, + ): RegistryEntry { + val generators = datagensByEntry.row(Pair.of(name, type)) + var localization: EntryLocalization? = null + var declarations: Collection> = emptyList() + if (builder is AbstractBuilder<*, *, *, *> && name == builder.name && type == builder.registryKey) { + declarations = builder.dataGenerators() + localization = builder.localization() + } + val entry = registrationTracker.track( + name, + type, + creator, + entryFactory, + EntryMetadata(generators.values, localization), + ) + for (generator in declarations) { + if (!generators.containsKey(generator.type)) { + setDataGenerator(name, type, generator) + } + } + return entry + } + + /** + * Returns the declarations for an entry submitted by this Registrate instance. + */ + open fun getEntryMetadata(key: ResourceKey<*>): EntryMetadata = registrationTracker.getMetadata(key) + + /** + * Helper to create a new registry for custom objects. The returned [ResourceKey] can be used immediately in + * methods like [simple][simple] or + * [generic][generic]. + * + * Alternatively, a custom [builder][Builder] can be created. + * + * This method will automatically subscribe to the [NewRegistryEvent] and create the registry at the proper + * time. Thus, the new registry will not exist immediately after this is called. + * + * @param R + * The type of object the new registry will contain + * @param name + * The ID of this registry + * @param builder + * A function to create the [RegistryBuilder] that defines the other properties/behaviors of + * the created registry + * @return A [resource key][ResourceKey] referencing the to-be-created registry. + */ + open fun makeRegistry(name: String, builder: Function>, RegistryBuilder>): ResourceKey> { + val registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(modid, name)) + addModListener( + this, + NewRegistryEvent::class.java, + Consumer { e: NewRegistryEvent -> e.register(builder.apply(registryId).create()) }, + ) + return registryId + } + + /** + * Registers the given registry key as an unsynced datapack registry, which will cause data to be loaded from + * a datapack folder based on the registry's name. The datapack registry is not required to be present + * on clients when connecting to servers with the mod/registry. + * + * Data JSONs will be loaded from `data//modid/registryname/`, where `modid` is the + * namespace of the registry key. + * + * @param name The ID of this registry + * @param codec The codec to be used for loading data from datapacks on servers + * @see .makeDatapackRegistry + */ + open fun makeDatapackRegistry(name: String, codec: Codec) = makeDatapackRegistry(name, codec, null) + + /** + * Registers the registry key as a datapack registry, which will cause data to be loaded from + * a datapack folder based on the registry's name. + * + * Data JSONs will be loaded from `data//modid/registryname/`, where `modid` is the + * namespace of the registry key. + * + * @param name The ID of this registry + * @param codec The codec to be used for loading data from datapacks on servers + * @param networkCodec The codec to be used for syncing loaded data to clients. + * If `networkCodec` is null, data will not be synced, and clients are not required to + * have this + * datapack registry to join a server. + * + * If `networkCodec` is not null, clients must have this datapack registry/mod + * when joining a server that has this datapack registry/mod. + * The data will be synced using the network codec and accessible via + * [net.minecraft.client.multiplayer.ClientPacketListener.registryAccess]. + * @see .makeDatapackRegistry + */ + open fun makeDatapackRegistry(name: String, codec: Codec, networkCodec: Codec?): ResourceKey> { + val registryId = ResourceKey.createRegistryKey(ResourceLocation.fromNamespaceAndPath(modid, name)) + addModListener( + this, + NewRegistry::class.java, + Consumer { event: NewRegistry -> event.dataPackRegistry(registryId, codec, networkCodec) }, + ) + return registryId + } + + /* === Builder helpers === */ + // Generic + open fun simple(registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = simple(currentName(), registryType, factory) + + open fun simple(name: String, registryType: ResourceKey>, factory: NonNullSupplier) = simple(this, name, registryType, factory) + + open fun simple(parent: P, registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = + simple(parent, currentName(), registryType, factory) + + open fun simple(parent: P, name: String, registryType: ResourceKey>, factory: NonNullSupplier): RegistryEntry = + generic(parent, name, registryType, factory).register() + + open fun generic(registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(self(), registryType, factory) + + open fun generic(name: String, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = generic(self(), name, registryType, factory) + + open fun generic(parent: P, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = + generic(parent, currentName(), registryType, factory) + + open fun generic(parent: P, name: String, registryType: ResourceKey>, factory: NonNullSupplier): NoConfigBuilder = + entry>( + name, + ) { callback: BuilderCallback -> + NoConfigBuilder( + this, + parent, + name, + callback, + registryType, + factory, + ) + } + + // Items + open fun item(factory: NonNullFunction): ItemBuilder = item(self(), factory) + + open fun item(name: String, factory: NonNullFunction): ItemBuilder = item(self(), name, factory) + + open fun item(parent: P, factory: NonNullFunction): ItemBuilder = item(parent, currentName(), factory) + + open fun item(parent: P, name: String, factory: NonNullFunction): ItemBuilder = entry>( + name, + ) { callback: BuilderCallback -> + ItemBuilder.create(this, parent, name, callback, factory) + .tab(defaultCreativeModeTab) + } + + // Blocks + open fun block(factory: NonNullFunction): BlockBuilder = block(self(), factory) + + open fun block(name: String, factory: NonNullFunction): BlockBuilder = block(self(), name, factory) + + open fun block(parent: P, factory: NonNullFunction): BlockBuilder = block(parent, currentName(), factory) + + open fun block(parent: P, name: String, factory: NonNullFunction): BlockBuilder = entry>( + name, + ) { callback: BuilderCallback -> + BlockBuilder.create( + this, + parent, + name, + callback, + factory, + ) + } + + // Entities + open fun entity(factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(self(), factory, classification) + + open fun entity(name: String, factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(self(), name, factory, classification) + + open fun entity(parent: P, factory: EntityFactory, classification: MobCategory): EntityBuilder = entity(parent, currentName(), factory, classification) + + open fun entity(parent: P, name: String, factory: EntityFactory, classification: MobCategory): EntityBuilder = + entry, EntityType, P, EntityBuilder>( + name, + ) { callback: BuilderCallback -> + EntityBuilder.create( + this, + parent, + name, + callback, + factory, + classification, + ) + } + + // Block Entities + open fun blockEntity(factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(self(), factory) + + open fun blockEntity(name: String, factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(self(), name, factory) + + open fun blockEntity(parent: P, factory: BlockEntityFactory): BlockEntityBuilder = blockEntity(parent, currentName(), factory) + + open fun blockEntity(parent: P, name: String, factory: BlockEntityFactory): BlockEntityBuilder = + entry, BlockEntityType, P, BlockEntityBuilder>( + name, + ) { callback: BuilderCallback -> + BlockEntityBuilder.create( + this, + parent, + name, + callback, + factory, + ) + } + + // Fluids + open fun fluid(): FluidBuilder = fluid(self()) + + open fun fluid(typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), typeFactory) + + open fun fluid(fluidType: NonNullSupplier): FluidBuilder = fluid(self(), fluidType) + + open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = fluid(self(), stillTexture, flowingTexture) + + open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), stillTexture, flowingTexture, typeFactory) + + open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = + fluid(self(), stillTexture, flowingTexture, fluidType) + + open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = + fluid(self(), stillTexture, flowingTexture, fluidFactory) + + open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory, fluidFactory: FluidFactory): FluidBuilder = + fluid(self(), stillTexture, flowingTexture, typeFactory, fluidFactory) + + open fun fluid(stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier, fluidFactory: FluidFactory): FluidBuilder = + fluid(self(), stillTexture, flowingTexture, fluidType, fluidFactory) + + open fun fluid(name: String): FluidBuilder = fluid(self(), name) + + open fun fluid(name: String, typeFactory: FluidTypeFactory): FluidBuilder = fluid(self(), name, typeFactory) + + open fun fluid(name: String, fluidType: NonNullSupplier): FluidBuilder = fluid(self(), name, fluidType) + + open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture) + + open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = + fluid(self(), name, stillTexture, flowingTexture, typeFactory) + + open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = + fluid(self(), name, stillTexture, flowingTexture, fluidType) + + open fun fluid(name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = + fluid(self(), name, stillTexture, flowingTexture, fluidFactory) + + open fun fluid( + name: String, + stillTexture: ResourceLocation, + flowingTexture: ResourceLocation, + typeFactory: FluidTypeFactory, + fluidFactory: FluidFactory, + ): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, typeFactory, fluidFactory) + + open fun fluid( + name: String, + stillTexture: ResourceLocation, + flowingTexture: ResourceLocation, + fluidType: NonNullSupplier, + fluidFactory: FluidFactory, + ): FluidBuilder = fluid(self(), name, stillTexture, flowingTexture, fluidType, fluidFactory) + + open fun

fluid(parent: P): FluidBuilder = fluid(parent, currentName()) + + open fun

fluid(parent: P, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, currentName(), typeFactory) + + open fun

fluid(parent: P, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, currentName(), fluidType) + + open fun

fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture) + + open fun

fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = + fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory) + + open fun

fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = + fluid(parent, currentName(), stillTexture, flowingTexture, fluidType) + + open fun fluid(parent: P, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = + fluid(parent, currentName(), stillTexture, flowingTexture, fluidFactory) + + open fun fluid( + parent: P, + stillTexture: ResourceLocation, + flowingTexture: ResourceLocation, + typeFactory: FluidTypeFactory, + fluidFactory: FluidFactory, + ): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, typeFactory, fluidFactory) + + open fun fluid( + parent: P, + stillTexture: ResourceLocation, + flowingTexture: ResourceLocation, + fluidType: NonNullSupplier, + fluidFactory: FluidFactory, + ): FluidBuilder = fluid(parent, currentName(), stillTexture, flowingTexture, fluidType, fluidFactory) + + open fun

fluid(parent: P, name: String): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture()) + + open fun

fluid(parent: P, name: String, typeFactory: FluidTypeFactory): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), typeFactory) + + open fun

fluid(parent: P, name: String, fluidType: NonNullSupplier): FluidBuilder = fluid(parent, name, defaultStillTexture(), defaultFlowingTexture(), fluidType) + + private fun defaultStillTexture(): ResourceLocation = ResourceLocation.fromNamespaceAndPath(modid, "block/" + currentName() + "_still") + + private fun defaultFlowingTexture(): ResourceLocation = ResourceLocation.fromNamespaceAndPath(modid, "block/" + currentName() + "_flow") + + open fun

fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder = entry>( + name, + ) { callback: BuilderCallback -> + FluidBuilder.create( + this, + parent, + name, + callback, + FluidTypeFactory(::FluidType), + ) + }.model(stillTexture, flowingTexture) + + open fun

fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, typeFactory: FluidTypeFactory): FluidBuilder = + entry>( + name, + ) { callback: BuilderCallback -> + FluidBuilder.create( + this, + parent, + name, + callback, + typeFactory, + ) + }.model(stillTexture, flowingTexture) + + open fun

fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidType: NonNullSupplier): FluidBuilder = + entry>( + name, + ) { callback: BuilderCallback -> + FluidBuilder.create( + this, + parent, + name, + callback, + fluidType, + ) + }.model(stillTexture, flowingTexture) + + open fun fluid(parent: P, name: String, stillTexture: ResourceLocation, flowingTexture: ResourceLocation, fluidFactory: FluidFactory): FluidBuilder = + entry>( + name, + ) { callback: BuilderCallback -> + FluidBuilder.create( + this, + parent, + name, + callback, + fluidFactory, + ) + }.model(stillTexture, flowingTexture) + + open fun fluid( + parent: P, + name: String, + stillTexture: ResourceLocation, + flowingTexture: ResourceLocation, + typeFactory: FluidTypeFactory, + fluidFactory: FluidFactory, + ): FluidBuilder = entry>( + name, + ) { callback: BuilderCallback -> + FluidBuilder.create( + this, + parent, + name, + callback, + typeFactory, + fluidFactory, + ) + }.model(stillTexture, flowingTexture) + + open fun fluid( + parent: P, + name: String, + stillTexture: ResourceLocation, + flowingTexture: ResourceLocation, + fluidType: NonNullSupplier, + fluidFactory: FluidFactory, + ): FluidBuilder = entry>( + name, + ) { callback: BuilderCallback -> + FluidBuilder.create( + this, + parent, + name, + callback, + fluidType, + fluidFactory, + ) + }.model(stillTexture, flowingTexture) + + // Menu + open fun menu(factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = + menu(currentName(), factory, screenFactory) + + open fun menu(name: String, factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = + menu(self(), name, factory, screenFactory) + + open fun menu(parent: P, factory: MenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = + menu(parent, currentName(), factory, screenFactory) + + open fun menu( + parent: P, + name: String, + factory: MenuFactory, + screenFactory: NonNullSupplier>, + ): MenuBuilder where SC : Screen, SC : MenuAccess = entry, MenuType, P, MenuBuilder>( + name, + ) { callback: BuilderCallback -> + MenuBuilder( + this, + parent, + name, + callback, + factory, + screenFactory, + ) + } + + open fun menu(factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = + menu(currentName(), factory, screenFactory) + + open fun menu(name: String, factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = + menu(self(), name, factory, screenFactory) + + open fun menu(parent: P, factory: ForgeMenuFactory, screenFactory: NonNullSupplier>) where SC : Screen, SC : MenuAccess = + menu(parent, currentName(), factory, screenFactory) + + open fun menu( + parent: P, + name: String, + factory: ForgeMenuFactory, + screenFactory: NonNullSupplier>, + ): MenuBuilder where SC : Screen, SC : MenuAccess = entry, MenuType, P, MenuBuilder>( + name, + ) { callback: BuilderCallback -> + MenuBuilder( + this, + parent, + name, + callback, + factory, + screenFactory, + ) + } + + // Creative Tab + open fun defaultCreativeTab(): NoConfigBuilder = defaultCreativeTab(self()) + + open fun defaultCreativeTab(name: String): NoConfigBuilder = defaultCreativeTab(self(), name) + + open fun

defaultCreativeTab(parent: P): NoConfigBuilder = defaultCreativeTab(parent, currentName()) + + open fun

defaultCreativeTab(parent: P, name: String): NoConfigBuilder = defaultCreativeTab( + parent, + name, + ) { tab: CreativeModeTab.Builder -> + } + + open fun defaultCreativeTab(config: Consumer): NoConfigBuilder = defaultCreativeTab(self(), config) + + open fun defaultCreativeTab(name: String, config: Consumer): NoConfigBuilder = defaultCreativeTab(self(), name, config) + + open fun

defaultCreativeTab(parent: P, config: Consumer): NoConfigBuilder = + defaultCreativeTab(parent, currentName(), config) + + open fun

defaultCreativeTab(parent: P, name: String, config: Consumer): NoConfigBuilder { + this.defaultCreativeModeTab = ResourceKey.create( + Registries.CREATIVE_MODE_TAB, + ResourceLocation.fromNamespaceAndPath(this.modid, name), + ) + return this.generic( + parent, + name, + Registries.CREATIVE_MODE_TAB, + ) { + val builder = CreativeModeTab.builder() + .icon { + getAll(Registries.ITEM).firstOrNull()?.get()?.let(::ItemStack) ?: ItemStack.EMPTY + } + .title( + addRawLang( + Util.makeDescriptionId("itemGroup", this.defaultCreativeModeTab.location()), + toEnglishName(name), + TranslationSource.Kind.AUTOMATIC, + ), + ) + config.accept(builder) + builder.build() + } + } + + companion object { + private val LOGGER = core() + private val DATAGEN_LOGGER = datagen() + + /** Enables development diagnostics when NeoForge is running outside production. */ + @get:JvmStatic + val isDevEnvironment: Boolean + get() = !FMLEnvironment.production + } +} diff --git a/src/main/java/com/modularmc/registrate/Registrate.java b/src/main/java/com/modularmc/registrate/Registrate.java deleted file mode 100644 index 9e8d07d..0000000 --- a/src/main/java/com/modularmc/registrate/Registrate.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.modularmc.registrate; - -import com.modularmc.registrate.internal.util.RegistrateLogger; - -import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.ModContainer; -import net.neoforged.fml.ModList; - -import org.apache.logging.log4j.Logger; - -import java.util.Optional; - -public class Registrate extends AbstractRegistrate { - - private static final Logger LOGGER = RegistrateLogger.core(); - - /** - * Create a new {@link Registrate} and register event listeners for registration and data generation. Used in lieu - * of adding side-effects to constructor, so that alternate initialization - * strategies can be done in subclasses. - * - * @param modid - * The mod ID for which objects will be registered - * @return The {@link Registrate} instance - */ - public static Registrate create(String modid) { - var ret = new Registrate(modid); - - Optional modEventBus = ModList.get().getModContainerById(modid) - .map(ModContainer::getEventBus); - - modEventBus.ifPresentOrElse(ret::registerEventListeners, () -> LOGGER.fatal( - RegistrateLogger.modMessage( - "Failed to locate the mod event bus during Registrate.create; registration listeners were not attached"), - modid)); - - return ret; - } - - protected Registrate(String modid) { - super(modid); - } -} diff --git a/src/main/java/com/modularmc/registrate/Registrate.kt b/src/main/java/com/modularmc/registrate/Registrate.kt new file mode 100644 index 0000000..8b098b0 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/Registrate.kt @@ -0,0 +1,24 @@ +package com.modularmc.registrate + +import com.modularmc.registrate.internal.util.RegistrateLogger + +import net.neoforged.fml.ModList + +open class Registrate protected constructor(modid: String) : AbstractRegistrate(modid) { + companion object { + private val LOGGER = RegistrateLogger.core() + + /** Creates a Registrate and attaches its listeners to the owning mod's event bus. */ + @JvmStatic + fun create(modid: String): Registrate { + val registrate = Registrate(modid) + val bus = ModList.get().getModContainerById(modid).orElse(null)?.eventBus + if (bus != null) { + registrate.registerEventListeners(bus) + } else { + LOGGER.fatal(RegistrateLogger.modMessage("Failed to locate the mod event bus during Registrate.create; registration listeners were not attached"), modid) + } + return registrate + } + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java deleted file mode 100644 index 35ff835..0000000 --- a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.java +++ /dev/null @@ -1,386 +0,0 @@ -package com.modularmc.registrate.builders; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.builders.BlockEntityBuilder.BlockEntityFactory; -import com.modularmc.registrate.builders.base.AbstractBuilder; -import com.modularmc.registrate.builders.base.BuilderCallback; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; -import com.modularmc.registrate.internal.util.RegistrateDistExecutor; -import com.modularmc.registrate.providers.DataGenContext; -import com.modularmc.registrate.providers.RegistrateLangProvider; -import com.modularmc.registrate.providers.core.GeneratorType; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.generators.RegistrateBlockModelGenerator; -import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; -import com.modularmc.registrate.providers.loot.RegistrateBlockLootTables; -import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider.LootType; -import com.modularmc.registrate.util.entry.BlockEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullBiConsumer; -import com.modularmc.registrate.util.nullness.NonNullBiFunction; -import com.modularmc.registrate.util.nullness.NonNullFunction; -import com.modularmc.registrate.util.nullness.NonNullSupplier; -import com.modularmc.registrate.util.nullness.NonNullUnaryOperator; - -import net.minecraft.client.color.block.BlockColor; -import net.minecraft.core.registries.Registries; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.storage.loot.BuiltInLootTables; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent; -import net.neoforged.neoforge.client.extensions.common.IClientBlockExtensions; -import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; -import net.neoforged.neoforge.registries.DeferredHolder; - -import org.jspecify.annotations.Nullable; - -import java.util.function.Supplier; - -import javax.annotation.Nonnull; - -/** - * A builder for blocks, allows for customization of the {@link Block.Properties}, creation of block items, and - * configuration of data associated with blocks (loot tables, recipes, etc.). - * - * @param - * The type of block being built - * @param

- * Parent object type - */ -public class BlockBuilder extends AbstractBuilder> { - - /** - * Create a new {@link BlockBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - *

- * The block will be assigned the following data: - *

    - *
  • A default blockstate file mapping all states to one model (via {@link #defaultBlockstate()})
  • - *
  • A simple cube_all model (used in the blockstate) with one texture (via {@link #defaultBlockstate()})
  • - *
  • A self-dropping loot table (via {@link #defaultLoot()})
  • - *
  • The default translation (via {@link #defaultLang()})
  • - *
- * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the block - * @return A new {@link BlockBuilder} with reasonable default data generators. - */ - public static BlockBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory) { - return new BlockBuilder<>(owner, parent, name, callback, factory, () -> BlockBehaviour.Properties.of()) - .defaultBlockstate().defaultLoot().defaultLang(); - } - - private final NonNullFunction factory; - - private NonNullSupplier initialProperties; - private NonNullFunction propertiesCallback = NonNullUnaryOperator.identity(); - - private @Nullable NonNullSupplier> colorHandler; - - protected BlockBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory, NonNullSupplier initialProperties) { - super(owner, parent, name, callback, Registries.BLOCK); - this.factory = factory; - this.initialProperties = initialProperties; - } - - /** - * Modify the properties of the block. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. - *

- * If a different properties instance is returned, it will replace the existing one entirely. - * - * @param func - * The action to perform on the properties - * @return this {@link BlockBuilder} - */ - public BlockBuilder properties(NonNullUnaryOperator func) { - propertiesCallback = propertiesCallback.andThen(func); - return this; - } - - /** - * Replace the initial state of the block properties, without replacing or removing any modifications done via - * {@link #properties(NonNullUnaryOperator)}. - * - * @param block - * The block to create the initial properties from (via - * {@link Block.Properties#ofFullCopy(BlockBehaviour)}) - * @return this {@link BlockBuilder} - */ - public BlockBuilder initialProperties(NonNullSupplier block) { - initialProperties = () -> BlockBehaviour.Properties.ofFullCopy(block.get()); - return this; - } - - /** - * Create a standard {@link BlockItem} for this block, building it immediately, and not allowing for further - * configuration. - *

- * The item will have no lang entry (since it would duplicate the block's) - * - * @return this {@link BlockBuilder} - * @see #item() - */ - public BlockBuilder simpleItem() { - return item().build(); - } - - /** - * Create a standard {@link BlockItem} for this block, and return the builder for it so that further customization - * can be done. - *

- * The item will have no lang entry (since it would duplicate the block's) - * - * @return the {@link ItemBuilder} for the {@link BlockItem} - */ - public ItemBuilder> item() { - return item(BlockItem::new); - } - - /** - * Create a {@link BlockItem} for this block, which is created by the given factory, and return the builder for it - * so that further customization can be done. - *

- * By default, the item will have no lang entry (since it would duplicate the block's) and a simple block item - * model. - * - * @param - * The type of the item - * @param factory - * A factory for the item, which accepts the block object and properties and returns a new item - * @return the {@link ItemBuilder} for the {@link BlockItem} - */ - public ItemBuilder> item(NonNullBiFunction factory) { - return getOwner().>item(this, getName(), p -> factory.apply(getEntry(), p)) - .removeData(ProviderType.LANG) - .model(() -> (ctx, prov) -> { - if (prov.hasModel(ctx.get())) { - return; - } - var block = getEntry(); - var model = getOwner().getDataProvider(ProviderType.BLOCKSTATE) - .flatMap(generator -> generator.getSingleVariantModel(block)) - .orElseGet(() -> RegistrateBlockModelGenerator.modelLocation(block)); - prov.createWithExistingModel(ctx.get(), model); - }); - } - - /** - * Create a {@link BlockEntity} for this block, which is created by the given factory, and assigned this block as - * its one and only valid block. - * - * @param - * The type of the block entity - * @param factory - * A factory for the block entity - * @return this {@link BlockBuilder} - */ - public BlockBuilder simpleBlockEntity(BlockEntityFactory factory) { - return blockEntity(factory).build(); - } - - /** - * Create a {@link BlockEntity} for this block, which is created by the given factory, and assigned this block as - * its one and only valid block. - *

- * The created {@link BlockEntityBuilder} is returned for further configuration. - * - * @param - * The type of the block entity - * @param factory - * A factory for the block entity - * @return the {@link BlockEntityBuilder} - */ - public BlockEntityBuilder> blockEntity(BlockEntityFactory factory) { - return getOwner().>blockEntity(this, getName(), factory).validBlock(asSupplier()); - } - - /** - * Registers the client color handler for all tint indices of this block. - * - * @param colorHandler A side-safe supplier of the client color handler - * @return this {@link BlockBuilder} - */ - public BlockBuilder color(NonNullSupplier> colorHandler) { - if (this.colorHandler == null) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerBlockColor); - } - this.colorHandler = colorHandler; - return this; - } - - protected void registerBlockColor() { - OneTimeEventReceiver.addModListener(getOwner(), RegisterColorHandlersEvent.Block.class, event -> { - var colorHandler = this.colorHandler; - if (colorHandler != null) { - event.register(colorHandler.get().get(), getEntry()); - } - }); - } - - /** - * Assign the default blockstate, which maps all states to a single model file (via - * {@link RegistrateBlockModelGenerator#createTrivialCube(Block)}). This is the default, so it is generally not - * necessary - * to call, unless for undoing previous changes. - * - * @return this {@link BlockBuilder} - */ - public BlockBuilder defaultBlockstate() { - return blockstate(() -> (ctx, prov) -> prov.createTrivialCube(ctx.getEntry())); - } - - /** - * Configure the blockstate/models for this block. - * - * @param cons - * The callback which will be invoked during data generation. - * @return this {@link BlockBuilder} - * @see #setData(GeneratorType, NonNullBiConsumer) - */ - public BlockBuilder blockstate(NonNullSupplier, RegistrateBlockModelGenerator>> cons) { - if (!getOwner().doDatagen().get()) return this; - return setData(ProviderType.BLOCKSTATE, cons.get()); - } - - /** - * Assign the default translation, as specified by - * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, net.minecraft.resources.ResourceKey)}. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. - * - * @return this {@link BlockBuilder} - */ - public BlockBuilder defaultLang() { - return lang(Block::getDescriptionId); - } - - /** - * Set the translation for this block. - * - * @param name - * A localized English name - * @return this {@link BlockBuilder} - */ - public BlockBuilder lang(String name) { - return lang(Block::getDescriptionId, name); - } - - /** - * Assign the default loot table, as specified by {@link RegistrateBlockLootTables#dropSelf(Block)}. This is the - * default, so it is generally not necessary to call, unless for - * undoing previous changes. - * - * @return this {@link BlockBuilder} - */ - public BlockBuilder defaultLoot() { - return loot(RegistrateBlockLootTables::dropSelf); - } - - /** - * Configure the loot table for this block. This is different than most data gen callbacks as the callback does not - * accept a {@link DataGenContext}, but instead a - * {@link RegistrateBlockLootTables}, for creating specifically block loot tables. - *

- * If the block does not have a loot table (i.e. {@link Block.Properties#noLootTable()} is called) this action will - * be skipped. - * - * @param cons - * The callback which will be invoked during block loot table creation. - * @return this {@link BlockBuilder} - */ - public BlockBuilder loot(NonNullBiConsumer cons) { - return setData(ProviderType.LOOT, (ctx, prov) -> prov.addLootAction(LootType.BLOCK, tb -> { - if (ctx.getEntry().getLootTable() != BuiltInLootTables.EMPTY) { - cons.accept(tb, ctx.getEntry()); - } - })); - } - - /** - * Configure the recipe(s) for this block. - * - * @param cons - * The callback which will be invoked during data generation. - * @return this {@link BlockBuilder} - * @see #setData(GeneratorType, NonNullBiConsumer) - */ - public BlockBuilder recipe(NonNullBiConsumer, RegistrateRecipeProvider> cons) { - return setData(ProviderType.RECIPE, cons); - } - - private @Nullable NonNullSupplier> clientExtension; - - /** - * Register a client extension for this block. - * The {@link IClientBlockExtensions} instance can be shared across many items. - * - * @param clientExtension - * The client extension to register for this block - * @return this {@link BlockBuilder} - */ - public BlockBuilder clientExtension(NonNullSupplier> clientExtension) { - if (this.clientExtension == null) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); - } - this.clientExtension = clientExtension; - return this; - } - - protected void registerClientExtension() { - OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, e -> { - NonNullSupplier> clientExtension = this.clientExtension; - if (clientExtension != null) { - e.registerBlock(clientExtension.get().get(), getEntry()); - } - }); - } - - /** - * Assign {@link TagKey}{@code s} to this block. Multiple calls will add additional tags. - * - * @param tags - * The tags to assign - * @return this {@link BlockBuilder} - */ - @SafeVarargs - public final BlockBuilder tag(TagKey... tags) { - return tag(ProviderType.BLOCK_TAGS, tags); - } - - @Override - protected T createEntry() { - @Nonnull - BlockBehaviour.Properties properties = this.initialProperties.get(); - properties = propertiesCallback.apply(properties); - return factory.apply(properties); - } - - @Override - protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { - return new BlockEntry<>(getOwner(), delegate); - } - - @Override - public BlockEntry register() { - return (BlockEntry) super.register(); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt new file mode 100644 index 0000000..d276606 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/BlockBuilder.kt @@ -0,0 +1,407 @@ +package com.modularmc.registrate.builders + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.builders.base.AbstractBuilder +import com.modularmc.registrate.builders.base.BuilderCallback +import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener +import com.modularmc.registrate.internal.util.RegistrateDistExecutor.unsafeRunWhenOn +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.providers.DataGenContext +import com.modularmc.registrate.providers.RegistrateLangProvider +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.generators.RegistrateBlockModelGenerator +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider +import com.modularmc.registrate.providers.loot.RegistrateBlockLootTables +import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider +import com.modularmc.registrate.util.entry.BlockEntry +import com.modularmc.registrate.util.nullness.* + +import net.minecraft.client.color.block.BlockColor +import net.minecraft.core.registries.Registries +import net.minecraft.tags.TagKey +import net.minecraft.world.item.BlockItem +import net.minecraft.world.item.Item +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.block.entity.BlockEntity +import net.minecraft.world.level.block.state.BlockBehaviour +import net.minecraft.world.level.storage.loot.BuiltInLootTables +import net.neoforged.api.distmarker.Dist +import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent +import net.neoforged.neoforge.client.extensions.common.IClientBlockExtensions +import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent +import net.neoforged.neoforge.registries.DeferredHolder + +import java.util.function.Consumer +import java.util.function.Function +import java.util.function.Supplier + +/** + * A builder for blocks, allows for customization of the [Block.Properties], creation of block items, and + * configuration of data associated with blocks (loot tables, recipes, etc.). + * + * @param T + * The type of block being built + * @param P + * Parent object type + */ +open class BlockBuilder protected constructor( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + private val factory: NonNullFunction, + private var initialProperties: NonNullSupplier, +) : AbstractBuilder>(owner, parent, name, callback, Registries.BLOCK) { + private var propertiesCallback = + NonNullUnaryOperator.identity() + + private var colorHandler: NonNullSupplier>? = null + + /** + * Modify the properties of the block. Modifications are done lazily, but the passed function is composed with the + * current one, and as such this method can be called multiple times to perform + * different operations. + * + * + * If a different properties instance is returned, it will replace the existing one entirely. + * + * @param func + * The action to perform on the properties + * @return this [BlockBuilder] + */ + open fun properties(func: NonNullUnaryOperator): BlockBuilder { + propertiesCallback = propertiesCallback.andThen(func) + return this + } + + /** + * Replace the initial state of the block properties, without replacing or removing any modifications done via + * [properties]. + * + * @param block + * The block to create the initial properties from (via + * [Block.Properties.ofFullCopy]) + * @return this [BlockBuilder] + */ + open fun initialProperties(block: NonNullSupplier): BlockBuilder { + initialProperties = NonNullSupplier { BlockBehaviour.Properties.ofFullCopy(block.get()) } + return this + } + + /** + * Create a standard [BlockItem] for this block, building it immediately, and not allowing for further + * configuration. + * + * + * The item will have no lang entry (since it would duplicate the block's) + * + * @return this [BlockBuilder] + * @see .item + */ + open fun simpleItem(): BlockBuilder = item().build() + + /** + * Create a standard [BlockItem] for this block, and return the builder for it so that further customization + * can be done. + * + * + * The item will have no lang entry (since it would duplicate the block's) + * + * @return the [ItemBuilder] for the [BlockItem] + */ + open fun item() = item( + NonNullBiFunction { block: T, properties: Item.Properties -> + BlockItem( + block, + properties, + ) + }, + ) + + /** + * Create a [BlockItem] for this block, which is created by the given factory, and return the builder for it + * so that further customization can be done. + * + * + * By default, the item will have no lang entry (since it would duplicate the block's) and a simple block item + * model. + * + * @param I + * The type of the item + * @param factory + * A factory for the item, which accepts the block object and properties and returns a new item + * @return the [ItemBuilder] for the [BlockItem] + */ + open fun item(factory: NonNullBiFunction): ItemBuilder> { + return owner.item( + this, + name, + ) { p: Item.Properties -> factory.apply(entry, p) } + .removeData(ProviderType.LANG) + .model { + NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateItemModelGenerator -> + if (prov.hasModel(ctx.get())) { + return@NonNullBiConsumer + } + val block = entry + val model = owner.getDataProvider(ProviderType.BLOCKSTATE) + .flatMap( + Function { generator: RegistrateBlockModelGenerator -> + generator.getSingleVariantModel( + block, + ) + }, + ) + .orElseGet(Supplier { RegistrateBlockModelGenerator.modelLocation(block) }) + prov.createWithExistingModel(ctx.get(), model) + } + } + } + + /** + * Create a [BlockEntity] for this block, which is created by the given factory, and assigned this block as + * its one and only valid block. + * + * @param BE + * The type of the block entity + * @param factory + * A factory for the block entity + * @return this [BlockBuilder] + */ + open fun simpleBlockEntity(factory: BlockEntityBuilder.BlockEntityFactory) = blockEntity(factory).build() + + /** + * Create a [BlockEntity] for this block, which is created by the given factory, and assigned this block as + * its one and only valid block. + * + * + * The created [BlockEntityBuilder] is returned for further configuration. + * + * @param BE + * The type of the block entity + * @param factory + * A factory for the block entity + * @return the [BlockEntityBuilder] + */ + open fun blockEntity(factory: BlockEntityBuilder.BlockEntityFactory) = owner.blockEntity(this, name, factory).validBlock(asSupplier()) + + /** + * Registers the client color handler for all tint indices of this block. + * + * @param colorHandler A side-safe supplier of the client color handler + * @return this [BlockBuilder] + */ + open fun color(colorHandler: NonNullSupplier>): BlockBuilder { + if (this.colorHandler == null) { + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerBlockColor() } } + } + this.colorHandler = colorHandler + return this + } + + protected open fun registerBlockColor() { + addModListener( + owner, + RegisterColorHandlersEvent.Block::class.java, + Consumer { event: RegisterColorHandlersEvent.Block -> + val colorHandler = this.colorHandler + if (colorHandler != null) { + event.register(colorHandler.get().get(), entry) + } + }, + ) + } + + /** + * Assign the default blockstate, which maps all states to a single model file (via + * [RegistrateBlockModelGenerator.createTrivialCube]). This is the default, so it is generally not + * necessary + * to call, unless for undoing previous changes. + * + * @return this [BlockBuilder] + */ + open fun defaultBlockstate(): BlockBuilder = blockstate { + NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateBlockModelGenerator -> + prov.createTrivialCube( + ctx.entry, + ) + } + } + + /** + * Configure the blockstate/models for this block. + * + * @param cons + * The callback which will be invoked during data generation. + * @return this [BlockBuilder] + * @see .setData + */ + open fun blockstate(cons: NonNullSupplier, RegistrateBlockModelGenerator>>): BlockBuilder { + val blockstate: NonNullSupplier, RegistrateBlockModelGenerator>> = + cons.lazy() + return setData( + ProviderType.BLOCKSTATE, + ) { context: DataGenContext, generator: RegistrateBlockModelGenerator -> + blockstate.get().accept(context, generator) + } + } + + /** + * Assign the default translation, as specified by + * [RegistrateLangProvider.getAutomaticName]. This is + * the default, so it is generally + * not necessary to call, unless for undoing previous changes. + * + * @return this [BlockBuilder] + */ + open fun defaultLang(): BlockBuilder = lang { obj: T -> obj.descriptionId } + + /** Configures the source text and translations of this entry. */ + open fun localization(configure: Consumer): BlockBuilder = localization({ obj: T -> obj.descriptionId }, configure) + + /** + * Set the translation for this block. + * + * @param name + * A localized English name + * @return this [BlockBuilder] + */ + open fun lang(name: String): BlockBuilder = lang({ obj: T -> obj.descriptionId }, name) + + /** + * Assign the default loot table, as specified by [RegistrateBlockLootTables.dropSelf]. This is the + * default, so it is generally not necessary to call, unless for + * undoing previous changes. + * + * @return this [BlockBuilder] + */ + open fun defaultLoot(): BlockBuilder = loot { obj: RegistrateBlockLootTables, block: T -> obj.dropSelf(block) } + + /** + * Configure the loot table for this block. This is different than most data gen callbacks as the callback does not + * accept a [DataGenContext], but instead a + * [RegistrateBlockLootTables], for creating specifically block loot tables. + * + * + * If the block does not have a loot table (i.e. [Block.Properties.noLootTable] is called) this action will + * be *skipped*. + * + * @param cons + * The callback which will be invoked during block loot table creation. + * @return this [BlockBuilder] + */ + open fun loot(cons: NonNullBiConsumer) = setData( + ProviderType.LOOT, + ) { ctx: DataGenContext, prov: RegistrateLootTableProvider -> + prov.addLootAction( + RegistrateLootTableProvider.LootType.BLOCK, + ) { tb: RegistrateBlockLootTables -> + if (ctx.entry.lootTable !== BuiltInLootTables.EMPTY) { + cons.accept(tb, ctx.entry) + } + } + } + + /** + * Configure the recipe(s) for this block. + * + * @param cons + * The callback which will be invoked during data generation. + * @return this [BlockBuilder] + * @see .setData + */ + open fun recipe(cons: NonNullBiConsumer, RegistrateRecipeProvider>) = setData(ProviderType.RECIPE, cons) + + private var clientExtension: NonNullSupplier>? = null + + /** + * Register a client extension for this block. + * The [IClientBlockExtensions] instance can be shared across many items. + * + * @param clientExtension + * The client extension to register for this block + * @return this [BlockBuilder] + */ + open fun clientExtension(clientExtension: NonNullSupplier>): BlockBuilder { + if (this.clientExtension == null) { + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerClientExtension() } } + } + this.clientExtension = clientExtension + return this + } + + protected open fun registerClientExtension() { + addModListener( + owner, + RegisterClientExtensionsEvent::class.java, + Consumer { e: RegisterClientExtensionsEvent -> + val clientExtension = this.clientExtension + if (clientExtension != null) { + e.registerBlock(clientExtension.get().get(), entry) + } + }, + ) + } + + /** + * Assign [TagKey]`s` to this block. Multiple calls will add additional tags. + * + * @param tags + * The tags to assign + * @return this [BlockBuilder] + */ + @SafeVarargs + fun tag(vararg tags: TagKey) = tag(ProviderType.BLOCK_TAGS, *tags) + + override fun createEntry(): T { + var properties = this.initialProperties.get() + properties = propertiesCallback.apply(properties) + return factory.apply(properties) + } + + override fun createEntryWrapper(delegate: DeferredHolder) = BlockEntry(owner, delegate) + + override fun register(): BlockEntry = super.register() as BlockEntry + + companion object { + /** + * Create a new [BlockBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + * + * + * The block will be assigned the following data: + * + * * A default blockstate file mapping all states to one model (via [.defaultBlockstate]) + * * A simple cube_all model (used in the blockstate) with one texture (via [.defaultBlockstate]) + * * A self-dropping loot table (via [.defaultLoot]) + * * The default translation (via [.defaultLang]) + * + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the block + * @return A new [BlockBuilder] with reasonable default data generators. +

*/ + @JvmStatic + fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: NonNullFunction) = BlockBuilder( + owner, + parent, + name, + callback, + factory, + ) { BlockBehaviour.Properties.of() } + .defaultBlockstate().defaultLoot().defaultLang() + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java deleted file mode 100644 index e4ccc55..0000000 --- a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.modularmc.registrate.builders; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.builders.base.AbstractBuilder; -import com.modularmc.registrate.builders.base.BuilderCallback; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; -import com.modularmc.registrate.internal.util.RegistrateDistExecutor; -import com.modularmc.registrate.util.entry.BlockEntityEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullFunction; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; -import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; -import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; -import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.Registries; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; -import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; -import net.neoforged.neoforge.registries.DeferredHolder; - -import org.jspecify.annotations.Nullable; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Function; - -/** - * A builder for block entities, allows for customization of the valid blocks. - * - * @param - * The type of block entity being built - * @param

- * Parent object type - */ -public class BlockEntityBuilder extends AbstractBuilder, BlockEntityType, P, BlockEntityBuilder> { - - public interface BlockEntityFactory { - - T create(BlockEntityType type, BlockPos pos, BlockState state); - } - - /** - * Create a new {@link BlockEntityBuilder} and configure data. Used in lieu of adding side-effects to constructor, - * so that alternate initialization strategies can be done in subclasses. - *

- * The block entity will be assigned the following data: - * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the block entity - * @return A new {@link BlockEntityBuilder} with reasonable default data generators. - */ - public static BlockEntityBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, BlockEntityFactory factory) { - return new BlockEntityBuilder<>(owner, parent, name, callback, factory); - } - - private final BlockEntityFactory factory; - private final Set> validBlocks = new HashSet<>(); - private @Nullable NonNullSupplier>> renderer; - - protected BlockEntityBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, BlockEntityFactory factory) { - super(owner, parent, name, callback, Registries.BLOCK_ENTITY_TYPE); - this.factory = factory; - } - - /** - * Add a valid block for this block entity. - * - * @param block - * A supplier for the block to add at registration time - * @return this {@link BlockEntityBuilder} - */ - public BlockEntityBuilder validBlock(NonNullSupplier block) { - validBlocks.add(block); - return this; - } - - /** - * Add valid blocks for this block entity. - * - * @param blocks - * An array of suppliers for the block to add at registration time - * @return this {@link BlockEntityBuilder} - */ - @SafeVarargs - public final BlockEntityBuilder validBlocks(NonNullSupplier... blocks) { - Arrays.stream(blocks).forEach(this::validBlock); - return this; - } - - /** - * Register an {@link BlockEntityRenderer} for this block entity. - *

- * - * @apiNote This requires the {@link Class} of the block entity object, which can only be gotten by inspecting an - * instance of it. Thus, the entity will be constructed to register the renderer. - * - * @param renderer - * A (server safe) supplier to an {@link Function} that will provide this block entity's renderer - * given the renderer dispatcher - * @return this {@link BlockEntityBuilder} - */ - public BlockEntityBuilder renderer(NonNullSupplier>> renderer) { - if (this.renderer == null) { // First call only - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerRenderer); - } - this.renderer = renderer; - return this; - } - - protected void registerRenderer() { - OneTimeEventReceiver.addModListener(getOwner(), FMLClientSetupEvent.class, $ -> { - var renderer = this.renderer; - if (renderer != null) { - BlockEntityRenderers.register(getEntry(), renderer.get()::apply); - } - }); - } - - /** - * Register {@link net.neoforged.neoforge.capabilities.Capabilities} for this block entity. - * - * @param registerCapabilitiesEvent A consumer for the register capabilities event - * @return this {@link BlockEntityBuilder} - */ - public BlockEntityBuilder registerCapability(Consumer registerCapabilitiesEvent) { - OneTimeEventReceiver.addModListener(getOwner(), RegisterCapabilitiesEvent.class, registerCapabilitiesEvent); - return this; - } - - @Override - protected BlockEntityType createEntry() { - BlockEntityFactory factory = this.factory; - final var supplier = asSupplier(); - return BlockEntityType.Builder.of( - (pos, state) -> factory.create(supplier.get(), pos, state), - validBlocks.stream().map(NonNullSupplier::get).toArray(Block[]::new)).build(null); - } - - @Override - protected RegistryEntry, BlockEntityType> createEntryWrapper(DeferredHolder, BlockEntityType> delegate) { - return new BlockEntityEntry<>(getOwner(), delegate); - } - - @Override - public BlockEntityEntry register() { - return (BlockEntityEntry) super.register(); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt new file mode 100644 index 0000000..1036f95 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/BlockEntityBuilder.kt @@ -0,0 +1,179 @@ +package com.modularmc.registrate.builders + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.builders.base.AbstractBuilder +import com.modularmc.registrate.builders.base.BuilderCallback +import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener +import com.modularmc.registrate.internal.util.RegistrateDistExecutor.unsafeRunWhenOn +import com.modularmc.registrate.util.entry.BlockEntityEntry +import com.modularmc.registrate.util.nullness.NonNullFunction +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer +import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider +import net.minecraft.client.renderer.blockentity.BlockEntityRenderers +import net.minecraft.core.BlockPos +import net.minecraft.core.registries.Registries +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.block.entity.BlockEntity +import net.minecraft.world.level.block.entity.BlockEntityType +import net.minecraft.world.level.block.state.BlockState +import net.neoforged.api.distmarker.Dist +import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent +import net.neoforged.neoforge.capabilities.Capabilities +import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent +import net.neoforged.neoforge.registries.DeferredHolder + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.function.Consumer + +/** + * A builder for block entities, allows for customization of the valid blocks. + * + * @param T + * The type of block entity being built + * @param P + * Parent object type + */ +open class BlockEntityBuilder protected constructor( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + private val factory: BlockEntityFactory, +) : AbstractBuilder, BlockEntityType, P, BlockEntityBuilder>( + owner, + parent, + name, + callback, + Registries.BLOCK_ENTITY_TYPE, +) { + fun interface BlockEntityFactory { + fun create(type: BlockEntityType, pos: BlockPos, state: BlockState): T + } + + private val validBlocks = ObjectOpenHashSet>() + private var renderer: NonNullSupplier>>? = + null + + /** + * Add a valid block for this block entity. + * + * @param block + * A supplier for the block to add at registration time + * @return this [BlockEntityBuilder] + */ + open fun validBlock(block: NonNullSupplier): BlockEntityBuilder { + validBlocks.add(block) + return this + } + + /** + * Add valid blocks for this block entity. + * + * @param blocks + * An array of suppliers for the block to add at registration time + * @return this [BlockEntityBuilder] + */ + @SafeVarargs + fun validBlocks(vararg blocks: NonNullSupplier): BlockEntityBuilder { + validBlocks.addAll(blocks.asList()) + return this + } + + /** + * Register an [BlockEntityRenderer] for this block entity. + * + * + * + * @apiNote This requires the [Class] of the block entity object, which can only be gotten by inspecting an + * instance of it. Thus, the entity will be constructed to register the renderer. + * + * @param renderer + * A (server safe) supplier to an [Function] that will provide this block entity's renderer + * given the renderer dispatcher + * @return this [BlockEntityBuilder] + */ + open fun renderer(renderer: NonNullSupplier>>): BlockEntityBuilder { + if (this.renderer == null) { // First call only + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerRenderer() } } + } + this.renderer = renderer + return this + } + + protected open fun registerRenderer() { + addModListener( + owner, + FMLClientSetupEvent::class.java, + Consumer { `$`: FMLClientSetupEvent -> + val renderer: NonNullSupplier>>? = + this.renderer + if (renderer != null) { + BlockEntityRenderers.register( + entry, + ) { t: BlockEntityRendererProvider.Context? -> + renderer.get().apply(t!!) + } + } + }, + ) + } + + /** + * Register [Capabilities] for this block entity. + * + * @param registerCapabilitiesEvent A consumer for the register capabilities event + * @return this [BlockEntityBuilder] + */ + open fun registerCapability(registerCapabilitiesEvent: Consumer): BlockEntityBuilder { + addModListener( + owner, + RegisterCapabilitiesEvent::class.java, + registerCapabilitiesEvent, + ) + return this + } + + override fun createEntry(): BlockEntityType { + val factory: BlockEntityFactory = this.factory + val supplier: NonNullSupplier> = asSupplier() + val blocks = validBlocks.iterator() + val valid = Array(validBlocks.size) { blocks.next().get() } + return BlockEntityType.Builder.of({ pos, state -> factory.create(supplier.get(), pos, state) }, *valid).build(null) + } + + override fun createEntryWrapper(delegate: DeferredHolder, BlockEntityType>) = BlockEntityEntry(owner, delegate) + + override fun register(): BlockEntityEntry = super.register() as BlockEntityEntry + + companion object { + /** + * Create a new [BlockEntityBuilder] and configure data. Used in lieu of adding side-effects to constructor, + * so that alternate initialization strategies can be done in subclasses. + * + * + * The block entity will be assigned the following data: + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the block entity + * @return A new [BlockEntityBuilder] with reasonable default data generators. +

*/ + @JvmStatic + fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: BlockEntityFactory) = + BlockEntityBuilder(owner, parent, name, callback, factory) + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java deleted file mode 100644 index 7ba4aa6..0000000 --- a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.java +++ /dev/null @@ -1,300 +0,0 @@ -package com.modularmc.registrate.builders; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.builders.base.AbstractBuilder; -import com.modularmc.registrate.builders.base.BuilderCallback; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; -import com.modularmc.registrate.internal.util.RegistrateDistExecutor; -import com.modularmc.registrate.providers.DataGenContext; -import com.modularmc.registrate.providers.RegistrateLangProvider; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.loot.RegistrateEntityLootTables; -import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider.LootType; -import com.modularmc.registrate.util.entry.EntityEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullBiConsumer; -import com.modularmc.registrate.util.nullness.NonNullConsumer; -import com.modularmc.registrate.util.nullness.NonNullFunction; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.client.renderer.entity.EntityRenderer; -import net.minecraft.client.renderer.entity.EntityRendererProvider; -import net.minecraft.core.registries.Registries; -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.*; -import net.minecraft.world.entity.SpawnPlacements.SpawnPredicate; -import net.minecraft.world.entity.ai.attributes.AttributeSupplier; -import net.minecraft.world.item.CreativeModeTabs; -import net.minecraft.world.item.SpawnEggItem; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.levelgen.Heightmap; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.neoforge.client.event.EntityRenderersEvent; -import net.neoforged.neoforge.common.DeferredSpawnEggItem; -import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent; -import net.neoforged.neoforge.event.entity.RegisterSpawnPlacementsEvent; -import net.neoforged.neoforge.registries.DeferredHolder; - -import org.jspecify.annotations.Nullable; - -import java.util.function.Supplier; - -/** - * A builder for entities, allows for customization of the {@link EntityType.Builder}, easy creation of spawn egg items, - * and configuration of data associated with entities (loot tables, etc.). - * - * @param - * The type of entity being built - * @param

- * Parent object type - */ -public class EntityBuilder extends AbstractBuilder, EntityType, P, EntityBuilder> { - - /** - * Create a new {@link EntityBuilder} and configure data. Used in lieu of adding side-effects to constructor, so - * that alternate initialization strategies can be done in subclasses. - *

- * The entity will be assigned the following data: - *

    - *
  • The default translation (via {@link #defaultLang()})
  • - *
- * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the entity - * @param classification - * The {@link MobCategory} of the entity - * @return A new {@link EntityBuilder} with reasonable default data generators. - */ - public static EntityBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, EntityType.EntityFactory factory, - MobCategory classification) { - return new EntityBuilder<>(owner, parent, name, callback, factory, classification) - .defaultLang(); - } - - private final NonNullSupplier> builder; - - private NonNullConsumer> builderCallback = $ -> {}; - - private @Nullable NonNullSupplier>> renderer; - - private boolean attributesConfigured, spawnConfigured; - - protected EntityBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, EntityType.EntityFactory factory, MobCategory classification) { - super(owner, parent, name, callback, Registries.ENTITY_TYPE); - this.builder = () -> EntityType.Builder.of(factory, classification); - } - - /** - * Modify the properties of the entity. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. - * - * @param cons - * The action to perform on the properties - * @return this {@link EntityBuilder} - */ - public EntityBuilder properties(NonNullConsumer> cons) { - builderCallback = builderCallback.andThen(cons); - return this; - } - - /** - * Register an {@link EntityRenderer} for this entity. - *

- * - * @param renderer - * A (server safe) supplier to an {@link EntityRendererProvider} that will provide this entity's - * renderer - * @return this {@link EntityBuilder} - */ - public EntityBuilder renderer(NonNullSupplier>> renderer) { - if (this.renderer == null) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerRenderer); - } - this.renderer = renderer; - return this; - } - - protected void registerRenderer() { - OneTimeEventReceiver.addModListener(getOwner(), EntityRenderersEvent.RegisterRenderers.class, evt -> { - var renderer = this.renderer; - if (renderer != null) { - try { - var provider = renderer.get(); - evt.registerEntityRenderer(getEntry(), provider::apply); - } catch (Exception e) { - throw new IllegalStateException("Failed to register renderer for Entity " + get().getId(), e); - } - } - }); - } - - /** - * Register a attributes for this entity. The entity must extend {@link LivingEntity}. - *

- * Cannot be called more than once per builder. - * - * @param attributes - * A supplier to the attributes for this entity, usually of the form - * {@code EntityClass::createAttributes} - * @return this {@link EntityBuilder} - * @throws IllegalStateException - * When called more than once - */ - @SuppressWarnings("unchecked") - public EntityBuilder attributes(Supplier attributes) { - if (attributesConfigured) { - throw new IllegalStateException("Cannot configure attributes more than once"); - } - attributesConfigured = true; - OneTimeEventReceiver.addModListener(getOwner(), EntityAttributeCreationEvent.class, e -> e.put((EntityType) getEntry(), attributes.get().build())); - return this; - } - - /** - * Register a spawn placement for this entity. The entity must extend {@link Mob} and allow construction with a - * {@code null} {@link Level}. - *

- * Cannot be called more than once per builder. - * - * @param type - * The type of placement to use - * @param heightmap - * Which heightmap to use to choose placement locations - * @param predicate - * A predicate to check spawn locations for validity - * @return this {@link EntityBuilder} - * @throws IllegalStateException - * When called more than once - */ - @SuppressWarnings("unchecked") - public EntityBuilder spawnPlacement(SpawnPlacementType type, Heightmap.Types heightmap, SpawnPredicate predicate, RegisterSpawnPlacementsEvent.Operation operation) { - if (spawnConfigured) { - throw new IllegalStateException("Cannot configure spawn placement more than once"); - } - spawnConfigured = true; - this.onRegister(t -> { - OneTimeEventReceiver.addModListener(getOwner(), RegisterSpawnPlacementsEvent.class, e -> { - e.register(t, type, heightmap, predicate, operation); - }); - }); - return this; - } - - /** - * Create a spawn egg item for this entity and build it immediately. - * - * @return this {@link EntityBuilder} - */ - public EntityBuilder spawnEgg() { - return spawnEgg($ -> {}); - } - - /** - * Create a spawn egg item for this entity and expose its builder for further customization. - * - *

- * The egg resolves the entity after registration and uses the standard spawn egg model by default. - * - * @param consumer - * A callback for customizing the nested egg {@link ItemBuilder} - * @return this {@link EntityBuilder} - */ - public EntityBuilder spawnEgg(NonNullConsumer>> consumer) { - return spawnEgg(0xFFFFFF, 0xFFFFFF, consumer); - } - - /** - * Registers a spawn egg with the given base and highlight colors and configures it before registration. - */ - @SuppressWarnings("unchecked") - public EntityBuilder spawnEgg(int baseColor, int highlightColor, NonNullConsumer>> consumer) { - NonNullSupplier> entityType = asSupplier(); - // NeoForge's deferred egg API accepts a mob factory. Registrate resolves the type after the item registry runs. - Supplier> mobType = (Supplier>) (Supplier) entityType; - ItemBuilder> eggBuilder = getOwner() - .>item(this, getName() + "_spawn_egg", - properties -> new DeferredSpawnEggItem(mobType, baseColor, highlightColor, properties)) - .model(() -> (ctx, prov) -> prov.createWithExistingModel(ctx.get(), prov.mcLoc("item/template_spawn_egg"))) - .tab(CreativeModeTabs.SPAWN_EGGS); - consumer.accept(eggBuilder); - return eggBuilder.build(); - } - - /** - * Assign the default translation, as specified by - * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, net.minecraft.resources.ResourceKey)}. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. - * - * @return this {@link EntityBuilder} - */ - public EntityBuilder defaultLang() { - return lang(EntityType::getDescriptionId); - } - - /** - * Set the translation for this entity. - * - * @param name - * A localized English name - * @return this {@link EntityBuilder} - */ - public EntityBuilder lang(String name) { - return lang(EntityType::getDescriptionId, name); - } - - /** - * Configure the loot table for this entity. This is different than most data gen callbacks as the callback does not - * accept a {@link DataGenContext}, but instead a - * {@link RegistrateEntityLootTables}, for creating specifically entity loot tables. - * - * @param cons - * The callback which will be invoked during entity loot table creation. - * @return this {@link EntityBuilder} - */ - public EntityBuilder loot(NonNullBiConsumer> cons) { - return setData(ProviderType.LOOT, (ctx, prov) -> prov.addLootAction(LootType.ENTITY, tb -> cons.accept(tb, ctx.getEntry()))); - } - - /** - * Assign {@link TagKey}{@code s} to this entity. Multiple calls will add additional tags. - * - * @param tags - * The tags to assign - * @return this {@link EntityBuilder} - */ - @SafeVarargs - public final EntityBuilder tag(TagKey>... tags) { - return tag(ProviderType.ENTITY_TAGS, tags); - } - - @Override - protected EntityType createEntry() { - EntityType.Builder builder = this.builder.get(); - builderCallback.accept(builder); - return builder.build(getResourceKey().location().toString()); - } - - @Override - protected RegistryEntry, EntityType> createEntryWrapper(DeferredHolder, EntityType> delegate) { - return new EntityEntry<>(getOwner(), delegate); - } - - @Override - public EntityEntry register() { - return (EntityEntry) super.register(); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt new file mode 100644 index 0000000..5406e27 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/EntityBuilder.kt @@ -0,0 +1,326 @@ +// Keep the Java overload signatures while formatting the Kotlin declarations. +@file:Suppress("ktlint:standard:max-line-length") + +package com.modularmc.registrate.builders + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.builders.base.AbstractBuilder +import com.modularmc.registrate.builders.base.BuilderCallback +import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener +import com.modularmc.registrate.internal.util.RegistrateDistExecutor.unsafeRunWhenOn +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.providers.DataGenContext +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator +import com.modularmc.registrate.providers.loot.RegistrateEntityLootTables +import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider +import com.modularmc.registrate.util.entry.EntityEntry +import com.modularmc.registrate.util.nullness.NonNullBiConsumer +import com.modularmc.registrate.util.nullness.NonNullConsumer +import com.modularmc.registrate.util.nullness.NonNullFunction +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.client.renderer.entity.EntityRenderer +import net.minecraft.client.renderer.entity.EntityRendererProvider +import net.minecraft.core.registries.Registries +import net.minecraft.tags.TagKey +import net.minecraft.world.entity.* +import net.minecraft.world.entity.EntityType.EntityFactory +import net.minecraft.world.entity.ai.attributes.AttributeSupplier +import net.minecraft.world.item.CreativeModeTabs +import net.minecraft.world.item.Item +import net.minecraft.world.item.SpawnEggItem +import net.minecraft.world.level.levelgen.Heightmap +import net.neoforged.api.distmarker.Dist +import net.neoforged.neoforge.client.event.EntityRenderersEvent.RegisterRenderers +import net.neoforged.neoforge.common.DeferredSpawnEggItem +import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent +import net.neoforged.neoforge.event.entity.RegisterSpawnPlacementsEvent +import net.neoforged.neoforge.registries.DeferredHolder + +import java.util.function.Consumer +import java.util.function.Supplier + +/** + * A builder for entities, allows for customization of the [EntityType.Builder], easy creation of spawn egg items, + * and configuration of data associated with entities (loot tables, etc.). + * + * @param T + * The type of entity being built + * @param P + * Parent object type + */ +open class EntityBuilder protected constructor( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + factory: EntityFactory, + classification: MobCategory, +) : AbstractBuilder, EntityType, P, EntityBuilder>( + owner, + parent, + name, + callback, + Registries.ENTITY_TYPE, +) { + private val builder: NonNullSupplier> = + NonNullSupplier { EntityType.Builder.of(factory, classification) } + + private var builderCallback = NonNullConsumer { `$`: EntityType.Builder -> } + + private var renderer: NonNullSupplier>>? = + null + + private var attributesConfigured = false + private var spawnConfigured = false + + /** + * Modify the properties of the entity. Modifications are done lazily, but the passed function is composed with the + * current one, and as such this method can be called multiple times to perform + * different operations. + * + * @param cons + * The action to perform on the properties + * @return this [EntityBuilder] + */ + open fun properties(cons: NonNullConsumer>): EntityBuilder { + builderCallback = builderCallback.andThen(cons) + return this + } + + /** + * Register an [EntityRenderer] for this entity. + * + * + * + * @param renderer + * A (server safe) supplier to an [EntityRendererProvider] that will provide this entity's + * renderer + * @return this [EntityBuilder] + */ + open fun renderer(renderer: NonNullSupplier>>): EntityBuilder { + if (this.renderer == null) { + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerRenderer() } } + } + this.renderer = renderer + return this + } + + protected open fun registerRenderer() { + addModListener( + owner, + RegisterRenderers::class.java, + Consumer { evt: RegisterRenderers -> + val renderer: NonNullSupplier>>? = + this.renderer + if (renderer != null) { + try { + val provider = renderer.get() + evt.registerEntityRenderer(entry) { context -> provider.apply(context) } + } catch (e: Exception) { + throw IllegalStateException("Failed to register renderer for Entity " + get().id, e) + } + } + }, + ) + } + + /** + * Register a attributes for this entity. The entity must extend [LivingEntity]. + * + * + * Cannot be called more than once per builder. + * + * @param attributes + * A supplier to the attributes for this entity, usually of the form + * `EntityClass::createAttributes` + * @return this [EntityBuilder] + * @throws IllegalStateException + * When called more than once + */ + open fun attributes(attributes: Supplier): EntityBuilder { + check(!attributesConfigured) { "Cannot configure attributes more than once" } + attributesConfigured = true + addModListener( + owner, + EntityAttributeCreationEvent::class.java, + Consumer { e: EntityAttributeCreationEvent -> + e.put( + entry as EntityType, + attributes.get().build(), + ) + }, + ) + return this + } + + /** + * Register a spawn placement for this entity. The entity must extend [Mob] and allow construction with a + * `null` [net.minecraft.world.level.Level]. + * + * + * Cannot be called more than once per builder. + * + * @param type + * The type of placement to use + * @param heightmap + * Which heightmap to use to choose placement locations + * @param predicate + * A predicate to check spawn locations for validity + * @return this [EntityBuilder] + * @throws IllegalStateException + * When called more than once + */ + open fun spawnPlacement( + type: SpawnPlacementType, + heightmap: Heightmap.Types, + predicate: SpawnPlacements.SpawnPredicate, + operation: RegisterSpawnPlacementsEvent.Operation, + ): EntityBuilder { + check(!spawnConfigured) { "Cannot configure spawn placement more than once" } + spawnConfigured = true + this.onRegister( + NonNullConsumer { t: EntityType? -> + addModListener( + owner, + RegisterSpawnPlacementsEvent::class.java, + Consumer { e: RegisterSpawnPlacementsEvent -> + e.register(t, type, heightmap, predicate, operation) + }, + ) + }, + ) + return this + } + + /** Registers a spawn egg using the given customization callback and standard model. */ + @JvmOverloads + open fun spawnEgg(consumer: NonNullConsumer>> = NonNullConsumer.noop()): EntityBuilder = spawnEgg(0xFFFFFF, 0xFFFFFF, consumer) + + /** + * Registers a spawn egg with the given base and highlight colors and configures it before registration. + */ + open fun spawnEgg(baseColor: Int, highlightColor: Int, consumer: NonNullConsumer>>): EntityBuilder { + val entityType: NonNullSupplier> = asSupplier() + // NeoForge's deferred egg API accepts a mob factory. Registrate resolves the type after the item registry runs. + val mobType = entityType as Supplier<*> as Supplier> + val eggBuilder = owner + .item>( + this, + name + "_spawn_egg", + ) { properties: Item.Properties -> + DeferredSpawnEggItem( + mobType, + baseColor, + highlightColor, + properties, + ) + } + .model { + NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateItemModelGenerator -> + prov.createWithExistingModel( + ctx.get(), + prov.mcLoc("item/template_spawn_egg"), + ) + } + } + .tab(CreativeModeTabs.SPAWN_EGGS) + consumer.accept(eggBuilder) + return eggBuilder.build() + } + + /** + * Assign the default translation, as specified by + * [com.modularmc.registrate.providers.RegistrateLangProvider.getAutomaticName]. This is + * the default, so it is generally + * not necessary to call, unless for undoing previous changes. + * + * @return this [EntityBuilder] + */ + open fun defaultLang(): EntityBuilder = lang { obj: EntityType -> obj.descriptionId } + + /** Configures the source text and translations of this entry. */ + open fun localization(configure: Consumer): EntityBuilder = localization({ obj: EntityType -> obj.descriptionId }, configure) + + /** + * Set the translation for this entity. + * + * @param name + * A localized English name + * @return this [EntityBuilder] + */ + open fun lang(name: String): EntityBuilder = lang({ obj: EntityType -> obj.descriptionId }, name) + + /** + * Configure the loot table for this entity. This is different than most data gen callbacks as the callback does not + * accept a [DataGenContext], but instead a + * [RegistrateEntityLootTables], for creating specifically entity loot tables. + * + * @param cons + * The callback which will be invoked during entity loot table creation. + * @return this [EntityBuilder] + */ + open fun loot(cons: NonNullBiConsumer>) = setData( + ProviderType.LOOT, + ) { ctx: DataGenContext, EntityType>, prov: RegistrateLootTableProvider -> + prov.addLootAction( + RegistrateLootTableProvider.LootType.ENTITY, + ) { tb: RegistrateEntityLootTables -> cons.accept(tb, ctx.entry) } + } + + /** + * Assign [TagKey]`s` to this entity. Multiple calls will add additional tags. + * + * @param tags + * The tags to assign + * @return this [EntityBuilder] + */ + @SafeVarargs + fun tag(vararg tags: TagKey>) = tag(ProviderType.ENTITY_TAGS, *tags) + + override fun createEntry(): EntityType { + val builder: EntityType.Builder = this.builder.get() + builderCallback.accept(builder) + return builder.build(resourceKey.location().toString()) + } + + override fun createEntryWrapper(delegate: DeferredHolder, EntityType>) = EntityEntry(owner, delegate) + + override fun register(): EntityEntry = super.register() as EntityEntry + + companion object { + /** + * Create a new [EntityBuilder] and configure data. Used in lieu of adding side-effects to constructor, so + * that alternate initialization strategies can be done in subclasses. + * + * + * The entity will be assigned the following data: + * + * * The default translation (via [.defaultLang]) + * + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the entity + * @param classification + * The [MobCategory] of the entity + * @return A new [EntityBuilder] with reasonable default data generators. +

*/ + @JvmStatic + fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: EntityFactory, classification: MobCategory) = + EntityBuilder(owner, parent, name, callback, factory, classification) + .defaultLang() + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java deleted file mode 100644 index 01a2a26..0000000 --- a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.java +++ /dev/null @@ -1,647 +0,0 @@ -package com.modularmc.registrate.builders; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.builders.base.AbstractBuilder; -import com.modularmc.registrate.builders.base.BuilderCallback; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; -import com.modularmc.registrate.internal.util.RegistrateDistExecutor; -import com.modularmc.registrate.providers.RegistrateLangProvider; -import com.modularmc.registrate.providers.RegistrateTagsProvider; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.util.entry.FluidEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.*; - -import net.minecraft.Util; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.BucketItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.LiquidBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Fluid; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; -import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; -import net.neoforged.neoforge.client.model.DynamicFluidContainerModel.Colors; -import net.neoforged.neoforge.common.util.Lazy; -import net.neoforged.neoforge.fluids.BaseFlowingFluid; -import net.neoforged.neoforge.fluids.FluidType; -import net.neoforged.neoforge.registries.DeferredHolder; -import net.neoforged.neoforge.registries.NeoForgeRegistries; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.function.Supplier; -import java.util.function.ToIntFunction; - -public class FluidBuilder extends AbstractBuilder> { - - @FunctionalInterface - public interface FluidTypeFactory { - - FluidType create(FluidType.Properties properties); - } - - @FunctionalInterface - public interface FluidFactory { - - T create(BaseFlowingFluid.Properties properties); - } - - private record FluidTextures(ResourceLocation still, ResourceLocation flowing) {} - - private @Nullable FluidTextures textures; - private @Nullable NonNullSupplier> clientExtension; - - /** - * Supplies the client extension for this fluid type. The extension controls its textures, tint and overlays. - * - * @param clientExtension the side-safe supplier of the client extension - * @return this fluid builder - */ - public FluidBuilder clientExtension(NonNullSupplier> clientExtension) { - if (this.clientExtension == null && !(registerType && textures != null)) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); - } - this.clientExtension = clientExtension; - return this; - } - - /** - * Sets the block particle texture and the default client textures for a fluid type registered by this builder. - * A shared fluid type supplied to the builder uses its own client extension. - */ - public FluidBuilder model(ResourceLocation stillTexture, ResourceLocation flowingTexture) { - if (textures == null && registerType && clientExtension == null) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); - } - textures = new FluidTextures(stillTexture, flowingTexture); - return this; - } - - protected void registerClientExtension() { - OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, event -> { - var custom = clientExtension; - var fluidTextures = textures; - if (custom != null) { - event.registerFluidType(custom.get().get(), fluidType.get()); - } else if (fluidTextures != null) { - event.registerFluidType(new IClientFluidTypeExtensions() { - - @Override - public ResourceLocation getStillTexture() { - return fluidTextures.still(); - } - - @Override - public ResourceLocation getFlowingTexture() { - return fluidTextures.flowing(); - } - }, fluidType.get()); - } - }); - } - - /** - * Create a new {@link FluidBuilder} and configure data. The created builder will use a default ({@link FluidType}) - * and fluid class ({@link BaseFlowingFluid.Flowing}). - * - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @return A new {@link FluidBuilder} with reasonable default data generators. - * @see #create(AbstractRegistrate, Object, String, BuilderCallback, FluidTypeFactory, FluidFactory) - */ - public static

FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback) { - return create(owner, parent, name, callback, FluidType::new, BaseFlowingFluid.Flowing::new); - } - - /** - * Create a new {@link FluidBuilder} and configure data. The created builder will use a default fluid class - * ({@link BaseFlowingFluid.Flowing}). - * - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param typeFactory - * A factory that creates the fluid type - * @return A new {@link FluidBuilder} with reasonable default data generators. - * @see #create(AbstractRegistrate, Object, String, BuilderCallback, FluidTypeFactory, FluidFactory) - */ - public static

FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, FluidTypeFactory typeFactory) { - return create(owner, parent, name, callback, typeFactory, BaseFlowingFluid.Flowing::new); - } - - /** - * Create a new {@link FluidBuilder} and configure data. The created builder will use a default fluid class - * ({@link BaseFlowingFluid.Flowing}). - * - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidType - * An existing and registered fluid type. - * @return A new {@link FluidBuilder} with reasonable default data generators. - * @see #create(AbstractRegistrate, Object, String, BuilderCallback, FluidTypeFactory, FluidFactory) - */ - public static

FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullSupplier fluidType) { - return create(owner, parent, name, callback, p -> fluidType.get(), BaseFlowingFluid.Flowing::new); - } - - /** - * Create a new {@link FluidBuilder} and configure data. The created builder will use a default ({@link FluidType}) - * and fluid class ({@link BaseFlowingFluid.Flowing}). - * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new {@link FluidBuilder} with reasonable default data generators. - */ - public static FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, - FluidFactory fluidFactory) { - return create(owner, parent, name, callback, FluidType::new, fluidFactory); - } - - /** - * Create a new {@link FluidBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - *

- * The fluid will be assigned the following data: - *

    - *
  • The default translation (via {@link #defaultLang()})
  • - *
  • A default {@link BaseFlowingFluid.Source source fluid} (via {@link #defaultSource})
  • - *
  • A default block for the fluid, with its own default blockstate and model that configure the particle texture - * (via {@link #defaultBlock()})
  • - *
  • A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid - * (via {@link #defaultBucket()})
  • - *
- * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param typeFactory - * A factory that creates the fluid type - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new {@link FluidBuilder} with reasonable default data generators. - */ - public static FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, - FluidTypeFactory typeFactory, FluidFactory fluidFactory) { - FluidBuilder ret = new FluidBuilder<>(owner, parent, name, callback, typeFactory, fluidFactory) - .defaultLang().defaultSource().defaultBlock().defaultBucket(); - return ret; - } - - /** - * Create a new {@link FluidBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - *

- * The fluid will be assigned the following data: - *

    - *
  • The default translation (via {@link #defaultLang()})
  • - *
  • A default {@link BaseFlowingFluid.Source source fluid} (via {@link #defaultSource})
  • - *
  • A default block for the fluid, with its own default blockstate and model that configure the particle texture - * (via {@link #defaultBlock()})
  • - *
  • A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid - * (via {@link #defaultBucket()})
  • - *
- * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param fluidType - * An existing and registered fluid type - * @param fluidFactory - * A factory that creates the flowing fluid - * @return A new {@link FluidBuilder} with reasonable default data generators. - */ - public static FluidBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, - NonNullSupplier fluidType, FluidFactory fluidFactory) { - return new FluidBuilder<>(owner, parent, name, callback, fluidType, fluidFactory) - .defaultLang().defaultSource().defaultBlock().defaultBucket(); - } - - private final String sourceName, bucketName; - - private final FluidFactory fluidFactory; - - private final NonNullSupplier fluidType; - - private @Nullable Boolean defaultSource, defaultBlock, defaultBucket; - - private NonNullConsumer typeProperties = $ -> {}; - - private NonNullConsumer fluidProperties = $ -> {}; - - private final boolean registerType; - - private @Nullable NonNullSupplier source; - private final List> tags = new ArrayList<>(); - - public FluidBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, FluidTypeFactory typeFactory, FluidFactory fluidFactory) { - super(owner, parent, "flowing_" + name, callback, Registries.FLUID); - this.sourceName = name; - this.bucketName = name + "_bucket"; - this.fluidFactory = fluidFactory; - this.fluidType = NonNullSupplier.lazy(() -> typeFactory.create(makeTypeProperties())); - this.registerType = true; - } - - public FluidBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullSupplier fluidType, FluidFactory fluidFactory) { - super(owner, parent, "flowing_" + name, callback, Registries.FLUID); - this.sourceName = name; - this.bucketName = name + "_bucket"; - this.fluidFactory = fluidFactory; - this.fluidType = fluidType; - this.registerType = false; // Don't register if we have a fluid from outside. - } - - /** - * Modify the properties of the fluid type. Modifications are done lazily, but the passed function is composed with - * the current one, and as such this method can be called multiple times to perform - * different operations. - * - * @param cons - * The action to perform on the attributes - * @return this {@link FluidBuilder} - */ - public FluidBuilder properties(NonNullConsumer cons) { - typeProperties = typeProperties.andThen(cons); - return this; - } - - /** - * Modify the properties of the flowing fluid. Modifications are done lazily, but the passed function is composed - * with the current one, and as such this method can be called multiple times to perform - * different operations. - * - * @param cons - * The action to perform on the attributes - * @return this {@link FluidBuilder} - */ - public FluidBuilder fluidProperties(NonNullConsumer cons) { - fluidProperties = fluidProperties.andThen(cons); - return this; - } - - /** - * Assign the default translation, as specified by {@link RegistrateLangProvider#toEnglishName(String)}. This is the - * default, so it is generally not necessary to call, unless for - * undoing previous changes. - * - * @return this {@link FluidBuilder} - */ - public FluidBuilder defaultLang() { - return lang(f -> f.getFluidType().getDescriptionId(), RegistrateLangProvider.toEnglishName(sourceName)); - } - - /** - * Set the translation for this fluid. - * - * @param name - * A localized English name - * @return this {@link FluidBuilder} - */ - public FluidBuilder lang(String name) { - return lang(f -> f.getFluidType().getDescriptionId(), name); - } - - /** - * Create a standard {@link BaseFlowingFluid.Source} for this fluid which will be built and registered along with - * this fluid. - * - * @return this {@link FluidBuilder} - * @see #source(NonNullFunction) - * @throws IllegalStateException - * If {@link #source(NonNullFunction)} has been called before this method - */ - public FluidBuilder defaultSource() { - if (this.defaultSource != null) { - throw new IllegalStateException("Cannot set a default source after a custom source has been created"); - } - this.defaultSource = true; - return this; - } - - /** - * Create a {@link BaseFlowingFluid} for this fluid, which is created by the given factory, and which will be built - * and registered along with this fluid. - * - * @param factory - * A factory for the fluid, which accepts the properties and returns a new fluid - * @return this {@link FluidBuilder} - */ - public FluidBuilder source(NonNullFunction factory) { - this.defaultSource = false; - this.source = NonNullSupplier.lazy(() -> factory.apply(makeProperties())); - return this; - } - - /** - * Create a standard {@link LiquidBlock} for this fluid, building it immediately, and not allowing for further - * configuration. - * - * @return this {@link FluidBuilder} - * @see #block() - * @throws IllegalStateException - * If {@link #block()} or {@link #block(NonNullBiFunction)} has been called before - * this method - */ - public FluidBuilder defaultBlock() { - if (this.defaultBlock != null) { - throw new IllegalStateException("Cannot set a default block after a custom block has been created"); - } - this.defaultBlock = true; - return this; - } - - /** - * Create a standard {@link LiquidBlock} for this fluid, and return the builder for it so that further customization - * can be done. - * - * @return the {@link BlockBuilder} for the {@link LiquidBlock} - */ - public BlockBuilder> block() { - return block(LiquidBlock::new); - } - - /** - * Create a {@link LiquidBlock} for this fluid, which is created by the given factory, and return the builder for it - * so that further customization can be done. - * - * @param - * The type of the block - * @param factory - * A factory for the block, which accepts the block object and properties and returns a new block - * @return the {@link BlockBuilder} for the {@link LiquidBlock} - */ - public BlockBuilder> block(NonNullBiFunction factory) { - if (this.defaultBlock == Boolean.FALSE) { - throw new IllegalStateException("Only one call to block/noBlock per builder allowed"); - } - this.defaultBlock = false; - final NonNullSupplier supplier = asSupplier(); - final var lightLevel = Lazy.of(() -> fluidType.get().getLightLevel()); - final ToIntFunction lightLevelInt = $ -> lightLevel.get(); - final var ret = getOwner().>block(this, sourceName, p -> factory.apply(supplier.get(), p)) - .properties(p -> BlockBehaviour.Properties.ofFullCopy(Blocks.WATER).noLootTable()) - .properties(p -> p.lightLevel(lightLevelInt)) - .blockstate(() -> (ctx, prov) -> { - var model = prov.models().getBuilder("block/" + ctx.getName()); - var fluidTextures = textures; - if (fluidTextures != null) { - model.texture("particle", fluidTextures.still()); - } - prov.simpleBlock(ctx.get(), model); - }); - this.fluidProperties(p -> p.block(ret.asSupplier())); - return ret; - } - - @Beta - public FluidBuilder noBlock() { - if (this.defaultBlock == Boolean.FALSE) { - throw new IllegalStateException("Only one call to block/noBlock per builder allowed"); - } - this.defaultBlock = false; - return this; - } - - /** - * Create a standard {@link BucketItem} for this fluid, building it immediately, and not allowing for further - * configuration. - * - * @return this {@link FluidBuilder} - * @see #bucket() - * @throws IllegalStateException - * If {@link #bucket()} or {@link #bucket(NonNullBiFunction)} has been called before - * this method - */ - public FluidBuilder defaultBucket() { - if (this.defaultBucket != null) { - throw new IllegalStateException("Cannot set a default bucket after a custom bucket has been created"); - } - defaultBucket = true; - return this; - } - - /** - * Create a standard {@link BucketItem} for this fluid, and return the builder for it so that further customization - * can be done. - * - * @return the {@link ItemBuilder} for the {@link BucketItem} - */ - public ItemBuilder> bucket() { - return bucket(BucketItem::new); - } - - /** - * Create a {@link BucketItem} for this fluid, which is created by the given factory, and return the builder for it - * so that further customization can be done. - * - * @param - * The type of the bucket item - * @param factory - * A factory for the bucket item, which accepts the fluid object supplier and properties and returns - * a new item - * @return the {@link ItemBuilder} for the {@link BucketItem} - */ - public ItemBuilder> bucket(NonNullBiFunction factory) { - if (this.defaultBucket == Boolean.FALSE) { - throw new IllegalStateException("Only one call to bucket/noBucket per builder allowed"); - } - this.defaultBucket = false; - NonNullSupplier source = this.source; - if (source == null) { - throw new IllegalStateException("Cannot create a bucket before creating a source block"); - } - final var ret = getOwner().>item(this, bucketName, p -> factory.apply(source.get(), p)) - .properties(p -> p.craftRemainder(Items.BUCKET).stacksTo(1)) - .color(() -> Colors::new) - .model(() -> (ctx, prov) -> prov.generateFluidBucket(ctx.getEntry(), source.get())); - this.fluidProperties(p -> p.bucket(ret.asSupplier())); - return ret; - } - - @Beta - public FluidBuilder noBucket() { - if (this.defaultBucket == Boolean.FALSE) { - throw new IllegalStateException("Only one call to bucket/noBucket per builder allowed"); - } - this.defaultBucket = false; - return this; - } - - /** - * Assign {@link TagKey}{@code s} to this fluid and its source fluid. Multiple calls will add additional tags. - * - * @param tags - * The tags to assign - * @return this {@link FluidBuilder} - */ - @SafeVarargs - public final FluidBuilder tag(TagKey... tags) { - FluidBuilder ret = this.tag(ProviderType.FLUID_TAGS, tags); - if (this.tags.isEmpty()) { - ret.getOwner()., Fluid>setDataGenerator(ret.sourceName, getRegistryKey(), ProviderType.FLUID_TAGS, - prov -> this.tags.stream().map(prov::tag).forEach(p -> p.add(getSource()))); - } - this.tags.addAll(Arrays.asList(tags)); - return ret; - } - - /** - * Remove {@link TagKey}{@code s} from this fluid and its source fluid. Multiple calls will remove additional tags. - * - * @param tags - * The tags to remove - * @return this {@link FluidBuilder} - */ - @SafeVarargs - public final FluidBuilder removeTag(TagKey... tags) { - this.tags.removeAll(Arrays.asList(tags)); - return this.removeTag(ProviderType.FLUID_TAGS, tags); - } - - private BaseFlowingFluid getSource() { - NonNullSupplier source = this.source; - Preconditions.checkNotNull(source, "Fluid has no source block: " + sourceName); - return source.get(); - } - - private BaseFlowingFluid.Properties makeProperties() { - NonNullSupplier source = this.source; - BaseFlowingFluid.Properties ret = new BaseFlowingFluid.Properties(fluidType, source == null ? null : source::get, asSupplier()); - fluidProperties.accept(ret); - return ret; - } - - private FluidType.Properties makeTypeProperties() { - FluidType.Properties properties = FluidType.Properties.create(); - Optional> block = getOwner().getOptional(sourceName, Registries.BLOCK); - this.typeProperties.accept(properties); - - // Force the translation key after the user callback runs - // This is done because we need to remove the lang data generator if using the block key, - // and if it was possible to undo this change, it might result in the user translation getting - // silently lost, as there's no good way to check whether the translation key was changed. - if (block.isPresent() && block.get().isBound()) { - properties.descriptionId(block.get().get().getDescriptionId()); - removeData(ProviderType.LANG); - } else { - properties.descriptionId(Util.makeDescriptionId("fluid", ResourceLocation.fromNamespaceAndPath(getOwner().getModid(), sourceName))); - } - - return properties; - } - - @Override - protected T createEntry() { - return fluidFactory.create(makeProperties()); - } - - /** - * {@inheritDoc} - *

- * Additionally registers the source fluid and the fluid type (if constructed). - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public FluidEntry register() { - // Check the fluid has a type. - if (this.fluidType != null) { - // Register the type. - if (this.registerType) { - getOwner().simple(this, this.sourceName, NeoForgeRegistries.Keys.FLUID_TYPES, this.fluidType); - } - } else { - throw new IllegalStateException("Fluid must have a type: " + getName()); - } - - if (defaultSource == Boolean.TRUE) { - source(BaseFlowingFluid.Source::new); - } - if (defaultBlock == Boolean.TRUE) { - block().register(); - } - if (defaultBucket == Boolean.TRUE) { - bucket().register(); - } - - NonNullSupplier source = this.source; - if (source != null) { - getCallback().accept(sourceName, Registries.FLUID, (FluidBuilder) this, source::get); - } else { - throw new IllegalStateException("Fluid must have a source version: " + getName()); - } - - return (FluidEntry) super.register(); - } - - @Override - protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { - return new FluidEntry<>(getOwner(), delegate); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt new file mode 100644 index 0000000..6c85eed --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/FluidBuilder.kt @@ -0,0 +1,680 @@ +@file:Suppress("ktlint:standard:max-line-length") // Spotless reports a line-length violation at the file header during formatting. + +package com.modularmc.registrate.builders + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.builders.base.AbstractBuilder +import com.modularmc.registrate.builders.base.Builder +import com.modularmc.registrate.builders.base.BuilderCallback +import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener +import com.modularmc.registrate.internal.util.RegistrateDistExecutor.unsafeRunWhenOn +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.providers.DataGenContext +import com.modularmc.registrate.providers.RegistrateTagsProvider +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.generators.RegistrateBlockModelGenerator +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator +import com.modularmc.registrate.util.entry.FluidEntry +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.* + +import net.minecraft.Util +import net.minecraft.core.registries.Registries +import net.minecraft.resources.ResourceLocation +import net.minecraft.tags.TagKey +import net.minecraft.world.item.BucketItem +import net.minecraft.world.item.Item +import net.minecraft.world.item.Items +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.block.Blocks +import net.minecraft.world.level.block.LiquidBlock +import net.minecraft.world.level.block.state.BlockBehaviour +import net.minecraft.world.level.block.state.BlockState +import net.minecraft.world.level.material.Fluid +import net.neoforged.api.distmarker.Dist +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions +import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent +import net.neoforged.neoforge.client.model.DynamicFluidContainerModel.Colors +import net.neoforged.neoforge.common.util.Lazy +import net.neoforged.neoforge.fluids.BaseFlowingFluid +import net.neoforged.neoforge.fluids.BaseFlowingFluid.Flowing +import net.neoforged.neoforge.fluids.FluidType +import net.neoforged.neoforge.registries.DeferredHolder +import net.neoforged.neoforge.registries.NeoForgeRegistries + +import com.google.common.annotations.Beta +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.function.Consumer +import java.util.function.Supplier +import java.util.function.ToIntFunction + +open class FluidBuilder : AbstractBuilder> { + fun interface FluidTypeFactory { + fun create(properties: FluidType.Properties): FluidType + } + + fun interface FluidFactory { + fun create(properties: BaseFlowingFluid.Properties): T + } + + @JvmRecord + private data class FluidTextures(val still: ResourceLocation, val flowing: ResourceLocation) + + private var textures: FluidTextures? = null + private var clientExtension: NonNullSupplier>? = null + + /** + * Supplies the client extension for this fluid type. The extension controls its textures, tint and overlays. + * + * @param clientExtension the side-safe supplier of the client extension + * @return this fluid builder + */ + open fun clientExtension(clientExtension: NonNullSupplier>): FluidBuilder { + if (this.clientExtension == null && !(registerType && textures != null)) { + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerClientExtension() } } + } + this.clientExtension = clientExtension + return this + } + + /** + * Sets the block particle texture and the default client textures for a fluid type registered by this builder. + * A shared fluid type supplied to the builder uses its own client extension. + */ + open fun model(stillTexture: ResourceLocation, flowingTexture: ResourceLocation): FluidBuilder { + if (textures == null && registerType && clientExtension == null) { + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerClientExtension() } } + } + textures = FluidTextures(stillTexture, flowingTexture) + return this + } + + protected open fun registerClientExtension() { + addModListener( + owner, + RegisterClientExtensionsEvent::class.java, + Consumer { event: RegisterClientExtensionsEvent -> + val custom = clientExtension + val fluidTextures = textures + if (custom != null) { + event.registerFluidType(custom.get().get(), fluidType.get()) + } else if (fluidTextures != null) { + event.registerFluidType( + object : IClientFluidTypeExtensions { + override fun getStillTexture(): ResourceLocation = fluidTextures.still + + override fun getFlowingTexture(): ResourceLocation = fluidTextures.flowing + }, + fluidType.get(), + ) + } + }, + ) + } + + private val sourceName: String + private val bucketName: String + + private val fluidFactory: FluidFactory + + private val fluidType: NonNullSupplier + + private var defaultSource: Boolean? = null + private var defaultBlock: Boolean? = null + private var defaultBucket: Boolean? = null + + private var typeProperties = NonNullConsumer.noop() + + private var fluidProperties = NonNullConsumer.noop() + + private val registerType: Boolean + + private lateinit var source: NonNullSupplier + private val tags = ObjectOpenHashSet>() + + constructor( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + typeFactory: FluidTypeFactory, + fluidFactory: FluidFactory, + ) : super(owner, parent, "flowing_$name", callback, Registries.FLUID) { + this.sourceName = name + this.bucketName = name + "_bucket" + this.fluidFactory = fluidFactory + this.fluidType = NonNullSupplier.lazy { typeFactory.create(makeTypeProperties()) } + this.registerType = true + } + + constructor( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + fluidType: NonNullSupplier, + fluidFactory: FluidFactory, + ) : super(owner, parent, "flowing_$name", callback, Registries.FLUID) { + this.sourceName = name + this.bucketName = name + "_bucket" + this.fluidFactory = fluidFactory + this.fluidType = fluidType + this.registerType = false // Don't register if we have a fluid from outside. + } + + /** + * Modify the properties of the fluid type. Modifications are done lazily, but the passed function is composed with + * the current one, and as such this method can be called multiple times to perform + * different operations. + * + * @param cons + * The action to perform on the attributes + * @return this [FluidBuilder] + */ + open fun properties(cons: NonNullConsumer): FluidBuilder { + typeProperties = typeProperties.andThen(cons) + return this + } + + /** + * Modify the properties of the flowing fluid. Modifications are done lazily, but the passed function is composed + * with the current one, and as such this method can be called multiple times to perform + * different operations. + * + * @param cons + * The action to perform on the attributes + * @return this [FluidBuilder] + */ + open fun fluidProperties(cons: NonNullConsumer): FluidBuilder { + fluidProperties = fluidProperties.andThen(cons) + return this + } + + /** + * Assign the default translation, as specified by [RegistrateLangProvider.toEnglishName]. This is the + * default, so it is generally not necessary to call, unless for + * undoing previous changes. + * + * @return this [FluidBuilder] + */ + open fun defaultLang(): FluidBuilder = defaultLang({ f: T -> f.fluidType.descriptionId }, sourceName) + + /** Configures the source text and translations of this entry. */ + open fun localization(configure: Consumer): FluidBuilder = localization({ fluid: T -> fluid.fluidType.descriptionId }, configure) + + /** + * Set the translation for this fluid. + * + * @param name + * A localized English name + * @return this [FluidBuilder] + */ + open fun lang(name: String): FluidBuilder = lang({ f: T -> f.fluidType.descriptionId }, name) + + /** + * Create a standard [BaseFlowingFluid.Source] for this fluid which will be built and registered along with + * this fluid. + * + * @return this [FluidBuilder] + * @see .source + * @throws IllegalStateException + * If [source] has been called before this method + */ + open fun defaultSource(): FluidBuilder { + check(this.defaultSource == null) { "Cannot set a default source after a custom source has been created" } + this.defaultSource = true + return this + } + + /** + * Create a [BaseFlowingFluid] for this fluid, which is created by the given factory, and which will be built + * and registered along with this fluid. + * + * @param factory + * A factory for the fluid, which accepts the properties and returns a new fluid + * @return this [FluidBuilder] + */ + open fun source(factory: NonNullFunction): FluidBuilder { + this.defaultSource = false + this.source = NonNullSupplier.lazy { factory.apply(makeProperties()) } + return this + } + + /** + * Create a standard [LiquidBlock] for this fluid, building it immediately, and not allowing for further + * configuration. + * + * @return this [FluidBuilder] + * @see .block + * @throws IllegalStateException + * If [block] or [block] has been called before + * this method + */ + open fun defaultBlock(): FluidBuilder { + check(this.defaultBlock == null) { "Cannot set a default block after a custom block has been created" } + this.defaultBlock = true + return this + } + + /** + * Create a standard [LiquidBlock] for this fluid, and return the builder for it so that further customization + * can be done. + * + * @return the [BlockBuilder] for the [LiquidBlock] + */ + open fun block() = block( + NonNullBiFunction { fluid: T, properties: BlockBehaviour.Properties -> + LiquidBlock( + fluid, + properties, + ) + }, + ) + + /** + * Create a [LiquidBlock] for this fluid, which is created by the given factory, and return the builder for it + * so that further customization can be done. + * + * @param B + * The type of the block + * @param factory + * A factory for the block, which accepts the block object and properties and returns a new block + * @return the [BlockBuilder] for the [LiquidBlock] + */ + open fun block(factory: NonNullBiFunction): BlockBuilder> { + check(this.defaultBlock != false) { "Only one call to block/noBlock per builder allowed" } + this.defaultBlock = false + val supplier: NonNullSupplier = asSupplier() + val lightLevel = Lazy.of { fluidType.get().lightLevel } + val lightLevelInt = ToIntFunction { lightLevel.get() } + val ret = owner.block( + this, + sourceName, + ) { p: BlockBehaviour.Properties -> factory.apply(supplier.get(), p) } + .properties { + BlockBehaviour.Properties.ofFullCopy( + Blocks.WATER, + ).noLootTable() + } + .properties { p: BlockBehaviour.Properties -> p.lightLevel(lightLevelInt) } + .blockstate { + NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateBlockModelGenerator -> + val model = prov.models().getBuilder("block/" + ctx.name) + val fluidTextures = textures + if (fluidTextures != null) { + model.texture("particle", fluidTextures.still) + } + prov.simpleBlock(ctx.get(), model) + } + } + this.fluidProperties { it.block(ret.asSupplier()) } + return ret + } + + @Beta + open fun noBlock(): FluidBuilder { + check(this.defaultBlock != false) { "Only one call to block/noBlock per builder allowed" } + this.defaultBlock = false + return this + } + + /** + * Create a standard [BucketItem] for this fluid, building it immediately, and not allowing for further + * configuration. + * + * @return this [FluidBuilder] + * @see .bucket + * @throws IllegalStateException + * If [bucket] or [bucket] has been called before + * this method + */ + open fun defaultBucket(): FluidBuilder { + check(this.defaultBucket == null) { "Cannot set a default bucket after a custom bucket has been created" } + defaultBucket = true + return this + } + + /** + * Create a standard [BucketItem] for this fluid, and return the builder for it so that further customization + * can be done. + * + * @return the [ItemBuilder] for the [BucketItem] + */ + open fun bucket() = bucket( + NonNullBiFunction { content: BaseFlowingFluid, properties: Item.Properties -> + BucketItem( + content, + properties, + ) + }, + ) + + /** + * Create a [BucketItem] for this fluid, which is created by the given factory, and return the builder for it + * so that further customization can be done. + * + * @param I + * The type of the bucket item + * @param factory + * A factory for the bucket item, which accepts the fluid object supplier and properties and returns + * a new item + * @return the [ItemBuilder] for the [BucketItem] + */ + open fun bucket(factory: NonNullBiFunction): ItemBuilder> { + check(this.defaultBucket != false) { "Only one call to bucket/noBucket per builder allowed" } + this.defaultBucket = false + val source = this.source + val ret = owner.item( + this, + bucketName, + ) { p: Item.Properties -> factory.apply(source.get(), p) } + .properties { p: Item.Properties -> p.craftRemainder(Items.BUCKET).stacksTo(1) } + .color { Supplier { Colors() } } + .model { + NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateItemModelGenerator -> + prov.generateFluidBucket( + ctx.entry, + source.get(), + ) + } + } + this.fluidProperties { p: BaseFlowingFluid.Properties -> p.bucket(ret.asSupplier()) } + return ret + } + + @Beta + open fun noBucket(): FluidBuilder { + check(this.defaultBucket != false) { "Only one call to bucket/noBucket per builder allowed" } + this.defaultBucket = false + return this + } + + /** + * Assign [TagKey]`s` to this fluid and its source fluid. Multiple calls will add additional tags. + * + * @param tags + * The tags to assign + * @return this [FluidBuilder] + */ + @SafeVarargs + fun tag(vararg tags: TagKey): FluidBuilder { + val ret = + this.tag(ProviderType.FLUID_TAGS, *tags) + if (this.tags.isEmpty()) { + ret.owner.setDataGenerator, Fluid>( + ret.sourceName, + registryKey, + ProviderType.FLUID_TAGS, + NonNullConsumer { prov: RegistrateTagsProvider.Intrinsic -> + val source = getSource() + for (key in this.tags) prov.tag(key).add(source) + }, + ) + } + this.tags.addAll(tags.asList()) + return ret + } + + /** + * Remove [TagKey]`s` from this fluid and its source fluid. Multiple calls will remove additional tags. + * + * @param tags + * The tags to remove + * @return this [FluidBuilder] + */ + @SafeVarargs + fun removeTag(vararg tags: TagKey): FluidBuilder { + tags.forEach { this.tags.remove(it) } + return this.removeTag(ProviderType.FLUID_TAGS, *tags) + } + + private fun getSource(): BaseFlowingFluid = source.get() + + private fun makeProperties(): BaseFlowingFluid.Properties { + val ret = BaseFlowingFluid.Properties(fluidType, source, asSupplier()) + fluidProperties.accept(ret) + return ret + } + + private fun makeTypeProperties(): FluidType.Properties { + val properties = FluidType.Properties.create() + val block = owner.getOptional(sourceName, Registries.BLOCK) + this.typeProperties.accept(properties) + + // Use the sibling block's description ID for the default FluidType when it is already registered. + if (block.isPresent && block.get().isBound) { + properties.descriptionId(block.get().get().descriptionId) + } else { + properties.descriptionId( + Util.makeDescriptionId( + "fluid", + ResourceLocation.fromNamespaceAndPath(owner.modid, sourceName), + ), + ) + } + + return properties + } + + override fun createEntry(): T = fluidFactory.create(makeProperties()) + + /** + * {@inheritDoc} + * + * + * Additionally registers the source fluid and the fluid type (if constructed). + */ + override fun register(): FluidEntry { + if (registerType) { + owner.simple(this, sourceName, NeoForgeRegistries.Keys.FLUID_TYPES, fluidType) + } + if (defaultSource == true) { + source(NonNullFunction { properties: BaseFlowingFluid.Properties -> BaseFlowingFluid.Source(properties) }) + } + if (defaultBlock == true) { + block().register() + } + if (defaultBucket == true) { + bucket().register() + } + + @Suppress("UNCHECKED_CAST") + callback.accept(sourceName, Registries.FLUID, this as Builder, source) + + return super.register() as FluidEntry + } + + override fun createEntryWrapper(delegate: DeferredHolder): RegistryEntry = FluidEntry(owner, delegate) + + companion object { + /** + * Create a new [FluidBuilder] and configure data. The created builder will use a default ([FluidType]) + * and fluid class ([BaseFlowingFluid.Flowing]). + * + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @return A new [FluidBuilder] with reasonable default data generators. + * @see .create +

*/ + @JvmStatic + fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback) = create( + owner, + parent, + name, + callback, + { properties: FluidType.Properties -> FluidType(properties) }, + { properties: BaseFlowingFluid.Properties -> Flowing(properties) }, + ) + + /** + * Create a new [FluidBuilder] and configure data. The created builder will use a default fluid class + * ([BaseFlowingFluid.Flowing]). + * + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param typeFactory + * A factory that creates the fluid type + * @return A new [FluidBuilder] with reasonable default data generators. + * @see .create +

*/ + @JvmStatic + fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, typeFactory: FluidTypeFactory): FluidBuilder = + create(owner, parent, name, callback, typeFactory, ::Flowing) + + /** + * Create a new [FluidBuilder] and configure data. The created builder will use a default fluid class + * ([BaseFlowingFluid.Flowing]). + * + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param fluidType + * An existing and registered fluid type. + * @return A new [FluidBuilder] with reasonable default data generators. + * @see .create +

*/ + @JvmStatic + fun

create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, fluidType: NonNullSupplier): FluidBuilder = + create(owner, parent, name, callback, FluidTypeFactory { fluidType.get() }, ::Flowing) + + /** + * Create a new [FluidBuilder] and configure data. The created builder will use a default ([FluidType]) + * and fluid class ([BaseFlowingFluid.Flowing]). + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param fluidFactory + * A factory that creates the flowing fluid + * @return A new [FluidBuilder] with reasonable default data generators. +

*/ + @JvmStatic + fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, fluidFactory: FluidFactory): FluidBuilder = + create(owner, parent, name, callback, ::FluidType, fluidFactory) + + /** + * Create a new [FluidBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + * + * + * The fluid will be assigned the following data: + * + * * The default translation (via [.defaultLang]) + * * A default [source fluid][BaseFlowingFluid.Source] (via [.defaultSource]) + * * A default block for the fluid, with its own default blockstate and model that configure the particle texture + * (via [.defaultBlock]) + * * A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid + * (via [.defaultBucket]) + * + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param typeFactory + * A factory that creates the fluid type + * @param fluidFactory + * A factory that creates the flowing fluid + * @return A new [FluidBuilder] with reasonable default data generators. +

*/ + @JvmStatic + fun create( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + typeFactory: FluidTypeFactory, + fluidFactory: FluidFactory, + ): FluidBuilder { + val ret = + FluidBuilder(owner, parent, name, callback, typeFactory, fluidFactory) + .defaultLang().defaultSource().defaultBlock().defaultBucket() + return ret + } + + /** + * Create a new [FluidBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + * + * + * The fluid will be assigned the following data: + * + * * The default translation (via [.defaultLang]) + * * A default [source fluid][BaseFlowingFluid.Source] (via [.defaultSource]) + * * A default block for the fluid, with its own default blockstate and model that configure the particle texture + * (via [.defaultBlock]) + * * A default bucket item, that uses a simple generated item model with a texture of the same name as this fluid + * (via [.defaultBucket]) + * + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param fluidType + * An existing and registered fluid type + * @param fluidFactory + * A factory that creates the flowing fluid + * @return A new [FluidBuilder] with reasonable default data generators. +

*/ + @JvmStatic + fun create( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + fluidType: NonNullSupplier, + fluidFactory: FluidFactory, + ) = FluidBuilder(owner, parent, name, callback, fluidType, fluidFactory) + .defaultLang().defaultSource().defaultBlock().defaultBucket() + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java deleted file mode 100644 index cbcdcef..0000000 --- a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.java +++ /dev/null @@ -1,369 +0,0 @@ -package com.modularmc.registrate.builders; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.builders.base.AbstractBuilder; -import com.modularmc.registrate.builders.base.BuilderCallback; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; -import com.modularmc.registrate.internal.util.RegistrateDistExecutor; -import com.modularmc.registrate.providers.DataGenContext; -import com.modularmc.registrate.providers.RegistrateLangProvider; -import com.modularmc.registrate.providers.core.GeneratorType; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator; -import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; -import com.modularmc.registrate.util.CreativeModeTabModifier; -import com.modularmc.registrate.util.entry.ItemEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullBiConsumer; -import com.modularmc.registrate.util.nullness.NonNullFunction; -import com.modularmc.registrate.util.nullness.NonNullSupplier; -import com.modularmc.registrate.util.nullness.NonNullUnaryOperator; - -import net.minecraft.client.color.item.ItemColor; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent; -import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions; -import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent; -import net.neoforged.neoforge.registries.DeferredHolder; -import net.neoforged.neoforge.registries.datamaps.builtin.Compostable; -import net.neoforged.neoforge.registries.datamaps.builtin.FurnaceFuel; -import net.neoforged.neoforge.registries.datamaps.builtin.NeoForgeDataMaps; - -import com.google.common.collect.Maps; -import org.jspecify.annotations.Nullable; - -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * A builder for items, allows for customization of the {@link Item.Properties} and configuration of data associated - * with items (models, recipes, etc.). - * - * @param - * The type of item being built - * @param

- * Parent object type - */ -public class ItemBuilder extends AbstractBuilder> { - - /** - * Create a new {@link ItemBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that - * alternate initialization strategies can be done in subclasses. - *

- * The item will be assigned the following data: - *

    - *
  • A simple generated model with one texture (via {@link #defaultModel()})
  • - *
  • The default translation (via {@link #defaultLang()})
  • - *
- * - * @param - * The type of the builder - * @param

- * Parent object type - * @param owner - * The owning {@link AbstractRegistrate} object - * @param parent - * The parent object - * @param name - * Name of the entry being built - * @param callback - * A callback used to actually register the built entry - * @param factory - * Factory to create the item - * @return A new {@link ItemBuilder} with reasonable default data generators. - */ - public static ItemBuilder create(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory) { - return new ItemBuilder<>(owner, parent, name, callback, factory) - .defaultModel().defaultLang(); - } - - private final NonNullFunction factory; - - private NonNullSupplier initialProperties = Item.Properties::new; - private NonNullFunction propertiesCallback = NonNullUnaryOperator.identity(); - private @Nullable NonNullSupplier> colorHandler; - - private Map, NonNullBiConsumer, CreativeModeTabModifier>> creativeModeTabs = Maps.newLinkedHashMap(); - - protected ItemBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, NonNullFunction factory) { - super(owner, parent, name, callback, Registries.ITEM); - this.factory = factory; - - onRegister(item -> { - creativeModeTabs.forEach((creativeModeTab, consumer) -> owner.modifyCreativeModeTab(creativeModeTab, modifier -> consumer.accept(DataGenContext.from(this), modifier))); - creativeModeTabs.clear(); // this registration should only fire once, to doubly ensure this, clear the map - }); - } - - /** - * Modify the properties of the item. Modifications are done lazily, but the passed function is composed with the - * current one, and as such this method can be called multiple times to perform - * different operations. - *

- * If a different properties instance is returned, it will replace the existing one entirely. - * - * @param func - * The action to perform on the properties - * @return this {@link ItemBuilder} - */ - public ItemBuilder properties(NonNullUnaryOperator func) { - propertiesCallback = propertiesCallback.andThen(func); - return this; - } - - /** - * Replace the initial state of the item properties, without replacing or removing any modifications done via - * {@link #properties(NonNullUnaryOperator)}. - * - * @param properties - * A supplier to to create the initial properties - * @return this {@link ItemBuilder} - */ - public ItemBuilder initialProperties(NonNullSupplier properties) { - initialProperties = properties; - return this; - } - - /** - * Sets a tab modifier for the given tab which can be used to define custom logic for how the item stack is created - * and/or added to the tab. - * - *

- * CreativeModeTab registration is delegated off until the item has been finalized and registered to the - * {@link net.minecraft.core.registries.BuiltInRegistries#ITEM Item registry}.
- * This means you can call this method as many times as you like during the build process with no added side - * effects. - *

- * Calling this method with different {@link ResourceKey tab keys} will add the modifier to all the specified tabs. - *

- * Calling this method multiple times with the same {@link ResourceKey tab key} will replace any existing modifier - * for that tab. - * - * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to use the modifier for - * @param modifier A {@link Consumer consumer} accepting a {@link CreativeModeTabModifier} used to update the tab - * @return This builder - * @deprecated Use {@link #tab(ResourceKey, NonNullBiConsumer)} which provides access to the registered item. - */ - @Deprecated - public ItemBuilder tab(ResourceKey tab, Consumer modifier) { - return tab(tab, ($, m) -> modifier.accept(m)); - } - - /** - * Sets a tab modifier for the given tab which can be used to define custom logic for how the item stack is created - * and/or added to the tab. - * - *

- * CreativeModeTab registration is delegated off until the item has been finalized and registered to the - * {@link net.minecraft.core.registries.BuiltInRegistries#ITEM Item registry}.
- * This means you can call this method as many times as you like during the build process with no added side - * effects. - *

- * Calling this method with different {@link ResourceKey tab keys} will add the modifier to all the specified tabs. - *

- * Calling this method multiple times with the same {@link ResourceKey tab key} will replace any existing modifier - * for that tab. - * - * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to use the modifier for - * @param modifier A {@link NonNullBiConsumer consumer} accepting a context object and - * {@link CreativeModeTabModifier} used to update the tab - * @return This builder - */ - public ItemBuilder tab(ResourceKey tab, NonNullBiConsumer, CreativeModeTabModifier> modifier) { - creativeModeTabs.put(tab, modifier); // Should we get the current value in the map [if one exists] and - // .andThen() the 2 together? right now we replace any consumer that - // currently exists - return this; - } - - /** - * Adds the item built from this builder into the given CreativeModeTab using the default ItemStack instance. - *

- * CreativeModeTab registration is delegated off until the item has been finalized and registered to the - * {@link net.minecraft.core.registries.BuiltInRegistries#ITEM Item registry}.
- * This means you can call this method as many times as you like during the build process with no added side - * effects. - *

- * Calling this method with different {@link ResourceKey tab keys} will add the item to all the specified tabs. - *

- * Calling this method multiple times with the same {@link NonNullSupplier tab supplier} will have no effect. - * - * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to add to - * @return This builder - * @see #tab(ResourceKey, NonNullBiConsumer) - */ - public ItemBuilder tab(ResourceKey tab) { - return tab(tab, (item, modifier) -> modifier.accept(item)); - } - - /** - * Removes the modifier from this builder from the given {@link CreativeModeTab}. - * - * @param tab A {@link ResourceKey} representing the {@link CreativeModeTab} to remove the modifier from - * @return This builder - */ - public ItemBuilder removeTab(ResourceKey tab) { - creativeModeTabs.remove(tab); - return this; - } - - /** - * Assign the default model to this item, which is simply a generated model with a single texture of the same name. - * - * @return this {@link ItemBuilder} - */ - public ItemBuilder defaultModel() { - return model(() -> (ctx, prov) -> prov.generateFlatItem(ctx.get(), prov.modItemTexture(ctx.getName()))); - } - - /** - * Registers the client color handler for the tint indices used by the item model. - * - * @param colorHandler A side-safe supplier of the client color handler - * @return this {@link ItemBuilder} - */ - public ItemBuilder color(NonNullSupplier> colorHandler) { - if (this.colorHandler == null) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerItemColor); - } - this.colorHandler = colorHandler; - return this; - } - - protected void registerItemColor() { - OneTimeEventReceiver.addModListener(getOwner(), RegisterColorHandlersEvent.Item.class, event -> { - var colorHandler = this.colorHandler; - if (colorHandler != null) { - event.register(colorHandler.get().get(), getEntry()); - } - }); - } - - /** - * Configure the model for this item. - * - * @param cons - * The callback which will be invoked during data creation - * @return this {@link ItemBuilder} - * @see #setData(GeneratorType, NonNullBiConsumer) - */ - public ItemBuilder model(NonNullSupplier, RegistrateItemModelGenerator>> cons) { - if (!getOwner().doDatagen().get()) return this; - return setData(ProviderType.ITEM_MODEL, cons.get()); - } - - /** - * Assign the default translation, as specified by - * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, net.minecraft.resources.ResourceKey)}. This is - * the default, so it is generally - * not necessary to call, unless for undoing previous changes. - * - * @return this {@link ItemBuilder} - */ - public ItemBuilder defaultLang() { - return lang(Item::getDescriptionId); - } - - /** - * Set the translation for this item. - * - * @param name - * A localized English name - * @return this {@link ItemBuilder} - */ - public ItemBuilder lang(String name) { - return lang(Item::getDescriptionId, name); - } - - /** - * Configure the recipe(s) for this item. - * - * @param cons - * The callback which will be invoked during data generation. - * @return this {@link ItemBuilder} - * @see #setData(GeneratorType, NonNullBiConsumer) - */ - public ItemBuilder recipe(NonNullBiConsumer, RegistrateRecipeProvider> cons) { - return setData(ProviderType.RECIPE, cons); - } - - /** - * Add burn time for the item - * - * @param tick time in ticks for this item to burn in furnace. - */ - public ItemBuilder burnTime(int tick) { - return dataMap(NeoForgeDataMaps.FURNACE_FUELS, new FurnaceFuel(tick)); - } - - /** - * Add compost chance for the item - * - * @param chance chance for composter to increase one level when composting this item. - */ - public ItemBuilder compostable(float chance) { - return dataMap(NeoForgeDataMaps.COMPOSTABLES, new Compostable(chance)); - } - - private @Nullable NonNullSupplier> clientExtension; - - /** - * Register a client extension for this item. The {@link IClientItemExtensions} instance can be shared across many - * items. - * - * @param clientExtension - * The client extension to register for this item - * @return this {@link ItemBuilder} - */ - public ItemBuilder clientExtension(NonNullSupplier> clientExtension) { - if (this.clientExtension == null) { - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension); - } - this.clientExtension = clientExtension; - return this; - } - - protected void registerClientExtension() { - OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, e -> { - NonNullSupplier> clientExtension = this.clientExtension; - if (clientExtension != null) { - e.registerItem(clientExtension.get().get(), getEntry()); - } - }); - } - - /** - * Assign {@link TagKey}{@code s} to this item. Multiple calls will add additional tags. - * - * @param tags - * The tag to assign - * @return this {@link ItemBuilder} - */ - @SafeVarargs - public final ItemBuilder tag(TagKey... tags) { - return tag(ProviderType.ITEM_TAGS, tags); - } - - @Override - protected T createEntry() { - Item.Properties properties = this.initialProperties.get(); - properties = propertiesCallback.apply(properties); - return factory.apply(properties); - } - - @Override - protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { - return new ItemEntry<>(getOwner(), delegate); - } - - @Override - public ItemEntry register() { - return (ItemEntry) super.register(); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt new file mode 100644 index 0000000..52488e9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/ItemBuilder.kt @@ -0,0 +1,324 @@ +package com.modularmc.registrate.builders + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.builders.base.AbstractBuilder +import com.modularmc.registrate.builders.base.BuilderCallback +import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener +import com.modularmc.registrate.internal.util.RegistrateDistExecutor.unsafeRunWhenOn +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.providers.DataGenContext +import com.modularmc.registrate.providers.RegistrateLangProvider +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider +import com.modularmc.registrate.util.CreativeModeTabModifier +import com.modularmc.registrate.util.entry.ItemEntry +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.* + +import net.minecraft.client.color.item.ItemColor +import net.minecraft.core.registries.Registries +import net.minecraft.resources.ResourceKey +import net.minecraft.tags.TagKey +import net.minecraft.world.item.CreativeModeTab +import net.minecraft.world.item.Item +import net.neoforged.api.distmarker.Dist +import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent +import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions +import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent +import net.neoforged.neoforge.registries.DeferredHolder +import net.neoforged.neoforge.registries.datamaps.builtin.Compostable +import net.neoforged.neoforge.registries.datamaps.builtin.FurnaceFuel +import net.neoforged.neoforge.registries.datamaps.builtin.NeoForgeDataMaps + +import com.google.common.collect.Maps + +import java.util.function.Consumer +import java.util.function.Supplier + +/** + * A builder for items, allows for customization of the [Item.Properties] and configuration of data associated + * with items (models, recipes, etc.). + * + * @param T + * The type of item being built + * @param P + * Parent object type + */ +open class ItemBuilder protected constructor( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + private val factory: NonNullFunction, +) : AbstractBuilder>(owner, parent, name, callback, Registries.ITEM) { + private var initialProperties = NonNullSupplier { Item.Properties() } + private var propertiesCallback: NonNullFunction = NonNullUnaryOperator.identity() + private var colorHandler: NonNullSupplier>? = null + + private val creativeModeTabs: MutableMap, NonNullBiConsumer, CreativeModeTabModifier>> = + Maps.newLinkedHashMap, NonNullBiConsumer, CreativeModeTabModifier>>() + + /** + * Modify the properties of the item. Modifications are done lazily, but the passed function is composed with the + * current one, and as such this method can be called multiple times to perform + * different operations. + * + * + * If a different properties instance is returned, it will replace the existing one entirely. + * + * @param func + * The action to perform on the properties + * @return this [ItemBuilder] + */ + open fun properties(func: NonNullUnaryOperator): ItemBuilder { + propertiesCallback = propertiesCallback.andThen(func) + return this + } + + /** + * Replace the initial state of the item properties, without replacing or removing any modifications done via + * [properties]. + * + * @param properties + * A supplier to to create the initial properties + * @return this [ItemBuilder] + */ + open fun initialProperties(properties: NonNullSupplier): ItemBuilder { + initialProperties = properties + return this + } + + /** Adds this item to a tab, with an optional callback to customize its display. */ + @JvmOverloads + open fun tab( + tab: ResourceKey, + modifier: NonNullBiConsumer, CreativeModeTabModifier> = NonNullBiConsumer { item: DataGenContext, modifier: CreativeModeTabModifier -> + modifier.accept(item) + }, + ): ItemBuilder { + creativeModeTabs[tab] = modifier // Should we get the current value in the map [if one exists] and + // .andThen() the 2 together? right now we replace any consumer that + // currently exists + return this + } + + /** + * Removes the modifier from this builder from the given [CreativeModeTab]. + * + * @param tab A [ResourceKey] representing the [CreativeModeTab] to remove the modifier from + * @return This builder + */ + open fun removeTab(tab: ResourceKey): ItemBuilder { + creativeModeTabs.remove(tab) + return this + } + + /** + * Assign the default model to this item, which is simply a generated model with a single texture of the same name. + * + * @return this [ItemBuilder] + */ + open fun defaultModel(): ItemBuilder = model { + NonNullBiConsumer { ctx: DataGenContext, prov: RegistrateItemModelGenerator -> + prov.generateFlatItem( + ctx.get(), + prov.modItemTexture(ctx.name), + ) + } + } + + /** + * Registers the client color handler for the tint indices used by the item model. + * + * @param colorHandler A side-safe supplier of the client color handler + * @return this [ItemBuilder] + */ + open fun color(colorHandler: NonNullSupplier>): ItemBuilder { + if (this.colorHandler == null) { + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerItemColor() } } + } + this.colorHandler = colorHandler + return this + } + + protected open fun registerItemColor() { + addModListener( + owner, + RegisterColorHandlersEvent.Item::class.java, + Consumer { event: RegisterColorHandlersEvent.Item -> + val colorHandler = this.colorHandler + if (colorHandler != null) { + event.register(colorHandler.get().get(), entry) + } + }, + ) + } + + /** + * Configure the model for this item. + * + * @param cons + * The callback which will be invoked during data creation + * @return this [ItemBuilder] + * @see .setData + */ + open fun model(cons: NonNullSupplier, RegistrateItemModelGenerator>>): ItemBuilder { + val model: NonNullSupplier, RegistrateItemModelGenerator>> = + cons.lazy() + return setData( + ProviderType.ITEM_MODEL, + ) { context: DataGenContext, generator: RegistrateItemModelGenerator -> + model.get().accept(context, generator) + } + } + + /** + * Assign the default translation, as specified by + * [RegistrateLangProvider.getAutomaticName]. This is + * the default, so it is generally + * not necessary to call, unless for undoing previous changes. + * + * @return this [ItemBuilder] + */ + open fun defaultLang(): ItemBuilder = lang { obj: T -> obj.descriptionId } + + /** Configures the source text and translations of this entry. */ + open fun localization(configure: Consumer): ItemBuilder = localization({ obj: T -> obj.descriptionId }, configure) + + /** + * Set the translation for this item. + * + * @param name + * A localized English name + * @return this [ItemBuilder] + */ + open fun lang(name: String): ItemBuilder = lang({ obj: T -> obj.descriptionId }, name) + + /** + * Configure the recipe(s) for this item. + * + * @param cons + * The callback which will be invoked during data generation. + * @return this [ItemBuilder] + * @see .setData + */ + open fun recipe(cons: NonNullBiConsumer, RegistrateRecipeProvider>) = setData(ProviderType.RECIPE, cons) + + /** + * Add burn time for the item + * + * @param tick time in ticks for this item to burn in furnace. + */ + open fun burnTime(tick: Int): ItemBuilder = dataMap(NeoForgeDataMaps.FURNACE_FUELS, FurnaceFuel(tick)) + + /** + * Add compost chance for the item + * + * @param chance chance for composter to increase one level when composting this item. + */ + open fun compostable(chance: Float): ItemBuilder = dataMap(NeoForgeDataMaps.COMPOSTABLES, Compostable(chance)) + + private var clientExtension: NonNullSupplier>? = null + + init { + onRegister( + NonNullConsumer { item: T -> + creativeModeTabs.forEach { (creativeModeTab, consumer) -> + owner.modifyCreativeModeTab( + creativeModeTab, + ) { modifier: CreativeModeTabModifier -> + consumer.accept( + DataGenContext.from(this), + modifier, + ) + } + } + creativeModeTabs.clear() // this registration should only fire once, to doubly ensure this, clear the map + }, + ) + } + + /** + * Register a client extension for this item. The [IClientItemExtensions] instance can be shared across many + * items. + * + * @param clientExtension + * The client extension to register for this item + * @return this [ItemBuilder] + */ + open fun clientExtension(clientExtension: NonNullSupplier>): ItemBuilder { + if (this.clientExtension == null) { + unsafeRunWhenOn(Dist.CLIENT) { Runnable { this.registerClientExtension() } } + } + this.clientExtension = clientExtension + return this + } + + protected open fun registerClientExtension() { + addModListener( + owner, + RegisterClientExtensionsEvent::class.java, + Consumer { e: RegisterClientExtensionsEvent -> + val clientExtension = this.clientExtension + if (clientExtension != null) { + e.registerItem(clientExtension.get().get(), entry) + } + }, + ) + } + + /** + * Assign [TagKey]`s` to this item. Multiple calls will add additional tags. + * + * @param tags + * The tag to assign + * @return this [ItemBuilder] + */ + @SafeVarargs + fun tag(vararg tags: TagKey) = tag(ProviderType.ITEM_TAGS, *tags) + + override fun createEntry(): T { + var properties = this.initialProperties.get() + properties = propertiesCallback.apply(properties) + return factory.apply(properties) + } + + override fun createEntryWrapper(delegate: DeferredHolder): RegistryEntry = ItemEntry(owner, delegate) + + override fun register(): ItemEntry = super.register() as ItemEntry + + companion object { + /** + * Create a new [ItemBuilder] and configure data. Used in lieu of adding side-effects to constructor, so that + * alternate initialization strategies can be done in subclasses. + * + * + * The item will be assigned the following data: + * + * * A simple generated model with one texture (via [.defaultModel]) + * * The default translation (via [.defaultLang]) + * + * + * @param + * The type of the builder + * @param

+ * Parent object type + * @param owner + * The owning [AbstractRegistrate] object + * @param parent + * The parent object + * @param name + * Name of the entry being built + * @param callback + * A callback used to actually register the built entry + * @param factory + * Factory to create the item + * @return A new [ItemBuilder] with reasonable default data generators. +

*/ + @JvmStatic + fun create(owner: AbstractRegistrate<*>, parent: P, name: String, callback: BuilderCallback, factory: NonNullFunction) = + ItemBuilder(owner, parent, name, callback, factory) + .defaultModel().defaultLang() + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.java b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.java deleted file mode 100644 index 9b0b6d1..0000000 --- a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.modularmc.registrate.builders; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.builders.base.AbstractBuilder; -import com.modularmc.registrate.builders.base.BuilderCallback; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; -import com.modularmc.registrate.internal.util.RegistrateDistExecutor; -import com.modularmc.registrate.util.entry.MenuEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.MenuAccess; -import net.minecraft.core.registries.Registries; -import net.minecraft.network.RegistryFriendlyByteBuf; -import net.minecraft.network.chat.Component; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent; -import net.neoforged.neoforge.common.extensions.IMenuTypeExtension; -import net.neoforged.neoforge.registries.DeferredHolder; - -import org.jspecify.annotations.Nullable; - -public class MenuBuilder, P> extends AbstractBuilder, MenuType, P, MenuBuilder> { - - public interface MenuFactory { - - T create(MenuType type, int windowId, Inventory inv); - } - - public interface ForgeMenuFactory { - - T create(MenuType type, int windowId, Inventory inv, @Nullable RegistryFriendlyByteBuf buffer); - } - - public interface ScreenFactory> { - - T create(M menu, Inventory inv, Component displayName); - } - - private final ForgeMenuFactory factory; - private final NonNullSupplier> screenFactory; - - public MenuBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, MenuFactory factory, NonNullSupplier> screenFactory) { - this(owner, parent, name, callback, (type, windowId, inv, $) -> factory.create(type, windowId, inv), screenFactory); - } - - public MenuBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, ForgeMenuFactory factory, NonNullSupplier> screenFactory) { - super(owner, parent, name, callback, Registries.MENU); - this.factory = factory; - this.screenFactory = screenFactory; - } - - @Override - protected MenuType createEntry() { - ForgeMenuFactory factory = this.factory; - final var supplier = this.asSupplier(); - MenuType ret = IMenuTypeExtension.create((windowId, inv, buf) -> factory.create(supplier.get(), windowId, inv, buf)); - RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { - ScreenFactory screenFactory = this.screenFactory.get(); - OneTimeEventReceiver.addModListener(this.getOwner(), RegisterMenuScreensEvent.class, event -> { - event.register(ret, screenFactory::create); - }); - }); - return ret; - } - - @Override - protected RegistryEntry, MenuType> createEntryWrapper(DeferredHolder, MenuType> delegate) { - return new MenuEntry<>(getOwner(), delegate); - } - - @Override - public MenuEntry register() { - return (MenuEntry) super.register(); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt new file mode 100644 index 0000000..6ff81c2 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/MenuBuilder.kt @@ -0,0 +1,86 @@ +package com.modularmc.registrate.builders + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.builders.base.AbstractBuilder +import com.modularmc.registrate.builders.base.BuilderCallback +import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener +import com.modularmc.registrate.internal.util.RegistrateDistExecutor.unsafeRunWhenOn +import com.modularmc.registrate.util.entry.MenuEntry +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.client.gui.screens.Screen +import net.minecraft.client.gui.screens.inventory.MenuAccess +import net.minecraft.core.registries.Registries +import net.minecraft.network.RegistryFriendlyByteBuf +import net.minecraft.network.chat.Component +import net.minecraft.world.entity.player.Inventory +import net.minecraft.world.inventory.AbstractContainerMenu +import net.minecraft.world.inventory.MenuType +import net.neoforged.api.distmarker.Dist +import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent +import net.neoforged.neoforge.common.extensions.IMenuTypeExtension +import net.neoforged.neoforge.registries.DeferredHolder + +open class MenuBuilder( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + private val factory: ForgeMenuFactory, + private val screenFactory: NonNullSupplier>, +) : AbstractBuilder, MenuType, P, MenuBuilder>( + owner, + parent, + name, + callback, + Registries.MENU, +) where S : Screen, S : MenuAccess { + fun interface MenuFactory { + fun create(type: MenuType, windowId: Int, inv: Inventory): T + } + + fun interface ForgeMenuFactory { + fun create(type: MenuType, windowId: Int, inv: Inventory, buffer: RegistryFriendlyByteBuf?): T + } + + fun interface ScreenFactory where T : Screen, T : MenuAccess { + fun create(menu: M, inv: Inventory, displayName: Component): T + } + + constructor( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + factory: MenuFactory, + screenFactory: NonNullSupplier>, + ) : this( + owner, + parent, + name, + callback, + ForgeMenuFactory { type, windowId, inv, _ -> factory.create(type, windowId, inv) }, + screenFactory, + ) + + override fun createEntry(): MenuType { + val supplier = asSupplier() + val menu = IMenuTypeExtension.create { id, inventory, buffer -> + factory.create(supplier.get(), id, inventory, buffer) + } + unsafeRunWhenOn(Dist.CLIENT) { + Runnable { + val screen = screenFactory.get() + addModListener(owner, RegisterMenuScreensEvent::class.java) { event -> + event.register(menu) { container, inventory, title -> screen.create(container, inventory, title) } + } + } + } + return menu + } + + override fun createEntryWrapper(delegate: DeferredHolder, MenuType>): RegistryEntry, MenuType> = MenuEntry(owner, delegate) + + override fun register(): MenuEntry = super.register() as MenuEntry +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java deleted file mode 100644 index 593fa68..0000000 --- a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.modularmc.registrate.builders.base; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.RegistrateLangProvider; -import com.modularmc.registrate.providers.RegistrateTagsProvider; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.util.entry.LazyRegistryEntry; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullBiFunction; -import com.modularmc.registrate.util.nullness.NonNullFunction; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.Registry; -import net.minecraft.data.tags.TagsProvider; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagEntry; -import net.minecraft.tags.TagKey; -import net.neoforged.neoforge.registries.DeferredHolder; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -import java.util.Arrays; - -/** - * Base class which most builders should extend, instead of implementing [@link {@link Builder} directly. - *

- * Provides the most basic functionality, and some utility methods that remove the need to pass the registry class. - * - * @param - * Type of the registry for the current object. This is the concrete base class that all registry entries - * must extend, and the type used for the forge registry itself. - * @param - * Actual type of the object being built. - * @param

- * Type of the parent object, this is returned from {@link #build()} and {@link #getParent()}. - * @param - * Self type - * @see Builder - */ -@RequiredArgsConstructor -public abstract class AbstractBuilder> implements Builder { - - @Getter(onMethod_ = { @Override }) - private final AbstractRegistrate owner; - @Getter(onMethod_ = { @Override }) - private final P parent; - @Getter(onMethod_ = { @Override }) - private final String name; - @Getter(AccessLevel.PROTECTED) - private final BuilderCallback callback; - @Getter(onMethod_ = { @Override }) - private final ResourceKey> registryKey; - - private final Multimap>, TagKey> tagsByType = HashMultimap.create(); - - /** A supplier for the entry that will discard the reference to this builder after it is resolved */ - private final LazyRegistryEntry safeSupplier = new LazyRegistryEntry<>(this); - - /** Indicates whether this entry should generate tags as optional tag */ - private boolean isOptional = false; - - /** - * Create the built entry. This method will be lazily resolved at registration time, so it is safe to bake in values - * from the builder. - * - * @return The built entry - */ - @SuppressWarnings("null") - protected abstract T createEntry(); - - @Override - public RegistryEntry register() { - return callback.accept(name, registryKey, this, this::createEntry, this::createEntryWrapper); - } - - protected RegistryEntry createEntryWrapper(DeferredHolder delegate) { - return new RegistryEntry<>(getOwner(), delegate); - } - - @Override - public NonNullSupplier asSupplier() { - return safeSupplier; - } - - /** - * Tag this entry with a tag (or tags) of the correct type. Multiple calls will add additional tags. - * - * @param type - * The provider type (which must be a tag provider) - * @param tags - * The tags to add - * @return this {@link Builder} - */ - @SuppressWarnings("unchecked") - @SafeVarargs - public final & RegistrateTagsProvider> S tag(ProviderType type, TagKey... tags) { - if (!tagsByType.containsKey(type)) { - setData(type, (ctx, prov) -> tagsByType.get(type).stream() - .map(t -> (TagKey) t) - .map(prov::rawBuilder) - .forEach(b -> b.add(asTag()))); - } - tagsByType.putAll(type, Arrays.asList(tags)); - return (S) this; - } - - /** - * Mark this entry as optional when generating tags - */ - @SuppressWarnings("unchecked") - public S asOptional() { - isOptional = true; - return (S) this; - } - - protected TagEntry asTag() { - ResourceLocation id = ResourceLocation.fromNamespaceAndPath(getOwner().getModid(), getName()); - if (isOptional) return TagEntry.optionalElement(id); - return TagEntry.element(id); - } - - /** - * Remove a tag (or tags) from this entry of a given type. Useful to remove default tags on fluids, for example. - * Multiple calls will remove additional tags. - * - * @param type - * The provider type (which must be a tag provider) - * @param tags - * The tags to remove - * @return this {@link Builder} - */ - @SuppressWarnings("unchecked") - @SafeVarargs - public final & RegistrateTagsProvider> S removeTag(ProviderType type, TagKey... tags) { - if (tagsByType.containsKey(type)) { - for (TagKey tag : tags) { - tagsByType.remove(type, tag); - } - } - return (S) this; - } - - /** - * Set the lang key for this entry to the default value (specified by - * {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, ResourceKey)}). Generally, specific helpers from - * concrete - * builders should be used instead. - * - * @param langKeyProvider - * A function to get the translation key from the entry - * @return this {@link Builder} - */ - public S lang(NonNullFunction langKeyProvider) { - return lang(langKeyProvider, (p, t) -> p.getAutomaticName(t, getRegistryKey())); - } - - /** - * Set the lang key for this entry to the specified name. Generally, specific helpers from concrete builders should - * be used instead. - * - * @param langKeyProvider - * A function to get the translation key from the entry - * @param name - * The name to use - * @return this {@link Builder} - */ - public S lang(NonNullFunction langKeyProvider, String name) { - return lang(langKeyProvider, (p, s) -> name); - } - - private S lang(NonNullFunction langKeyProvider, NonNullBiFunction, String> localizedNameProvider) { - return setData(ProviderType.LANG, (ctx, prov) -> prov.add(langKeyProvider.apply(ctx.getEntry()), localizedNameProvider.apply(prov, ctx::getEntry))); - } - - public ResourceKey getResourceKey() { - return ResourceKey.create(getRegistryKey(), ResourceLocation.fromNamespaceAndPath(getOwner().getModid(), getName())); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt new file mode 100644 index 0000000..905b0de --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt @@ -0,0 +1,133 @@ +package com.modularmc.registrate.builders.base + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.localization.EntryLocalization +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.TranslationSource.Kind +import com.modularmc.registrate.providers.DataGenContext +import com.modularmc.registrate.providers.RegistrateLangProvider +import com.modularmc.registrate.providers.RegistrateTagsProvider +import com.modularmc.registrate.providers.core.GeneratorType +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.util.entry.EntryMetadata.DataGenerator +import com.modularmc.registrate.util.entry.LazyRegistryEntry +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.NonNullBiConsumer +import com.modularmc.registrate.util.nullness.NonNullFunction +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.Registry +import net.minecraft.data.tags.TagsProvider +import net.minecraft.resources.ResourceKey +import net.minecraft.resources.ResourceLocation +import net.minecraft.tags.TagEntry +import net.minecraft.tags.TagKey +import net.neoforged.neoforge.registries.DeferredHolder + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.function.Consumer + +abstract class AbstractBuilder>( + override val owner: AbstractRegistrate<*>, + override val parent: P, + override val name: String, + protected val callback: BuilderCallback, + override val registryKey: ResourceKey>, +) : Builder { + private val tagsByType = Object2ObjectOpenHashMap, ObjectOpenHashSet>>(2) + private val dataGenerators = Object2ObjectLinkedOpenHashMap, DataGenerator<*>>(4) + private var localization: EntryLocalization? = null + private var submitted = false + private val safeSupplier = LazyRegistryEntry(this) + private var optional = false + + /** Invoked by the owner at registry time. */ + protected abstract fun createEntry(): T + + override fun register(): RegistryEntry { + val entry = callback.accept(name, registryKey, this, ::createEntry, ::createEntryWrapper) + submitted = true + dataGenerators.clear() + return entry + } + + fun dataGenerators(): Collection> = dataGenerators.values + + fun localization(): EntryLocalization? = localization + + override fun setData(type: GeneratorType, cons: NonNullBiConsumer, D>): S { + if (submitted) return super.setData(type, cons) + if (type === ProviderType.LANG) localization = null + dataGenerators.putAndMoveToLast(type, DataGenerator(type) { provider -> cons.accept(DataGenContext.from(this), provider) }) + return self() + } + + override fun removeData(type: GeneratorType): S { + if (submitted) return super.removeData(type) + if (type === ProviderType.LANG) localization = null + dataGenerators.remove(type) + return self() + } + + protected open fun createEntryWrapper(delegate: DeferredHolder): RegistryEntry = RegistryEntry(owner, delegate) + + override fun asSupplier(): NonNullSupplier = safeSupplier + + fun tag(type: ProviderType, vararg tags: TagKey): S where TP : TagsProvider, TP : RegistrateTagsProvider { + val keys = tagsByType.getOrPut(type) { + val registered = ObjectOpenHashSet>() + setData(type) { _, provider -> + val entry = asTag() + for (key in registered) provider.rawBuilder(key).add(entry) + } + registered + } + keys.addAll(tags.asList()) + return self() + } + + open fun asOptional(): S { + optional = true + return self() + } + + protected open fun asTag(): TagEntry { + val id = ResourceLocation.fromNamespaceAndPath(owner.modid, name) + return if (optional) TagEntry.optionalElement(id) else TagEntry.element(id) + } + + fun removeTag(type: ProviderType, vararg tags: TagKey): S where TP : TagsProvider, TP : RegistrateTagsProvider { + val keys = tagsByType[type] ?: return self() + for (key in tags) keys.remove(key) + return self() + } + + open fun lang(langKeyProvider: NonNullFunction): S = defaultLang(langKeyProvider, name) + + open fun lang(langKeyProvider: NonNullFunction, name: String): S = localization(langKeyProvider, { LocalizationDeclaration.sourceText(name) }, Kind.DECLARED) + + protected open fun defaultLang(key: NonNullFunction, path: String): S = + localization(key, { LocalizationDeclaration.sourceText(RegistrateLangProvider.toEnglishName(path)) }, Kind.AUTOMATIC) + + /** Declares text whose translation key is read from the registered object during DataGen. */ + open fun localization(key: NonNullFunction, configure: Consumer): S { + val declaration = LocalizationDeclaration.Builder().also(configure::accept).build() + return localization(key, { declaration }, Kind.DECLARED) + } + + private fun localization(key: NonNullFunction, declaration: NonNullSupplier, kind: Kind): S { + val builder = removeData(ProviderType.LANG) + val entry = asSupplier() + localization = EntryLocalization({ key.apply(entry.get()) }, declaration, kind) + return builder + } + + open val resourceKey: ResourceKey + get() = ResourceKey.create(registryKey, ResourceLocation.fromNamespaceAndPath(owner.modid, name)) + + @Suppress("UNCHECKED_CAST") + private fun self(): S = this as S +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/Builder.java b/src/main/java/com/modularmc/registrate/builders/base/Builder.java deleted file mode 100644 index 2d79248..0000000 --- a/src/main/java/com/modularmc/registrate/builders/base/Builder.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.modularmc.registrate.builders.base; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.DataGenContext; -import com.modularmc.registrate.providers.core.GeneratorType; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.*; - -import net.minecraft.core.HolderLookup; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.neoforged.neoforge.registries.datamaps.DataMapType; - -import java.util.function.Function; - -/** - * A Builder creates registry entries. A Builder instance has a constant name which will be used for the resultant - * object, they cannot be reused for different names. It holds a parent object that will - * be returned from some final methods. - *

- * When a builder is completed via {@link #register()} or {@link #build()}, the object will be lazily registered - * (through the owning {@link AbstractRegistrate} object). - * - * @param - * Type of the registry for the current object. This is the concrete base class that all registry entries - * must extend, and the type used for the forge registry itself. - * @param - * Actual type of the object being built. - * @param

- * Type of the parent object, this is returned from {@link #build()} and {@link #getParent()}. - * @param - * Self type - */ -public interface Builder> extends NonNullSupplier> { - - /** - * Complete the current entry, and return the {@link RegistryEntry} that will supply the built entry once it is - * available. The builder can be used afterwards, and changes made will reflect the - * output, as long as it is before registration takes place (before forge registry events). - * - * @return The {@link RegistryEntry} supplying the built entry. - */ - RegistryEntry register(); - - /** - * The owning {@link AbstractRegistrate} that created this builder. - * - * @return the owner {@link AbstractRegistrate} - */ - AbstractRegistrate getOwner(); - - /** - * The parent object. - * - * @return the parent object of this builder - */ - P getParent(); - - /** - * The name of the entry being created, and combined with the mod ID of the parent {@link AbstractRegistrate}, the - * registry name. - * - * @return the name of the current entry - */ - String getName(); - - ResourceKey> getRegistryKey(); - - /** - * Get the {@link RegistryEntry} representing the entry built by this builder. Cannot be called before the builder - * is built. - * - * @return An {@link RegistryEntry} for this builder's entry - * @throws IllegalArgumentException - * If this builder has not been built yet - */ - @Override - default RegistryEntry get() { - return getOwner().get(getName(), getRegistryKey()); - } - - /** - * Get the actual entry built by this builder. Cannot be called before registration. - * - * @return This builder's entry - * @throws IllegalArgumentException - * If this builder has not been built yet - * @throws NullPointerException - * If the entry from this builder has not been registered yet - */ - default T getEntry() { - return get().get(); - } - - /** - * Get a supplier for the entry created by this builder, which will not reference the builder after it has been - * resolved. - * - * @return A supplier for the entry - */ - NonNullSupplier asSupplier(); - - /** - * Set the data provider callback for this entry for the given provider type, which will be invoked when the - * provider of the given type executes. - *

- * If called multiple times for the same type, the existing callback will be overwritten. - *

- * This is mostly unneeded, and instead helper methods for specific data types should be used when possible. - * - * @param - * The type of provider - * @param type - * The {@link GeneratorType} for the desired provider - * @param cons - * The callback to execute when the provider is run - * @return this builder - */ - @SuppressWarnings("unchecked") - default S setData(GeneratorType type, NonNullBiConsumer, D> cons) { - getOwner().setDataGenerator(this, type, prov -> cons.accept(DataGenContext.from(this), prov)); - return (S) this; - } - - /** - * Remove the data provider callback for this entry for the given provider type, if one was previously configured. - * - * @param - * The type of provider - * @param type - * The {@link GeneratorType} for the desired provider - * @return this builder - */ - @SuppressWarnings("unchecked") - default S removeData(GeneratorType type) { - getOwner().removeDataGenerator(this, type); - return (S) this; - } - - /** - * Add a data provider callback which will be invoked when the provider of the given type executes. - *

- * Calling this multiple times for the same type will not overwrite an existing callback. - * - * @param - * The type of provider - * @param type - * The {@link GeneratorType} for the desired provider - * @param cons - * The callback to execute when the provider is run - * @return this builder - */ - @SuppressWarnings("unchecked") - default S addMiscData(GeneratorType type, NonNullConsumer cons) { - getOwner().addDataGenerator(type, cons); - return (S) this; - } - - /** - * Add data map associated with this builder - */ - @SuppressWarnings("unchecked") - default S dataMap(DataMapType type, D val) { - getOwner().addDataGenerator(ProviderType.DATA_MAP, e -> e.builder(type) - .add(DataGenContext.from(this).getId(), val, false)); - return (S) this; - } - - /** - * Add data map associated with this builder, with context - */ - @SuppressWarnings("unchecked") - default S dataMap(DataMapType type, NonNullFunction, D> factory) { - getOwner().addDataGenerator(ProviderType.DATA_MAP, e -> { - var ctx = DataGenContext.from(this); - e.builder(type).add(ctx.getId(), factory.apply(ctx), false); - }); - return (S) this; - } - - /** - * Add data map associated with this builder, with context - */ - @SuppressWarnings("unchecked") - default S dataMap(DataMapType type, NonNullBiFunction, HolderLookup.Provider, D> factory) { - getOwner().addDataGenerator(ProviderType.DATA_MAP, e -> { - var ctx = DataGenContext.from(this); - e.builder(type).add(ctx.getId(), factory.apply(ctx, e.getProvider()), false); - }); - return (S) this; - } - - /** - * Add a callback to be invoked when this entry is registered. Can be called multiple times to add multiple - * callbacks. - *

- * Builders which have had this method used on them (or another method which calls this one), must - * be registered, via - * {@link #register()}, or errors will be thrown when these "dangling" register callbacks are discovered at register - * time. - * - * @param callback - * the callback to invoke - * @return this {@link Builder} - */ - @SuppressWarnings("unchecked") - default S onRegister(NonNullConsumer callback) { - getOwner().addRegisterCallback(getName(), getRegistryKey(), callback); - return (S) this; - } - - /** - * Add a callback to be invoked when this entry is registered, but only after some other registry type has been - * registered as well. Can be called multiple times to add multiple callbacks. - *

- * Builders which have had this method used on them (or another method which calls this one), must - * be registered, via - * {@link #register()}, or errors will be thrown when these "dangling" register callbacks are discovered at register - * time. - * - * @param - * The dependency registry type - * @param dependencyType - * the base class for objects of the dependency registry. The callback will be invoked only - * after this registry has fired its registry events. - * @param callback - * the callback to invoke - * @return this {@link Builder} - */ - default S onRegisterAfter(ResourceKey> dependencyType, NonNullConsumer callback) { - return onRegister(e -> { - if (getOwner().isRegistered(dependencyType)) { - callback.accept(e); - } else { - getOwner().addRegisterCallback(dependencyType, () -> callback.accept(e)); - } - }); - } - - /** - * Apply a transformation to this {@link Builder}. Useful to apply helper methods within a fluent chain, e.g. - * - *

-     * {@code
-     *
-     * public static final RegistryObject MY_BLOCK = REGISTRATE.object("my_block")
-     *         .block(MyBlock::new)
-     *         .transform(Utils::defaultBlockProperties)
-     *         .register();
-     * }
-     * 
- * - * @param - * Registry type - * @param - * Entry type - * @param - * Parent type - * @param - * Self type - * @param func - * The {@link Function function} to apply - * @return the {@link Builder} returned by the given function - */ - @SuppressWarnings("unchecked") - default > S2 transform(NonNullFunction func) { - return func.apply((S) this); - } - - /** - * Register the entry and return the parent object. The {@link net.neoforged.neoforge.registries.DeferredHolder} - * will be created but not returned. It can be retrieved later with {@link AbstractRegistrate#get(ResourceKey)} or - * {@link AbstractRegistrate#get(String, ResourceKey)}. - * - * @return the parent object - */ - default P build() { - register(); // Ignore return value - return getParent(); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/base/Builder.kt b/src/main/java/com/modularmc/registrate/builders/base/Builder.kt new file mode 100644 index 0000000..fab48e6 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/Builder.kt @@ -0,0 +1,96 @@ +package com.modularmc.registrate.builders.base + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.DataGenContext +import com.modularmc.registrate.providers.core.GeneratorType +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.NonNullBiConsumer +import com.modularmc.registrate.util.nullness.NonNullBiFunction +import com.modularmc.registrate.util.nullness.NonNullConsumer +import com.modularmc.registrate.util.nullness.NonNullFunction +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.HolderLookup +import net.minecraft.core.Registry +import net.minecraft.resources.ResourceKey +import net.neoforged.neoforge.registries.datamaps.DataMapType + +/** Collects entry declarations during mod setup and submits them to the owning Registrate. */ +interface Builder> : NonNullSupplier> { + val owner: AbstractRegistrate<*> + val parent: P + val name: String + val registryKey: ResourceKey> + + /** Submits the entry and returns its deferred holder. Each ID can be submitted once per registry. */ + fun register(): RegistryEntry + + override fun get(): RegistryEntry = owner.get(name, registryKey) + + /** The registered object, available after its holder binds. */ + val entry: T + get() = get().get() + + fun asSupplier(): NonNullSupplier + + @Suppress("UNCHECKED_CAST") + fun setData(type: GeneratorType, cons: NonNullBiConsumer, D>): S { + owner.setDataGenerator(this, type) { cons.accept(DataGenContext.from(this), it) } + return this as S + } + + @Suppress("UNCHECKED_CAST") + fun removeData(type: GeneratorType): S { + owner.removeDataGenerator(this, type) + return this as S + } + + @Suppress("UNCHECKED_CAST") + fun addMiscData(type: GeneratorType, cons: NonNullConsumer): S { + owner.addDataGenerator(type, cons) + return this as S + } + + fun dataMap(type: DataMapType, value: D): S = dataMap(type) { value } + + fun dataMap(type: DataMapType, factory: NonNullFunction, D>): S = dataMap(type) { context, _ -> + factory.apply( + context, + ) + } + + @Suppress("UNCHECKED_CAST") + fun dataMap(type: DataMapType, factory: NonNullBiFunction, HolderLookup.Provider, D>): S { + owner.addDataGenerator(ProviderType.DATA_MAP) { provider -> + val context = DataGenContext.from(this) + provider.builder(type).add(context.id, factory.apply(context, provider.getProvider()), false) + } + return this as S + } + + /** Adds a callback that runs after the object is inserted into its registry. */ + @Suppress("UNCHECKED_CAST") + fun onRegister(callback: NonNullConsumer): S { + owner.addRegisterCallback(name, registryKey, callback) + return this as S + } + + /** Runs the callback after this entry binds and the dependency registry is complete. */ + fun onRegisterAfter(dependencyType: ResourceKey>, callback: NonNullConsumer): S = onRegister { value -> + if (owner.isRegistered(dependencyType)) { + callback.accept(value) + } else { + owner.addRegisterCallback(dependencyType) { callback.accept(value) } + } + } + + @Suppress("UNCHECKED_CAST") + fun > transform(func: NonNullFunction): S2 = func.apply(this as S) + + /** Registers the entry and returns the parent so the enclosing chain can continue. */ + fun build(): P { + register() + return parent + } +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java deleted file mode 100644 index ff40121..0000000 --- a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.modularmc.registrate.builders.base; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullFunction; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.neoforged.neoforge.registries.DeferredHolder; - -/** - * A callback passed to {@link Builder builders} from the owning {@link AbstractRegistrate} which will add a - * registration for the built entry that lazily creates and registers it. - */ -@FunctionalInterface -public interface BuilderCallback { - - /** - * Accept a built entry, to later be constructed and registered. - * - * @param - * The registry type to which the entry will be registered - * @param - * The type of the entry - * @param name - * The name of the entry - * @param type - * A {@link ResourceKey} representing the registry type - * @param builder - * The builder performing this callback - * @param factory - * A {@link NonNullSupplier} that will create the entry - * @param entryFactory - * A {@link NonNullFunction} which accepts the entry delegate and returns a - * {@link RegistryEntry} wrapper - * @return A {@link RegistryEntry} that will supply the registered entry - */ - RegistryEntry accept(String name, ResourceKey> type, Builder builder, NonNullSupplier factory, NonNullFunction, ? extends RegistryEntry> entryFactory); - - /** - * Accept a built entry, to later be constructed and registered. Uses the default - * {@link RegistryEntry#RegistryEntry(AbstractRegistrate, DeferredHolder) RegistryEntry factory}. - * - * @param - * The registry type to which the entry will be registered - * @param - * The type of the entry - * @param name - * The name of the entry - * @param type - * A {@link Class} representing the registry type - * @param builder - * The builder performing this callback - * @param factory - * A {@link NonNullSupplier} that will create the entry - * @return A {@link RegistryEntry} that will supply the registered entry - */ - default RegistryEntry accept(String name, ResourceKey> type, Builder builder, NonNullSupplier factory) { - return accept(name, type, builder, factory, delegate -> new RegistryEntry<>(builder.getOwner(), delegate)); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt new file mode 100644 index 0000000..74a4b44 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/BuilderCallback.kt @@ -0,0 +1,25 @@ +package com.modularmc.registrate.builders.base + +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.NonNullFunction +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.Registry +import net.minecraft.resources.ResourceKey +import net.neoforged.neoforge.registries.DeferredHolder + +/** Submits a completed builder to its owner during mod setup. The creator runs at registry time. */ +interface BuilderCallback { + /** Queues an entry with its holder factory and returns the resulting deferred holder. */ + fun accept( + name: String, + type: ResourceKey>, + builder: Builder, + factory: NonNullSupplier, + entryFactory: NonNullFunction, out RegistryEntry>, + ): RegistryEntry + + /** Queues an entry using the default holder wrapper for its registry. */ + fun accept(name: String, type: ResourceKey>, builder: Builder, factory: NonNullSupplier): RegistryEntry = + accept(name, type, builder, factory) { RegistryEntry(builder.owner, it) } +} diff --git a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java deleted file mode 100644 index 7645feb..0000000 --- a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.modularmc.registrate.builders.base; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; - -public class NoConfigBuilder extends AbstractBuilder> { - - private final NonNullSupplier factory; - - public NoConfigBuilder(AbstractRegistrate owner, P parent, String name, BuilderCallback callback, ResourceKey> registryType, NonNullSupplier factory) { - super(owner, parent, name, callback, registryType); - this.factory = factory; - } - - @Override - protected T createEntry() { - return factory.get(); - } -} diff --git a/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt new file mode 100644 index 0000000..234e49c --- /dev/null +++ b/src/main/java/com/modularmc/registrate/builders/base/NoConfigBuilder.kt @@ -0,0 +1,18 @@ +package com.modularmc.registrate.builders.base + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.Registry +import net.minecraft.resources.ResourceKey + +open class NoConfigBuilder( + owner: AbstractRegistrate<*>, + parent: P, + name: String, + callback: BuilderCallback, + registryType: ResourceKey>, + private val factory: NonNullSupplier, +) : AbstractBuilder>(owner, parent, name, callback, registryType) { + override fun createEntry(): T = factory.get() +} diff --git a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java deleted file mode 100644 index ad87edd..0000000 --- a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.modularmc.registrate.internal; - -import com.modularmc.registrate.internal.util.DebugMarkers; -import com.modularmc.registrate.internal.util.RegistrateLogger; -import com.modularmc.registrate.util.entry.RegistryEntry; -import com.modularmc.registrate.util.nullness.NonNullConsumer; -import com.modularmc.registrate.util.nullness.NonNullFunction; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.neoforge.registries.DeferredHolder; -import net.neoforged.neoforge.registries.RegisterEvent; - -import com.google.common.base.Preconditions; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.Table; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.logging.log4j.Logger; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -public final class RegistrationTracker { - - private static final Logger LOGGER = RegistrateLogger.registration(); - - private static final class Registration { - - private final ResourceLocation identifier; - private final ResourceKey> registryKey; - private final NonNullSupplier creator; - private final RegistryEntry delegate; - private final List> callbacks = new ArrayList<>(); - - private Registration( - ResourceLocation identifier, - ResourceKey> registryKey, - NonNullSupplier creator, - NonNullFunction, ? extends RegistryEntry> entryFactory) { - this.identifier = identifier; - this.registryKey = registryKey; - this.creator = creator.lazy(); - this.delegate = entryFactory.apply(DeferredHolder.create(registryKey, identifier)); - } - - private ResourceLocation getIdentifier() { - return identifier; - } - - private RegistryEntry getDelegate() { - return delegate; - } - - private void register(RegisterEvent event) { - T entry = creator.get(); - event.register(registryKey, helper -> helper.register(identifier, entry)); - callbacks.forEach(callback -> callback.accept(entry)); - callbacks.clear(); - } - - private void addRegisterCallback(NonNullConsumer callback) { - Preconditions.checkNotNull(callback, "Callback must not be null"); - callbacks.add(callback); - } - } - - private final String modId; - private final Table>, String, Registration> registrations = HashBasedTable.create(); - private final Multimap>>, NonNullConsumer> pendingEntryCallbacks = HashMultimap.create(); - private final Multimap>, Runnable> afterRegisterCallbacks = HashMultimap.create(); - private final Set>> completedRegistrations = new HashSet<>(); - - public RegistrationTracker(String modId) { - this.modId = modId; - } - - public void onRegister(RegisterEvent event, boolean skipErrors, boolean devEnvironment) { - ResourceKey> registryKey = event.getRegistryKey(); - if (registryKey == null) { - LOGGER.debug( - DebugMarkers.REGISTER, - RegistrateLogger.modMessage("Skipping registry event without a registry key"), - modId); - return; - } - - if (!pendingEntryCallbacks.isEmpty()) { - pendingEntryCallbacks.asMap().forEach((entryKey, callbacks) -> LOGGER.warn( - RegistrateLogger.modMessage("Found {} unused register callback(s) for entry {} [{}]. Was the entry ever registered?"), - modId, - callbacks.size(), - entryKey.getLeft(), - entryKey.getRight().location())); - pendingEntryCallbacks.clear(); - if (devEnvironment) { - throw new IllegalStateException("Found unused register callbacks, see logs"); - } - } - - Map> registrationsForType = registrations.row(registryKey); - if (registrationsForType.isEmpty()) { - return; - } - - LOGGER.trace( - DebugMarkers.REGISTER, - RegistrateLogger.modMessage("Registering {} captured object(s) in {}"), - modId, - registrationsForType.size(), - registryKey.location()); - for (var entry : registrationsForType.entrySet()) { - Registration registration = entry.getValue(); - try { - registration.register(event); - LOGGER.trace( - DebugMarkers.REGISTER, - RegistrateLogger.modMessage("Registered {} in {}"), - modId, - registration.getIdentifier(), - registryKey.location()); - } catch (Exception exception) { - if (skipErrors) { - LOGGER.error( - DebugMarkers.REGISTER, - RegistrateLogger.modMessage("Unexpected error while registering entry {} in {}"), - modId, - registration.getIdentifier(), - registryKey.location(), - exception); - } else { - throw new RuntimeException( - "[%s] Unexpected error while registering entry %s in %s" - .formatted(modId, registration.getIdentifier(), registryKey.location()), - exception); - } - } - } - } - - public void onRegisterLate(RegisterEvent event) { - ResourceKey> registryKey = event.getRegistryKey(); - if (registryKey == null) { - return; - } - - Collection callbacks = afterRegisterCallbacks.get(registryKey); - callbacks.forEach(Runnable::run); - callbacks.clear(); - completedRegistrations.add(registryKey); - } - - public RegistryEntry track( - String name, - ResourceKey> registryKey, - NonNullSupplier creator, - NonNullFunction, ? extends RegistryEntry> entryFactory) { - Registration registration = new Registration<>( - ResourceLocation.fromNamespaceAndPath(modId, name), - registryKey, - creator, - entryFactory); - LOGGER.trace( - DebugMarkers.REGISTER, - RegistrateLogger.modMessage("Captured registration {} for registry {}"), - modId, - registration.getIdentifier(), - registryKey.location()); - pendingEntryCallbacks.removeAll(Pair.of(name, registryKey)).forEach(callback -> { - @SuppressWarnings("unchecked") - NonNullConsumer unsafeCallback = (NonNullConsumer) callback; - registration.addRegisterCallback(unsafeCallback); - }); - registrations.put(registryKey, name, registration); - return registration.getDelegate(); - } - - public void addRegisterCallback( - String name, - ResourceKey> registryKey, - NonNullConsumer callback) { - Registration registration = getRegistrationUnchecked(name, registryKey); - if (registration == null) { - pendingEntryCallbacks.put(Pair.of(name, registryKey), callback); - return; - } - registration.addRegisterCallback(callback); - } - - public void addAfterRegisterCallback(ResourceKey> registryKey, Runnable callback) { - afterRegisterCallbacks.put((ResourceKey>) registryKey, callback); - } - - public boolean isRegistered(ResourceKey> registryKey) { - return completedRegistrations.contains(registryKey); - } - - @SuppressWarnings("unchecked") - public RegistryEntry get(String name, ResourceKey> registryKey) { - return (RegistryEntry) getRegistration(name, registryKey).getDelegate(); - } - - public Optional> getOptional( - String name, - ResourceKey> registryKey) { - Registration registration = getRegistrationUnchecked(name, registryKey); - return registration == null ? Optional.empty() : Optional.of(registration.getDelegate()); - } - - @SuppressWarnings("unchecked") - public Collection> getAll(ResourceKey> registryKey) { - return registrations.row(registryKey) - .values() - .stream() - .map(registration -> (RegistryEntry) registration.getDelegate()) - .collect(Collectors.toList()); - } - - @SuppressWarnings("unchecked") - private Registration getRegistration(String name, ResourceKey> registryKey) { - Registration registration = (Registration) registrations.get(registryKey, name); - if (registration != null) { - return registration; - } - throw new IllegalArgumentException("Unknown registration " + name + " for type " + registryKey.location()); - } - - @SuppressWarnings("unchecked") - private Registration getRegistrationUnchecked( - String name, - ResourceKey> registryKey) { - return (Registration) registrations.get(registryKey, name); - } -} diff --git a/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt new file mode 100644 index 0000000..baff357 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/RegistrationTracker.kt @@ -0,0 +1,173 @@ +package com.modularmc.registrate.internal + +import com.modularmc.registrate.internal.util.DebugMarkers +import com.modularmc.registrate.internal.util.RegistrateLogger +import com.modularmc.registrate.localization.EntryLocalization +import com.modularmc.registrate.util.entry.EntryMetadata +import com.modularmc.registrate.util.entry.RegistryEntry +import com.modularmc.registrate.util.nullness.NonNullConsumer +import com.modularmc.registrate.util.nullness.NonNullFunction +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.Registry +import net.minecraft.resources.ResourceKey +import net.minecraft.resources.ResourceLocation +import net.neoforged.neoforge.registries.DeferredHolder +import net.neoforged.neoforge.registries.RegisterEvent + +import com.google.common.collect.HashMultimap +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.Optional +import java.util.function.BiConsumer + +class RegistrationTracker(private val modId: String) { + private enum class Stage(val description: String) { + CREATION("creation"), + INSERTION("registry insertion"), + CALLBACK("entry callback"), + } + + private data class EntryKey(val name: String, val registry: ResourceKey>) + + private class Registration( + val identifier: ResourceLocation, + val registry: ResourceKey>, + creator: NonNullSupplier, + entryFactory: NonNullFunction, out RegistryEntry>, + val metadata: EntryMetadata, + ) { + private val creator = creator.lazy() + val delegate: RegistryEntry = entryFactory.apply(DeferredHolder.create(registry, identifier)) + private var callbacks: MutableList>? = null + + fun addRegisterCallback(callback: NonNullConsumer) { + val callbacks = callbacks ?: ArrayList>(1).also { callbacks = it } + callbacks.add(callback) + } + + fun register(event: RegisterEvent) { + var stage = Stage.CREATION + try { + val entry = creator.get() + stage = Stage.INSERTION + event.register(registry) { it.register(identifier, entry) } + stage = Stage.CALLBACK + callbacks?.forEach { it.accept(entry) } + callbacks = null + } catch (error: RuntimeException) { + throw IllegalStateException( + "[${identifier.namespace}] Registration of $identifier in ${registry.location()} failed during ${stage.description}", + error, + ) + } + } + } + + private val registrations = Object2ObjectLinkedOpenHashMap>, Object2ObjectLinkedOpenHashMap>>() + private val pendingEntryCallbacks = HashMultimap.create>() + private val afterRegisterCallbacks = HashMultimap.create>, Runnable>() + private val completedRegistrations = ObjectOpenHashSet>>() + + fun onRegister(event: RegisterEvent, skipErrors: Boolean, devEnvironment: Boolean) { + val registry = event.registryKey + if (!pendingEntryCallbacks.isEmpty) { + for ((key, callbacks) in pendingEntryCallbacks.asMap()) { + LOGGER.warn( + RegistrateLogger.modMessage("Found {} unused register callback(s) for entry {} [{}]. Was the entry ever registered?"), + modId, + callbacks.size, + key.name, + key.registry.location(), + ) + } + pendingEntryCallbacks.clear() + check(!devEnvironment) { "Found unused register callbacks, see logs" } + } + + val entries = registrations[registry] ?: return + LOGGER.trace(DebugMarkers.REGISTER, RegistrateLogger.modMessage("Registering {} captured object(s) in {}"), modId, entries.size, registry.location()) + for (registration in entries.values) { + try { + registration.register(event) + LOGGER.trace(DebugMarkers.REGISTER, RegistrateLogger.modMessage("Registered {} in {}"), modId, registration.identifier, registry.location()) + } catch (error: IllegalStateException) { + if (!skipErrors) throw error + LOGGER.error(DebugMarkers.REGISTER, error.message, error) + } + } + } + + fun onRegisterLate(event: RegisterEvent) { + val registry = event.registryKey + completedRegistrations.add(registry) + for (callback in afterRegisterCallbacks.removeAll(registry)) callback.run() + } + + fun track( + name: String, + registry: ResourceKey>, + creator: NonNullSupplier, + entryFactory: NonNullFunction, out RegistryEntry>, + metadata: EntryMetadata, + ): RegistryEntry { + val id = ResourceLocation.fromNamespaceAndPath(modId, name) + val entries = registrations[registry] + require(entries?.containsKey(name) != true) { "[$modId] Duplicate registration $id in ${registry.location()}" } + + val registration = Registration(id, registry, creator, entryFactory, metadata) + LOGGER.trace(DebugMarkers.REGISTER, RegistrateLogger.modMessage("Captured registration {} for registry {}"), modId, id, registry.location()) + for (callback in pendingEntryCallbacks.removeAll(EntryKey(name, registry))) { + @Suppress("UNCHECKED_CAST") + registration.addRegisterCallback(callback as NonNullConsumer) + } + val row = entries ?: Object2ObjectLinkedOpenHashMap>().also { registrations[registry] = it } + row[name] = registration + return registration.delegate + } + + fun getMetadata(key: ResourceKey<*>): EntryMetadata = registration(key.location().path, key.registryKey()).metadata + + fun forEachLocalization(action: BiConsumer, EntryLocalization>) { + for (row in registrations.values) { + for (registration in row.values) { + val localization = registration.metadata.localization() ?: continue + action.accept(registration.delegate, localization) + } + } + } + + fun addRegisterCallback(name: String, registry: ResourceKey>, callback: NonNullConsumer) { + val entry = findRegistration(name, registry) + if (entry == null) { + pendingEntryCallbacks.put(EntryKey(name, registry), callback) + } else { + entry.addRegisterCallback(callback) + } + } + + fun addAfterRegisterCallback(registry: ResourceKey>, callback: Runnable) { + afterRegisterCallbacks.put(registry, callback) + } + + fun isRegistered(registry: ResourceKey>): Boolean = registry in completedRegistrations + + @Suppress("UNCHECKED_CAST") + fun get(name: String, registry: ResourceKey>): RegistryEntry = registration(name, registry).delegate as RegistryEntry + + fun getOptional(name: String, registry: ResourceKey>): Optional> = Optional.ofNullable(findRegistration(name, registry)?.delegate) + + @Suppress("UNCHECKED_CAST") + fun getAll(registry: ResourceKey>): Collection> = registrations[registry]?.values?.map { it.delegate as RegistryEntry } ?: emptyList() + + private fun registration(name: String, registry: ResourceKey>): Registration<*, *> = + registrations[registry]?.get(name) ?: throw IllegalArgumentException("Unknown registration $name for type ${registry.location()}") + + @Suppress("UNCHECKED_CAST") + private fun findRegistration(name: String, registry: ResourceKey>): Registration? = registrations[registry]?.get(name) as Registration? + + companion object { + private val LOGGER = RegistrateLogger.registration() + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java deleted file mode 100644 index 9c3d1b0..0000000 --- a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.modularmc.registrate.internal.event; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.neoforged.bus.api.Event; -import net.neoforged.bus.api.EventPriority; -import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.event.IModBusEvent; -import net.neoforged.fml.event.lifecycle.FMLLoadCompleteEvent; - -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Table; -import lombok.RequiredArgsConstructor; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.commons.lang3.tuple.Triple; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; - -@RequiredArgsConstructor -public final class OneTimeEventReceiver implements Consumer { - - public static void addModListener( - AbstractRegistrate owner, - Class evtClass, - Consumer listener) { - addModListener(owner, EventPriority.NORMAL, evtClass, listener); - } - - public static void addModListener( - AbstractRegistrate owner, - EventPriority priority, - Class evtClass, - Consumer listener) { - if (owner.getModEventBus() == null) { - if (!waitingModListeners.contains(owner, evtClass)) { - waitingModListeners.put(owner, evtClass, new ArrayList<>()); - } - waitingModListeners.get(owner, evtClass).add(Pair.of(priority, listener)); - return; - } - - if (initializedOwners.add(owner)) { - flushWaitingModListeners(owner); - addModListener(owner, FMLLoadCompleteEvent.class, OneTimeEventReceiver::onLoadComplete); - } - - addListener(owner.getModEventBus(), priority, evtClass, listener); - } - - private static final Set> initializedOwners = Collections.newSetFromMap(new IdentityHashMap<>()); - private static final Table, Class, List>>> waitingModListeners = HashBasedTable.create(); - - private final IEventBus bus; - private final Consumer listener; - private final AtomicBoolean consumed = new AtomicBoolean(); - - @Override - public void accept(T event) { - if (consumed.compareAndSet(false, true)) { - listener.accept(event); - unregister(bus, this, event); - } - } - - private static final List>> toUnregister = new ArrayList<>(); - - private static synchronized void unregister(IEventBus bus, Object listener, Event event) { - unregister(bus, listener, event.getClass()); - } - - public static synchronized void unregister(AbstractRegistrate owner, Object listener, Class event) { - unregister(owner.getModEventBus(), listener, event); - } - - private static synchronized void unregister(IEventBus bus, Object listener, Class event) { - toUnregister.add(Triple.of(bus, listener, event)); - } - - private static void onLoadComplete(FMLLoadCompleteEvent event) { - event.enqueueWork(() -> { - toUnregister.forEach(t -> t.getLeft().unregister(t.getMiddle())); - toUnregister.clear(); - }); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private static void flushWaitingModListeners(AbstractRegistrate owner) { - var waitingListeners = new ArrayList<>(waitingModListeners.row(owner).entrySet()); - waitingModListeners.row(owner).clear(); - for (var waitingListener : waitingListeners) { - for (var pair : waitingListener.getValue()) { - addListener(owner.getModEventBus(), pair.getKey(), (Class) waitingListener.getKey(), (Consumer) pair.getValue()); - } - } - } - - @SuppressWarnings("unchecked") - private static void addListener( - IEventBus bus, - EventPriority priority, - Class evtClass, - Consumer listener) { - bus.addListener(priority, false, (Class) evtClass, new OneTimeEventReceiver<>(bus, listener)); - } -} diff --git a/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt new file mode 100644 index 0000000..f740dc8 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/event/OneTimeEventReceiver.kt @@ -0,0 +1,74 @@ +package com.modularmc.registrate.internal.event + +import com.modularmc.registrate.AbstractRegistrate + +import net.neoforged.bus.api.Event +import net.neoforged.bus.api.EventPriority +import net.neoforged.bus.api.IEventBus +import net.neoforged.fml.event.IModBusEvent +import net.neoforged.fml.event.lifecycle.FMLLoadCompleteEvent + +import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet + +import java.util.concurrent.atomic.AtomicBoolean +import java.util.function.Consumer + +class OneTimeEventReceiver(private val bus: IEventBus, private val listener: Consumer) : Consumer { + private val consumed = AtomicBoolean() + + override fun accept(event: T) { + if (consumed.compareAndSet(false, true)) { + listener.accept(event) + unregister(bus, this) + } + } + + companion object { + private val initializedOwners = ReferenceOpenHashSet>() + private val waitingModListeners = Reference2ObjectOpenHashMap, MutableList>>() + private val toUnregister = ArrayList() + + @JvmStatic + fun addModListener(owner: AbstractRegistrate<*>, eventClass: Class, listener: Consumer) where T : Event, T : IModBusEvent { + addModListener(owner, EventPriority.NORMAL, eventClass, listener) + } + + @JvmStatic + fun addModListener(owner: AbstractRegistrate<*>, priority: EventPriority, eventClass: Class, listener: Consumer) where T : Event, T : IModBusEvent { + val bus = owner.modEventBus + if (bus == null) { + waitingModListeners.getOrPut(owner, ::ArrayList).add { addListener(it, priority, eventClass, listener) } + return + } + + if (initializedOwners.add(owner)) { + waitingModListeners.remove(owner)?.forEach { it.accept(bus) } + addModListener(owner, FMLLoadCompleteEvent::class.java, ::onLoadComplete) + } + addListener(bus, priority, eventClass, listener) + } + + @JvmStatic + @Suppress("UNUSED_PARAMETER") + fun unregister(owner: AbstractRegistrate<*>, listener: Any, event: Class) { + unregister(owner.modEventBus!!, listener) + } + + @Synchronized + private fun unregister(bus: IEventBus, listener: Any) { + toUnregister.add { bus.unregister(listener) } + } + + private fun onLoadComplete(event: FMLLoadCompleteEvent) { + event.enqueueWork { + toUnregister.forEach(Runnable::run) + toUnregister.clear() + } + } + + private fun addListener(bus: IEventBus, priority: EventPriority, eventClass: Class, listener: Consumer) { + bus.addListener(priority, false, eventClass, OneTimeEventReceiver(bus, listener)) + } + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java deleted file mode 100644 index 1f677ac..0000000 --- a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.modularmc.registrate.internal.lifecycle; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.internal.event.OneTimeEventReceiver; - -import net.neoforged.bus.api.EventPriority; -import net.neoforged.bus.api.IEventBus; -import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; -import net.neoforged.neoforge.data.event.GatherDataEvent; -import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent; -import net.neoforged.neoforge.registries.RegisterEvent; - -import org.jspecify.annotations.Nullable; - -import java.util.function.Consumer; - -/** - * Centralizes the per-instance NeoForge lifecycle wiring for a Registrate - * owner. - * - *

- * This keeps lifecycle listener registration easy to discover without - * collapsing multiple mod instances into a shared global runtime. - */ -public final class RegistrateLifecycle { - - public interface Hooks { - - @Nullable - IEventBus modEventBus(); - - void setModEventBus(IEventBus bus); - - boolean doDatagen(); - - void onRegister(RegisterEvent event); - - void onRegisterLate(RegisterEvent event); - - void onBuildCreativeModeTabContents(BuildCreativeModeTabContentsEvent event); - - void onData(GatherDataEvent event); - } - - private final AbstractRegistrate owner; - private final Hooks hooks; - - public RegistrateLifecycle(AbstractRegistrate owner, Hooks hooks) { - this.owner = owner; - this.hooks = hooks; - } - - public void register(IEventBus bus) { - if (hooks.modEventBus() == null) { - hooks.setModEventBus(bus); - } - - Consumer onRegister = hooks::onRegister; - Consumer onRegisterLate = hooks::onRegisterLate; - bus.addListener(onRegister); - bus.addListener(EventPriority.LOWEST, onRegisterLate); - bus.addListener(hooks::onBuildCreativeModeTabContents); - - // Register events fire multiple times, so clean them up on common setup. - OneTimeEventReceiver.addModListener(owner, FMLCommonSetupEvent.class, event -> { - event.getClass(); - OneTimeEventReceiver.unregister(owner, onRegister, RegisterEvent.class); - OneTimeEventReceiver.unregister(owner, onRegisterLate, RegisterEvent.class); - }); - - if (hooks.doDatagen()) { - OneTimeEventReceiver.addModListener(owner, GatherDataEvent.class, hooks::onData); - } - } -} diff --git a/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt new file mode 100644 index 0000000..005bfe4 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/lifecycle/RegistrateLifecycle.kt @@ -0,0 +1,54 @@ +package com.modularmc.registrate.internal.lifecycle + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.internal.event.OneTimeEventReceiver + +import net.neoforged.bus.api.EventPriority +import net.neoforged.bus.api.IEventBus +import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent +import net.neoforged.neoforge.data.event.GatherDataEvent +import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent +import net.neoforged.neoforge.registries.RegisterEvent + +import java.util.function.Consumer + +/** Attaches the registration and DataGen listeners for one Registrate. */ +class RegistrateLifecycle(private val owner: AbstractRegistrate<*>, private val hooks: Hooks) { + /** Callbacks bound to their owning Registrate before NeoForge posts lifecycle events. */ + interface Hooks { + fun modEventBus(): IEventBus? + + fun setModEventBus(bus: IEventBus) + + fun doDatagen(): Boolean + + fun onRegister(event: RegisterEvent) + + fun onRegisterLate(event: RegisterEvent) + + fun onBuildCreativeModeTabContents(event: BuildCreativeModeTabContentsEvent) + + fun onData(event: GatherDataEvent) + } + + fun register(bus: IEventBus) { + if (hooks.modEventBus() == null) { + hooks.setModEventBus(bus) + } + + val onRegister = Consumer(hooks::onRegister) + val onRegisterLate = Consumer(hooks::onRegisterLate) + bus.addListener(EventPriority.NORMAL, RegisterEvent::class.java, onRegister) + bus.addListener(EventPriority.LOWEST, RegisterEvent::class.java, onRegisterLate) + bus.addListener(BuildCreativeModeTabContentsEvent::class.java, hooks::onBuildCreativeModeTabContents) + + OneTimeEventReceiver.addModListener(owner, FMLCommonSetupEvent::class.java) { + OneTimeEventReceiver.unregister(owner, onRegister, RegisterEvent::class.java) + OneTimeEventReceiver.unregister(owner, onRegisterLate, RegisterEvent::class.java) + } + + if (hooks.doDatagen()) { + OneTimeEventReceiver.addModListener(owner, GatherDataEvent::class.java, hooks::onData) + } + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java deleted file mode 100644 index f02d9f6..0000000 --- a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.modularmc.registrate.internal.util; - -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; - -@SuppressWarnings("null") -public final class DebugMarkers { - - private static final String PREFIX = "REGISTRATE."; - - public static final Marker REGISTER = marker("REGISTER"); - public static final Marker DATA = marker("DATA"); - - private DebugMarkers() {} - - private static Marker marker(String name) { - return MarkerManager.getMarker(PREFIX + name); - } -} diff --git a/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt new file mode 100644 index 0000000..c40146b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/util/DebugMarkers.kt @@ -0,0 +1,16 @@ +package com.modularmc.registrate.internal.util + +import org.apache.logging.log4j.Marker +import org.apache.logging.log4j.MarkerManager + +object DebugMarkers { + private const val PREFIX = "REGISTRATE." + + @JvmField + val REGISTER: Marker = marker("REGISTER") + + @JvmField + val DATA: Marker = marker("DATA") + + private fun marker(name: String): Marker = MarkerManager.getMarker(PREFIX + name) +} diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java deleted file mode 100644 index 6500d91..0000000 --- a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.modularmc.registrate.internal.util; - -import net.neoforged.api.distmarker.Dist; -import net.neoforged.fml.loading.FMLEnvironment; - -import java.util.function.Supplier; - -public final class RegistrateDistExecutor { - - private RegistrateDistExecutor() {} - - public static void unsafeRunWhenOn(Dist dist, Supplier toRun) { - if (dist == FMLEnvironment.dist) { - toRun.get().run(); - } - } -} diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt new file mode 100644 index 0000000..0d14148 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateDistExecutor.kt @@ -0,0 +1,15 @@ +package com.modularmc.registrate.internal.util + +import net.neoforged.api.distmarker.Dist +import net.neoforged.fml.loading.FMLEnvironment + +import java.util.function.Supplier + +object RegistrateDistExecutor { + @JvmStatic + fun unsafeRunWhenOn(dist: Dist, toRun: Supplier) { + if (dist == FMLEnvironment.dist) { + toRun.get().run() + } + } +} diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java deleted file mode 100644 index 7a896b3..0000000 --- a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.modularmc.registrate.internal.util; - -import com.modularmc.registrate.RegistrateLib; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public final class RegistrateLogger { - - private static final Logger ROOT = RegistrateLib.LOGGER; - private static final Logger CORE = child("Core"); - private static final Logger DATAGEN = child("Datagen"); - private static final Logger REGISTRATION = child("Registration"); - - private RegistrateLogger() {} - - public static Logger root() { - return ROOT; - } - - public static Logger core() { - return CORE; - } - - public static Logger datagen() { - return DATAGEN; - } - - public static Logger registration() { - return REGISTRATION; - } - - public static String modMessage(String message) { - return "[{}] " + message; - } - - private static Logger child(String name) { - return LogManager.getLogger(ROOT.getName() + "." + name); - } -} diff --git a/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt new file mode 100644 index 0000000..940e512 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/internal/util/RegistrateLogger.kt @@ -0,0 +1,30 @@ +package com.modularmc.registrate.internal.util + +import com.modularmc.registrate.RegistrateLib + +import org.apache.logging.log4j.LogManager +import org.apache.logging.log4j.Logger + +object RegistrateLogger { + private val ROOT = RegistrateLib.LOGGER + private val CORE = child("Core") + private val DATAGEN = child("Datagen") + private val REGISTRATION = child("Registration") + + @JvmStatic + fun root(): Logger = ROOT + + @JvmStatic + fun core(): Logger = CORE + + @JvmStatic + fun datagen(): Logger = DATAGEN + + @JvmStatic + fun registration(): Logger = REGISTRATION + + @JvmStatic + fun modMessage(message: String): String = "[{}] $message" + + private fun child(name: String): Logger = LogManager.getLogger(ROOT.name + "." + name) +} diff --git a/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt b/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt new file mode 100644 index 0000000..e73537e --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/EntryLocalization.kt @@ -0,0 +1,8 @@ +package com.modularmc.registrate.localization + +import com.modularmc.registrate.localization.TranslationSource.Kind +import com.modularmc.registrate.util.nullness.NonNullSupplier + +/** A builder declaration whose key is obtained from the bound Minecraft object during DataGen. */ +@JvmRecord +data class EntryLocalization(val key: NonNullSupplier, val declaration: NonNullSupplier, val kind: Kind) diff --git a/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt new file mode 100644 index 0000000..53dee17 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt @@ -0,0 +1,47 @@ +package com.modularmc.registrate.localization + +import com.modularmc.registrate.localization.terminology.Domain +import com.modularmc.registrate.localization.terminology.LocalizationCatalog.GlossaryTerm + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap + +/** A source declaration and its explicit translations, resolved against the owning mod's source locale. */ +@JvmRecord +data class LocalizationDeclaration(val source: String, val translations: Map, val domains: List, val type: TextType?, val glossary: List) { + class Builder { + private lateinit var source: String + private var translations: Object2ObjectOpenHashMap? = null + private var domains: List? = null + private var type: TextType? = null + private var glossary: List? = null + private var profile = LocalizationProfile.EMPTY + + fun source(source: String) = apply { this.source = source } + + fun type(type: TextType?) = apply { this.type = type } + + fun profile(profile: LocalizationProfile) = apply { this.profile = profile } + + fun translation(locale: MinecraftLocale, text: String) = apply { + val texts = translations ?: Object2ObjectOpenHashMap(2).also { translations = it } + texts[locale] = text + } + + fun domain(vararg domains: Domain) = apply { this.domains = domains.toList() } + + fun glossary(vararg terms: GlossaryTerm) = apply { glossary = terms.toList() } + + fun build() = LocalizationDeclaration( + source, + translations?.toMap() ?: emptyMap(), + domains ?: profile.domains, + type ?: profile.type, + glossary ?: profile.glossary, + ) + } + + companion object { + @JvmStatic + fun sourceText(source: String) = LocalizationDeclaration(source, emptyMap(), emptyList(), null, emptyList()) + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/LocalizationProfile.kt b/src/main/java/com/modularmc/registrate/localization/LocalizationProfile.kt new file mode 100644 index 0000000..c594239 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/LocalizationProfile.kt @@ -0,0 +1,12 @@ +package com.modularmc.registrate.localization + +import com.modularmc.registrate.localization.terminology.Domain +import com.modularmc.registrate.localization.terminology.LocalizationCatalog.GlossaryTerm + +/** Reusable domain, text type and glossary defaults for a localization declaration. */ +@JvmRecord +data class LocalizationProfile(val domains: List, val type: TextType?, val glossary: List) { + companion object { + internal val EMPTY = LocalizationProfile(emptyList(), null, emptyList()) + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt b/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt new file mode 100644 index 0000000..d3c18ef --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/MinecraftLocale.kt @@ -0,0 +1,147 @@ +package com.modularmc.registrate.localization + +/** Languages shipped with Minecraft 1.21.1. */ +enum class MinecraftLocale { + AF_ZA, + AR_SA, + AST_ES, + AZ_AZ, + BAR, + BA_RU, + BE_BY, + BE_LATN, + BG_BG, + BRB, + BR_FR, + BS_BA, + CA_ES, + CS_CZ, + CY_GB, + DA_DK, + DE_AT, + DE_CH, + DE_DE, + EL_GR, + ENP, + ENWS, + EN_AU, + EN_CA, + EN_GB, + EN_NZ, + EN_PT, + EN_UD, + EN_US, + EO_UY, + ESAN, + ES_AR, + ES_CL, + ES_EC, + ES_ES, + ES_MX, + ES_UY, + ES_VE, + ET_EE, + EU_ES, + FA_IR, + FIL_PH, + FI_FI, + FO_FO, + FRA_DE, + FR_CA, + FR_FR, + FUR_IT, + FY_NL, + GA_IE, + GD_GB, + GL_ES, + HAL_UA, + HAW_US, + HE_IL, + HI_IN, + HN_NO, + HR_HR, + HU_HU, + HY_AM, + ID_ID, + IG_NG, + IO_EN, + ISV, + IS_IS, + IT_IT, + JA_JP, + JBO_EN, + KA_GE, + KK_KZ, + KN_IN, + KO_KR, + KSH, + KW_GB, + KY_KG, + LA_LA, + LB_LU, + LI_LI, + LMO, + LOL_US, + LO_LA, + LT_LT, + LV_LV, + LZH, + MK_MK, + MN_MN, + MS_MY, + MT_MT, + NAH, + NDS_DE, + NL_BE, + NL_NL, + NN_NO, + NO_NO, + OC_FR, + OVD, + PLS, + PL_PL, + PT_BR, + PT_PT, + QCB_ES, + QID, + QYA_AA, + RO_RO, + RPR, + RU_RU, + RY_UA, + SAH_SAH, + SE_NO, + SK_SK, + SL_SI, + SO_SO, + SQ_AL, + SR_CS, + SR_SP, + SV_SE, + SXU, + SZL, + TA_IN, + TH_TH, + TLH_AA, + TL_PH, + TOK, + TR_TR, + TT_RU, + TZO_MX, + UK_UA, + VAL_ES, + VEC_IT, + VI_VN, + VP_VL, + YI_DE, + YO_NG, + ZH_CN, + ZH_HK, + ZH_TW, + ZLM_ARAB, + ; + + private val code = name.lowercase() + + fun code(): String = code +} diff --git a/src/main/java/com/modularmc/registrate/localization/TextType.kt b/src/main/java/com/modularmc/registrate/localization/TextType.kt new file mode 100644 index 0000000..9568003 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/TextType.kt @@ -0,0 +1,19 @@ +package com.modularmc.registrate.localization + +/** The role of a piece of text in the mod. */ +enum class TextType { + ITEM, + BLOCK, + MACHINE, + MATERIAL, + PROCESS, + REACTION, + PHENOMENON, + ASTRONOMICAL_OBJECT, + BIOME, + RESEARCH, + STATISTIC, + DESCRIPTION, + TOOLTIP, + GUI_LABEL, +} diff --git a/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt b/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt new file mode 100644 index 0000000..4b5ab9d --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/TranslationKey.kt @@ -0,0 +1,5 @@ +package com.modularmc.registrate.localization + +/** The literal Minecraft translation key and the namespace of the language file that owns it. */ +@JvmRecord +data class TranslationKey(val namespace: String, val value: String) diff --git a/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt b/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt new file mode 100644 index 0000000..c062c7c --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/TranslationSource.kt @@ -0,0 +1,10 @@ +package com.modularmc.registrate.localization + +/** Identifies a translation's priority and the declaration that supplied it. */ +@JvmRecord +data class TranslationSource(val kind: Kind, val location: String) { + enum class Kind { + AUTOMATIC, + DECLARED, + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt new file mode 100644 index 0000000..ed42984 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt @@ -0,0 +1,6 @@ +package com.modularmc.registrate.localization.annotation + +/** Adds one translation key to the named mod's language declarations. */ +@Retention(AnnotationRetention.BINARY) +@Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) +annotation class Trans(val modId: String, val key: String, val source: String, val namespace: String = "", val translations: Array = []) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt new file mode 100644 index 0000000..1be3f31 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt @@ -0,0 +1,6 @@ +package com.modularmc.registrate.localization.annotation + +/** Adds a translation for each variant under the given key prefix. */ +@Retention(AnnotationRetention.BINARY) +@Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) +annotation class TransVariants(val modId: String, val keyPrefix: String, val value: Array, val namespace: String = "") diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt new file mode 100644 index 0000000..6ac0d1f --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Translation.kt @@ -0,0 +1,8 @@ +package com.modularmc.registrate.localization.annotation + +import com.modularmc.registrate.localization.MinecraftLocale + +/** Explicit target text supplied by an annotated declaration. */ +@Retention(AnnotationRetention.BINARY) +@Target() +annotation class Translation(val locale: MinecraftLocale, val text: String) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt new file mode 100644 index 0000000..38fa23e --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Variant.kt @@ -0,0 +1,6 @@ +package com.modularmc.registrate.localization.annotation + +/** One entry of a variant group, appended to the group's key prefix. */ +@Retention(AnnotationRetention.BINARY) +@Target() +annotation class Variant(val id: String, val source: String, val translations: Array = []) diff --git a/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt b/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt new file mode 100644 index 0000000..873f493 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt @@ -0,0 +1,41 @@ +package com.modularmc.registrate.localization.index + +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.resolution.TranslationRegistry + +import net.neoforged.fml.ModList + +import java.io.DataInputStream +import java.io.IOException +import java.io.UncheckedIOException +import java.nio.file.Files + +/** Loads the declarations compiled into a mod's own resources during DataGen. */ +object IndexedTranslations { + @JvmStatic + fun collect(modId: String, locale: MinecraftLocale, registry: TranslationRegistry) { + val modFile = ModList.get().getModFileById(modId).file + for (frontend in LocalizationIndex.Frontend.entries) { + val index = modFile.findResource(LocalizationIndex.path(modId, frontend)) + if (Files.notExists(index)) continue + + try { + DataInputStream(Files.newInputStream(index).buffered()).use { input -> + LocalizationIndex.read(input) { entry -> + registry.add( + TranslationKey(entry.namespace, entry.key), + locale, + LocalizationDeclaration(entry.source, entry.translations, emptyList(), null, emptyList()), + TranslationSource(TranslationSource.Kind.DECLARED, entry.location), + ) + } + } + } catch (error: IOException) { + throw UncheckedIOException("[$modId] Reading localization index $index", error) + } + } + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt b/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt new file mode 100644 index 0000000..ed1ff17 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt @@ -0,0 +1,90 @@ +package com.modularmc.registrate.localization.index + +import com.modularmc.registrate.localization.MinecraftLocale + +import java.io.DataInputStream +import java.io.DataOutputStream +import java.io.IOException +import java.util.EnumMap +import java.util.function.Consumer + +/** The declaration protocol used by compiler frontends and the DataGen reader. */ +object LocalizationIndex { + private const val MAGIC = -0x524c494e + private const val VERSION = 1 + + private val entryOrder = compareBy(Entry::namespace, Entry::key, Entry::location) + + enum class Frontend(val suffix: String) { + JAVAC(""), + KSP(".ksp"), + } + + @JvmRecord + data class Entry(val namespace: String, val key: String, val source: String, val location: String, val translations: Map) + + @JvmStatic + @JvmOverloads + fun path(modId: String, frontend: Frontend = Frontend.JAVAC): String = "META-INF/registratelib/localization/$modId${frontend.suffix}.bin" + + @JvmStatic + fun variantKey(prefix: String, id: String): String = if (prefix.endsWith('.')) "$prefix$id" else "$prefix.$id" + + @JvmStatic + @Throws(IOException::class) + fun write(output: DataOutputStream, entries: Collection) { + output.writeInt(MAGIC) + output.writeInt(VERSION) + output.writeInt(entries.size) + for ((namespace, key, source, location, translations) in entries.sortedWith(entryOrder)) { + output.writeUTF(namespace) + output.writeUTF(key) + output.writeUTF(source) + output.writeUTF(location) + output.writeInt(translations.size) + for ((locale, text) in translations) { + output.writeUTF(locale.name) + output.writeUTF(text) + } + } + } + + @JvmStatic + @Throws(IOException::class) + fun read(input: DataInputStream, consumer: Consumer) { + val leading = input.readInt() + val count = if (leading == MAGIC) { + val version = input.readInt() + if (version != VERSION) { + throw IOException("Unsupported localization index version $version") + } + input.readInt() + } else { + leading // Version 0 began with the entry count. + } + + if (count < 0) { + throw IOException("Invalid localization index entry count $count") + } + repeat(count) { + val namespace = input.readUTF() + val key = input.readUTF() + val source = input.readUTF() + val location = input.readUTF() + val targetCount = input.readInt() + if (targetCount < 0) { + throw IOException("Invalid translation count $targetCount for $namespace/$key") + } + val translations = if (targetCount == 0) { + emptyMap() + } else { + EnumMap(MinecraftLocale::class.java).apply { + repeat(targetCount) { + put(MinecraftLocale.valueOf(input.readUTF()), input.readUTF()) + } + } + } + consumer.accept(Entry(namespace, key, source, location, translations)) + } + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt b/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt new file mode 100644 index 0000000..0ec1387 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/resolution/MinecraftTextFormat.kt @@ -0,0 +1,90 @@ +package com.modularmc.registrate.localization.resolution + +import it.unimi.dsi.fastutil.ints.Int2IntMap +import it.unimi.dsi.fastutil.ints.Int2IntMaps +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap + +import java.util.regex.Pattern + +internal object MinecraftTextFormat { + private val tokenPattern = Pattern.compile("%(?:(\\d+)\\$)?s|%%") + private const val NORMAL = "abcdefghijklmn\u00F1opqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789()[]{}<>\u25C1\u25B7_,;.?!/\\'" + private const val INVERTED = + "\u0250q\u0254p\u01DD\u025Fb\u0265\u0131\u0638\u029E\u05DF\u026Fuuodb\u0279s\u0287n\u028C\u028Dx\u028Ez" + + "\u2C6F\u15FA\u0186\u15E1\u018E\u2132\u2141HI\u017F\u029E\uA780WNO\u0500\u1F49\u1D1AS\u27D8\u2229\u039BMX\u028EZ" + + "0\u0196\u1105\u0190\u3123\u03DB9\u312586)(][}{><\u25B7\u25C1\u203E'\u061B\u02D9\u00BF\u00A1\\/," + + private val invertedCodePoints = Int2IntOpenHashMap(NORMAL.length).apply { + for (index in NORMAL.indices) { + put(NORMAL[index].code, INVERTED[index].code) + } + } + + private data class Token(val start: Int, val end: Int, val argument: Int) + + private val plainTextSignature: Int2IntMap = Int2IntMaps.EMPTY_MAP + private val plainText = Parsed(plainTextSignature, null) + + class Parsed(val signature: Int2IntMap, val variant: String?) + + fun parse(text: String, invert: Boolean): Parsed { + val firstPercent = text.indexOf('%') + if (firstPercent < 0) { + return parsePlain(text, invert) + } + + val matcher = tokenPattern.matcher(text) + if (!matcher.find(firstPercent)) { + return parsePlain(text, invert) + } + + val tokens = if (invert) ArrayList(2) else null + val signature = Int2IntOpenHashMap(2) + var nextArgument = 1 + do { + val indexStart = matcher.start(1) + val argument = when { + text[matcher.start() + 1] == '%' -> 0 + + indexStart < 0 -> nextArgument++ + + else -> { + val position = Integer.parseInt(text, indexStart, matcher.end(1), 10) + require(position >= 1) { "Minecraft argument indices start at 1" } + position + } + } + signature.addTo(argument, 1) + tokens?.add(Token(matcher.start(), matcher.end(), argument)) + } while (matcher.find()) + return Parsed(signature, tokens?.let { upsideDown(text, it) }) + } + + private fun parsePlain(text: String, invert: Boolean): Parsed = if (invert) Parsed(plainTextSignature, upsideDown(text, emptyList())) else plainText + + private fun upsideDown(text: String, tokens: List): String { + val result = StringBuilder(text.length) + var cursor = text.length + for (index in tokens.indices.reversed()) { + val token = tokens[index] + appendUpsideDown(text, token.end, cursor, result) + if (token.argument == 0) { + result.append("%%") + } else { + result.append('%').append(token.argument).append($$"$s") + } + cursor = token.start + } + appendUpsideDown(text, 0, cursor, result) + return result.toString() + } + + private fun appendUpsideDown(text: String, start: Int, end: Int, result: StringBuilder) { + var cursor = end + while (cursor > start) { + val codePoint = text.codePointBefore(cursor) + cursor -= Character.charCount(codePoint) + result.appendCodePoint(invertedCodePoints.getOrDefault(codePoint, codePoint)) + } + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt new file mode 100644 index 0000000..0ffe1b0 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt @@ -0,0 +1,111 @@ +package com.modularmc.registrate.localization.resolution + +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.MinecraftLocale.EN_UD +import com.modularmc.registrate.localization.MinecraftLocale.EN_US +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource + +import it.unimi.dsi.fastutil.ints.Int2IntMap +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap + +import java.util.TreeMap + +/** Resolves the declarations for one DataGen output before the language provider writes any files. */ +class TranslationRegistry { + private val selections = Object2ObjectLinkedOpenHashMap() + + @JvmRecord + data class LanguageFile(val namespace: String, val locale: MinecraftLocale) + + private data class EntryKey(val key: TranslationKey, val locale: MinecraftLocale) { + override fun toString(): String = "${key.namespace}/${key.value} (${locale.code()})" + } + + private class Candidate(val text: String, val source: TranslationSource, val original: Selection?) + + private class Selection(var winner: Candidate) { + private var ties: MutableList? = null + lateinit var signature: Int2IntMap + + fun add(candidate: Candidate) { + val precedence = candidate.source.kind.compareTo(winner.source.kind) + if (precedence > 0) { + winner = candidate + ties = null + } else if (precedence == 0) { + val candidates = ties ?: ArrayList(1).also { ties = it } + candidates.add(candidate) + } + } + + fun verifyText(key: EntryKey) { + ties?.forEach { candidate -> + require(candidate.text == winner.text) { + "Conflicting translations for $key from ${winner.source.location} and ${candidate.source.location}" + } + } + } + + fun verifyPlaceholders(key: EntryKey) { + verifyPlaceholders(key, winner) + ties?.forEach { verifyPlaceholders(key, it) } + } + + private fun verifyPlaceholders(key: EntryKey, candidate: Candidate) { + candidate.original?.let { original -> + require(original.signature == signature) { "Minecraft placeholder mismatch for $key at ${candidate.source.location}" } + } + } + } + + fun add(key: TranslationKey, locale: MinecraftLocale, declaration: LocalizationDeclaration, source: TranslationSource) { + val original = add(EntryKey(key, locale), Candidate(declaration.source, source, null)) + for ((target, text) in declaration.translations) { + add(EntryKey(key, target), Candidate(text, source, original)) + } + } + + private fun add(key: EntryKey, candidate: Candidate): Selection { + val selection = selections[key] + if (selection != null) { + selection.add(candidate) + return selection + } + return Selection(candidate).also { selections[key] = it } + } + + fun resolve(): Map> { + val files = Object2ObjectLinkedOpenHashMap>() + val entries = selections.object2ObjectEntrySet() + var iterator = entries.fastIterator() + while (iterator.hasNext()) { + val entry = iterator.next() + val key = entry.key + val selection = entry.value + selection.verifyText(key) + + val winner = selection.winner + val variantKey = if (key.locale == EN_US) key.copy(locale = EN_UD) else null + val invert = variantKey != null && !selections.containsKey(variantKey) + val parsed = try { + MinecraftTextFormat.parse(winner.text, invert) + } catch (error: IllegalArgumentException) { + throw IllegalArgumentException("Invalid Minecraft placeholder for $key at ${winner.source.location}", error) + } + selection.signature = parsed.signature + files.computeIfAbsent(LanguageFile(key.key.namespace, key.locale)) { TreeMap() }[key.key.value] = winner.text + if (variantKey != null && parsed.variant != null) { + files.computeIfAbsent(LanguageFile(key.key.namespace, EN_UD)) { TreeMap() }[key.key.value] = parsed.variant + } + } + + iterator = entries.fastIterator() + while (iterator.hasNext()) { + val entry = iterator.next() + entry.value.verifyPlaceholders(entry.key) + } + return files + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt new file mode 100644 index 0000000..65bbb5c --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt @@ -0,0 +1,19 @@ +package com.modularmc.registrate.localization.terminology + +/** Built-in fields used to associate terms and localization declarations. */ +enum class Domain(private val id: String) { + CHEMISTRY("chemistry"), + PHYSICS("physics"), + ENERGY("energy"), + ASTRONOMY("astronomy"), + GEOGRAPHY("geography"), + GEOLOGY("geology"), + ENGINEERING("engineering"), + MATERIALS("materials"), + COMPUTING("computing"), + MAGIC("magic"), + ADVENTURE("adventure"), + ; + + fun id(): String = id +} diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/LocalizationCatalog.kt b/src/main/java/com/modularmc/registrate/localization/terminology/LocalizationCatalog.kt new file mode 100644 index 0000000..1205661 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/terminology/LocalizationCatalog.kt @@ -0,0 +1,39 @@ +package com.modularmc.registrate.localization.terminology + +import com.modularmc.registrate.localization.MinecraftLocale + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap + +import java.util.EnumSet +import java.util.Optional + +/** Terminology defined by one mod. Register it during mod setup and query it alongside declarations. */ +class LocalizationCatalog { + @JvmRecord + data class GlossaryTerm(val id: String, val source: String, val domains: List, val preferredTranslations: Map) + + @JvmRecord + data class Unit(val id: String, val symbol: String, val names: Map) + + private val domains = EnumSet.noneOf(Domain::class.java) + private val terms = Object2ObjectOpenHashMap() + private val units = Object2ObjectOpenHashMap() + + fun register(domain: Domain) { + domains.add(domain) + } + + fun register(term: GlossaryTerm) { + terms[term.id] = term + } + + fun register(unit: Unit) { + units[unit.id] = unit + } + + fun hasDomain(domain: Domain): Boolean = domains.contains(domain) + + fun glossary(id: String): Optional = Optional.ofNullable(terms[id]) + + fun unit(id: String): Optional = Optional.ofNullable(units[id]) +} diff --git a/src/main/java/com/modularmc/registrate/providers/DataGenContext.java b/src/main/java/com/modularmc/registrate/providers/DataGenContext.java deleted file mode 100644 index 2c14c65..0000000 --- a/src/main/java/com/modularmc/registrate/providers/DataGenContext.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.builders.base.Builder; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; - -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Value; -import lombok.experimental.Delegate; - -/** - * A context bean passed to data generator callbacks. Contains the entry that data is being created for, and some - * metadata about the entry. - * - * @param - * Type of the registry to which the entry belongs - * @param - * Type of the object for which data is being generated - */ -@Value -public class DataGenContext implements NonNullSupplier { - - @Getter(AccessLevel.NONE) - @Delegate - NonNullSupplier entry; - String name; - ResourceLocation id; - - @SuppressWarnings("null") - public E getEntry() { - return entry.get(); - } - - @Deprecated - public static DataGenContext from(Builder builder, ResourceKey> type) { - return from(builder); - } - - public static DataGenContext from(Builder builder) { - return new DataGenContext<>(NonNullSupplier.of(builder.getOwner().get(builder.getName(), builder.getRegistryKey())), builder.getName(), - ResourceLocation.fromNamespaceAndPath(builder.getOwner().getModid(), builder.getName())); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/DataGenContext.kt b/src/main/java/com/modularmc/registrate/providers/DataGenContext.kt new file mode 100644 index 0000000..99468fb --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/DataGenContext.kt @@ -0,0 +1,29 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.builders.base.Builder +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.Registry +import net.minecraft.resources.ResourceKey +import net.minecraft.resources.ResourceLocation + +/** The deferred entry and the ID assigned to it for DataGen. */ +data class DataGenContext(private val supplier: NonNullSupplier, val name: String, val id: ResourceLocation) : NonNullSupplier by supplier { + val entry: E + get() = supplier.get() + + companion object { + @JvmStatic + @Deprecated("The builder already identifies its registry", ReplaceWith("from(builder)")) + @Suppress("UNUSED_PARAMETER") + fun from(builder: Builder, type: ResourceKey>): DataGenContext = from(builder) + + @JvmStatic + fun from(builder: Builder): DataGenContext { + val owner = builder.owner + val name = builder.name + val entry = owner.get(name, builder.registryKey) + return DataGenContext(entry, name, entry.id) + } + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java deleted file mode 100644 index 5528cf6..0000000 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.core.RegistrateProvider; - -import net.minecraft.advancements.Advancement; -import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.core.Holder; -import net.minecraft.core.HolderLookup; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataProvider; -import net.minecraft.data.PackOutput; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.conditions.ICondition; -import net.neoforged.neoforge.common.conditions.WithConditions; - -import com.google.common.collect.Lists; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import lombok.Getter; -import org.jspecify.annotations.Nullable; - -import java.nio.file.Path; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; - -public class RegistrateAdvancementProvider implements RegistrateProvider, Consumer { - - private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().create(); - - private final AbstractRegistrate owner; - private final PackOutput packOutput; - private final CompletableFuture registriesLookup; - private final List> advancementsToSave = Lists.newArrayList(); - @Getter - private HolderLookup.Provider provider; - - public RegistrateAdvancementProvider(AbstractRegistrate owner, PackOutput packOutputIn, CompletableFuture registriesLookupIn) { - this.owner = owner; - this.packOutput = packOutputIn; - this.registriesLookup = registriesLookupIn; - } - - public Holder resolve(ResourceKey key) { - return provider.lookupOrThrow(key.registryKey()).getOrThrow(key); - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } - - public MutableComponent title(String category, String name, String title) { - return owner.addLang("advancements", ResourceLocation.fromNamespaceAndPath(category, name), "title", title); - } - - public MutableComponent desc(String category, String name, String desc) { - return owner.addLang("advancements", ResourceLocation.fromNamespaceAndPath(category, name), "description", desc); - } - - private @Nullable CachedOutput cache; - private Set seenAdvancements = new HashSet<>(); - - @Override - public CompletableFuture run(CachedOutput cache) { - return registriesLookup.thenCompose(lookup -> { - this.provider = lookup; - advancementsToSave.clear(); - - try { - this.cache = cache; - this.seenAdvancements.clear(); - owner.genData(ProviderType.ADVANCEMENT, this); - } finally { - this.cache = null; - } - - return CompletableFuture.allOf(advancementsToSave.toArray(CompletableFuture[]::new)); - }); - } - - @Override - public void accept(@Nullable AdvancementHolder holder) { - withConditions(holder, List.of()); - } - - public void withConditions(@Nullable AdvancementHolder holder, List conditions) { - this.registriesLookup.thenAccept(lookup -> { - CachedOutput cache = this.cache; - if (cache == null) { - throw new IllegalStateException("Cannot accept advancements outside of act"); - } - Objects.requireNonNull(holder, "Cannot accept a null advancement"); - Path path = getPath(this.packOutput.getOutputFolder(), holder); - if (!seenAdvancements.add(holder.id())) { - throw new IllegalStateException("Duplicate advancement " + holder.id()); - } else if (conditions.isEmpty()) { - advancementsToSave.add(DataProvider.saveStable(cache, lookup, Advancement.CODEC, holder.value(), path)); - } else { - advancementsToSave.add(DataProvider.saveStable(cache, lookup, Advancement.CONDITIONAL_CODEC, - Optional.of(new WithConditions<>(conditions, holder.value())), path)); - } - }); - } - - private static Path getPath(Path pathIn, AdvancementHolder advancementIn) { - return pathIn.resolve("data/" + advancementIn.id().getNamespace() + "/advancement/" + advancementIn.id().getPath() + ".json"); - } - - public String getName() { - return "Advancements"; - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.kt new file mode 100644 index 0000000..199e2af --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateAdvancementProvider.kt @@ -0,0 +1,77 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.core.RegistrateProvider + +import net.minecraft.advancements.Advancement +import net.minecraft.advancements.AdvancementHolder +import net.minecraft.core.Holder +import net.minecraft.core.HolderLookup +import net.minecraft.data.CachedOutput +import net.minecraft.data.DataProvider +import net.minecraft.data.PackOutput +import net.minecraft.network.chat.MutableComponent +import net.minecraft.resources.ResourceKey +import net.minecraft.resources.ResourceLocation +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.conditions.ICondition +import net.neoforged.neoforge.common.conditions.WithConditions + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.function.Consumer + +open class RegistrateAdvancementProvider(private val owner: AbstractRegistrate<*>, packOutput: PackOutput, private val registriesLookup: CompletableFuture) : + RegistrateProvider, + Consumer { + private val paths = packOutput.createPathProvider(PackOutput.Target.DATA_PACK, "advancement") + private val advancementsToSave = ArrayList>() + private val seenAdvancements = ObjectOpenHashSet() + private var cache: CachedOutput? = null + + lateinit var provider: HolderLookup.Provider + private set + + open fun resolve(key: ResourceKey): Holder = provider.lookupOrThrow(key.registryKey()).getOrThrow(key) + + override fun getSide(): LogicalSide = LogicalSide.SERVER + + open fun title(category: String, name: String, title: String): MutableComponent = owner.addLang("advancements", ResourceLocation.fromNamespaceAndPath(category, name), "title", title) + + open fun desc(category: String, name: String, desc: String): MutableComponent = owner.addLang("advancements", ResourceLocation.fromNamespaceAndPath(category, name), "description", desc) + + override fun run(cache: CachedOutput): CompletableFuture<*> = registriesLookup.thenCompose { lookup -> + provider = lookup + advancementsToSave.clear() + seenAdvancements.clear() + this.cache = cache + try { + owner.genData(ProviderType.ADVANCEMENT, this) + } finally { + this.cache = null + } + CompletableFuture.allOf(*advancementsToSave.toTypedArray()) + } + + override fun accept(holder: AdvancementHolder) { + withConditions(holder, emptyList()) + } + + open fun withConditions(holder: AdvancementHolder, conditions: List) { + val cache = checkNotNull(cache) { "Advancements must be submitted during their DataGen callback" } + check(seenAdvancements.add(holder.id())) { "Duplicate advancement ${holder.id()}" } + val path = paths.json(holder.id()) + val advancement = holder.value() + val write = if (conditions.isEmpty()) { + DataProvider.saveStable(cache, provider, Advancement.CODEC, advancement, path) + } else { + DataProvider.saveStable(cache, provider, Advancement.CONDITIONAL_CODEC, Optional.of(WithConditions(conditions, advancement)), path) + } + advancementsToSave.add(write) + } + + override fun getName(): String = "Advancements" +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java deleted file mode 100644 index 27d66bf..0000000 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.core.RegistrateProvider; - -import net.minecraft.core.HolderLookup; -import net.minecraft.data.PackOutput; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.data.DataMapProvider; - -import org.jetbrains.annotations.Nullable; - -import java.util.concurrent.CompletableFuture; - -public class RegistrateDataMapProvider extends DataMapProvider implements RegistrateProvider { - - private final AbstractRegistrate parent; - - private HolderLookup.@Nullable Provider provider; - - public RegistrateDataMapProvider(AbstractRegistrate parent, PackOutput output, CompletableFuture pvd) { - super(output, pvd); - this.parent = parent; - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } - - /** - * Generate data map entries. - * - * @param provider - */ - @Override - protected void gather(HolderLookup.Provider provider) { - this.provider = provider; - parent.genData(ProviderType.DATA_MAP, this); - this.provider = null; - } - - public HolderLookup.Provider getProvider() { - if (provider == null) throw new IllegalStateException("Holder Lookup Provider is not available now"); - return provider; - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.kt new file mode 100644 index 0000000..7fa373c --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateDataMapProvider.kt @@ -0,0 +1,31 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.core.RegistrateProvider + +import net.minecraft.core.HolderLookup +import net.minecraft.data.PackOutput +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.data.DataMapProvider + +import java.util.concurrent.CompletableFuture + +open class RegistrateDataMapProvider(private val parent: AbstractRegistrate<*>, output: PackOutput, lookup: CompletableFuture) : + DataMapProvider(output, lookup), + RegistrateProvider { + private var provider: HolderLookup.Provider? = null + + override fun getSide(): LogicalSide = LogicalSide.SERVER + + override fun gather(provider: HolderLookup.Provider) { + this.provider = provider + try { + parent.genData(ProviderType.DATA_MAP, this) + } finally { + this.provider = null + } + } + + open fun getProvider(): HolderLookup.Provider = checkNotNull(provider) { "Holder lookup is available during the data map callback" } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java deleted file mode 100644 index a385011..0000000 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.RegistrateLookupFillerProvider; - -import net.minecraft.core.HolderLookup; -import net.minecraft.data.PackOutput; -import net.minecraft.data.registries.RegistryPatchGenerator; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.data.DatapackBuiltinEntriesProvider; - -import java.util.Set; -import java.util.concurrent.CompletableFuture; - -public class RegistrateDatapackProvider extends DatapackBuiltinEntriesProvider implements RegistrateLookupFillerProvider { - - public RegistrateDatapackProvider(AbstractRegistrate parent, PackOutput output, CompletableFuture provider) { - super(output, RegistryPatchGenerator.createLookup(provider, parent.getDataGenInitializer().getDatapackRegistryProviders()), Set.of(parent.getModid())); - } - - @Override - public CompletableFuture getFilledProvider() { - return getRegistryProvider(); - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.kt new file mode 100644 index 0000000..1dbea75 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateDatapackProvider.kt @@ -0,0 +1,20 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.RegistrateLookupFillerProvider + +import net.minecraft.core.HolderLookup +import net.minecraft.data.PackOutput +import net.minecraft.data.registries.RegistryPatchGenerator +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.data.DatapackBuiltinEntriesProvider + +import java.util.concurrent.CompletableFuture + +open class RegistrateDatapackProvider(parent: AbstractRegistrate<*>, output: PackOutput, provider: CompletableFuture) : + DatapackBuiltinEntriesProvider(output, RegistryPatchGenerator.createLookup(provider, parent.dataGenInitializer.getDatapackRegistryProviders()), setOf(parent.modid)), + RegistrateLookupFillerProvider { + override fun getFilledProvider(): CompletableFuture = registryProvider + + override fun getSide(): LogicalSide = LogicalSide.SERVER +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java deleted file mode 100644 index cfb49a5..0000000 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.core.RegistrateProvider; - -import net.minecraft.core.HolderLookup; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataProvider; -import net.minecraft.data.PackOutput; -import net.neoforged.fml.LogicalSide; - -import org.apache.commons.compress.utils.Lists; -import org.jetbrains.annotations.ApiStatus; - -import java.util.List; -import java.util.Locale; -import java.util.concurrent.CompletableFuture; - -public final class RegistrateGenericProvider implements RegistrateProvider { - - private final AbstractRegistrate registrate; - private final PackOutput output; - private final CompletableFuture registries; - private final LogicalSide side; - private final ProviderType providerType; - private final List generators = Lists.newArrayList(); - - @ApiStatus.Internal - public RegistrateGenericProvider(AbstractRegistrate registrate, PackOutput output, CompletableFuture registries, LogicalSide side, ProviderType providerType) { - this.registrate = registrate; - this.output = output; - this.registries = registries; - this.side = side; - this.providerType = providerType; - } - - public RegistrateGenericProvider add(Generator generator) { - generators.add(generator); - return this; - } - - @Override - public LogicalSide getSide() { - return side; - } - - @Override - public CompletableFuture run(CachedOutput cache) { - generators.clear(); - var data = new GeneratorData(output, registries); - registrate.genData(providerType, this); - return CompletableFuture.allOf(generators - .stream() - .map(generator -> generator.generate(data)) - .map(provider -> provider.run(cache)) - .toArray(CompletableFuture[]::new)); - } - - @Override - public String getName() { - return "generic_%s_provider".formatted(side.name().toLowerCase(Locale.ROOT)); - } - - public record GeneratorData(PackOutput output, CompletableFuture registries) {} - - @FunctionalInterface - public interface Generator { - - DataProvider generate(GeneratorData data); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.kt new file mode 100644 index 0000000..342798f --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateGenericProvider.kt @@ -0,0 +1,47 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.core.RegistrateProvider + +import net.minecraft.core.HolderLookup +import net.minecraft.data.CachedOutput +import net.minecraft.data.DataProvider +import net.minecraft.data.PackOutput +import net.neoforged.fml.LogicalSide + +import org.jetbrains.annotations.ApiStatus + +import java.util.concurrent.CompletableFuture + +class RegistrateGenericProvider @ApiStatus.Internal constructor( + private val registrate: AbstractRegistrate<*>, + private val output: PackOutput, + private val registries: CompletableFuture, + private val side: LogicalSide, + private val providerType: ProviderType, +) : RegistrateProvider { + private val generators = ArrayList() + + fun add(generator: Generator) = apply { generators.add(generator) } + + override fun getSide(): LogicalSide = side + + override fun run(cache: CachedOutput): CompletableFuture<*> { + generators.clear() + val data = GeneratorData(output, registries) + registrate.genData(providerType, this) + val runs = Array(generators.size) { generators[it].generate(data).run(cache) } + return CompletableFuture.allOf(*runs) + } + + override fun getName(): String = "generic_${side.name.lowercase()}_provider" + + @JvmRecord + data class GeneratorData(val output: PackOutput, val registries: CompletableFuture) + + /** Supplies a provider for the current output and registry lookups. */ + fun interface Generator { + fun generate(data: GeneratorData): DataProvider + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java deleted file mode 100644 index c5ef80c..0000000 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.RegistrateTagsProvider.IntrinsicTags; -import com.modularmc.registrate.providers.core.ProviderType; - -import net.minecraft.core.HolderLookup; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.PackOutput; -import net.minecraft.data.tags.TagsProvider; -import net.minecraft.tags.TagBuilder; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.neoforged.neoforge.common.data.ExistingFileHelper; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -public class RegistrateItemTagsProvider extends IntrinsicTags { - - private final CompletableFuture> blockTags; - private final Map, TagKey> tagsToCopy = new HashMap<>(); - - public RegistrateItemTagsProvider(AbstractRegistrate owner, ProviderType type, String name, PackOutput output, CompletableFuture registriesLookup, CompletableFuture> blockTags, ExistingFileHelper fileHelper) { - super(owner, type, name, output, Registries.ITEM, registriesLookup, item -> BuiltInRegistries.ITEM.getResourceKey(item) - .orElseThrow(() -> new IllegalStateException("Cannot generate tags for unregistered item: " + item)), fileHelper); - this.blockTags = blockTags; - } - - public void copy(TagKey sourceTag, TagKey targetTag) { - tagsToCopy.put(sourceTag, targetTag); - } - - @Override - protected CompletableFuture createContentsProvider() { - return super.createContentsProvider().thenCombineAsync(blockTags, (lookupProvider, blockTagLookup) -> { - tagsToCopy.forEach((sourceTag, targetTag) -> { - TagBuilder tagBuilder = getOrCreateRawBuilder(targetTag); - Optional sourceBuilder = blockTagLookup.apply(sourceTag); - sourceBuilder - .orElseThrow(() -> new IllegalStateException("Missing block tag " + sourceTag.location())) - .build() - .forEach(tagBuilder::add); - }); - return lookupProvider; - }); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.kt new file mode 100644 index 0000000..64235e1 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateItemTagsProvider.kt @@ -0,0 +1,46 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.RegistrateTagsProvider.IntrinsicTags +import com.modularmc.registrate.providers.core.ProviderType + +import net.minecraft.core.HolderLookup +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.core.registries.Registries +import net.minecraft.data.PackOutput +import net.minecraft.data.tags.TagsProvider.TagLookup +import net.minecraft.tags.TagKey +import net.minecraft.world.item.Item +import net.minecraft.world.level.block.Block +import net.neoforged.neoforge.common.data.ExistingFileHelper + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap + +import java.util.concurrent.CompletableFuture + +open class RegistrateItemTagsProvider( + owner: AbstractRegistrate<*>, + type: ProviderType, + name: String, + output: PackOutput, + registriesLookup: CompletableFuture, + private val blockTags: CompletableFuture>, + fileHelper: ExistingFileHelper, +) : IntrinsicTags(owner, type, name, output, Registries.ITEM, registriesLookup, { item -> + BuiltInRegistries.ITEM.getResourceKey(item).orElseThrow { IllegalStateException("Cannot generate tags for unregistered item: $item") } +}, fileHelper) { + private val tagsToCopy = Object2ObjectOpenHashMap, TagKey>() + + open fun copy(sourceTag: TagKey, targetTag: TagKey) { + tagsToCopy[sourceTag] = targetTag + } + + override fun createContentsProvider(): CompletableFuture = super.createContentsProvider().thenCombineAsync(blockTags) { lookup, blockTagLookup -> + for ((source, target) in tagsToCopy) { + val destination = getOrCreateRawBuilder(target) + blockTagLookup.apply(source).orElseThrow { IllegalStateException("Missing block tag ${source.location()}") } + .build().forEach(destination::add) + } + lookup + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java deleted file mode 100644 index 0f53996..0000000 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.core.RegistrateProvider; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.PackOutput; -import net.minecraft.network.chat.contents.TranslatableContents; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.data.LanguageProvider; - -import org.apache.commons.lang3.StringUtils; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; - -public class RegistrateLangProvider extends LanguageProvider implements RegistrateProvider { - - private static class AccessibleLanguageProvider extends LanguageProvider { - - public AccessibleLanguageProvider(PackOutput packOutput, String modid, String locale) { - super(packOutput, modid, locale); - } - - @Override - public void add(@Nullable String key, @Nullable String value) { - super.add(key, value); - } - - @Override - protected void addTranslations() {} - } - - private final AbstractRegistrate owner; - - private final AccessibleLanguageProvider upsideDown; - - public RegistrateLangProvider(AbstractRegistrate owner, PackOutput packOutput) { - super(packOutput, owner.getModid(), "en_us"); - this.owner = owner; - this.upsideDown = new AccessibleLanguageProvider(packOutput, owner.getModid(), "en_ud"); - } - - @Override - public LogicalSide getSide() { - return LogicalSide.CLIENT; - } - - @Override - public String getName() { - return "Lang (en_us/en_ud)"; - } - - @Override - protected void addTranslations() { - owner.genData(ProviderType.LANG, this); - } - - public static final String toEnglishName(String internalName) { - return Arrays.stream(internalName.toLowerCase(Locale.ROOT).split("_")) - .map(StringUtils::capitalize) - .collect(Collectors.joining(" ")); - } - - @SuppressWarnings({ "unchecked", "ConstantConditions" }) - public String getAutomaticName(NonNullSupplier sup, ResourceKey> registry) { - return toEnglishName(((Registry>) BuiltInRegistries.REGISTRY).get(registry.location()).getKey(sup.get()).getPath()); - } - - public void addBlock(NonNullSupplier block) { - addBlock(block, getAutomaticName(block, Registries.BLOCK)); - } - - public void addBlockWithTooltip(NonNullSupplier block, String tooltip) { - addBlock(block); - addTooltip(block, tooltip); - } - - public void addBlockWithTooltip(NonNullSupplier block, String name, String tooltip) { - addBlock(block, name); - addTooltip(block, tooltip); - } - - public void addItem(NonNullSupplier item) { - addItem(item, getAutomaticName(item, Registries.ITEM)); - } - - public void addItemWithTooltip(NonNullSupplier block, String name, List tooltip) { - addItem(block, name); - addTooltip(block, tooltip); - } - - public void addTooltip(NonNullSupplier item, String tooltip) { - add(item.get().asItem().getDescriptionId() + ".desc", tooltip); - } - - public void addTooltip(NonNullSupplier item, List tooltip) { - for (int i = 0; i < tooltip.size(); i++) { - add(item.get().asItem().getDescriptionId() + ".desc." + i, tooltip.get(i)); - } - } - - public void add(CreativeModeTab tab, String name) { - var contents = tab.getDisplayName().getContents(); - if (contents instanceof TranslatableContents lang) { - add(lang.getKey(), name); - } else { - throw new IllegalArgumentException("Creative tab does not have a translatable name: " + tab.getDisplayName()); - } - } - - public void addEntityType(NonNullSupplier> entity) { - addEntityType(entity, getAutomaticName(entity, Registries.ENTITY_TYPE)); - } - - // Automatic en_ud generation - - private static final String NORMAL_CHARS = - /* lowercase */ "abcdefghijklmn\u00F1opqrstuvwxyz" + - /* uppercase */ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - /* numbers */ "0123456789" + - /* special */ "()[]{}<>\u25C1\u25B7_,;.?!/\\'"; - private static final String UPSIDE_DOWN_CHARS = - /* lowercase */ "\u0250q\u0254p\u01DD\u025Fb\u0265\u0131\u0638\u029E\u05DF\u026Fuuodb\u0279s\u0287n\u028C\u028Dx\u028Ez" + - /* uppercase */ "\u2C6F\u15FA\u0186\u15E1\u018E\u2132\u2141HI\u017F\u029E\uA780WNO\u0500\u1F49\u1D1AS\u27D8\u2229\u039BMX\u028EZ" + - /* numbers */ "0\u0196\u1105\u0190\u3123\u03DB9\u312586" + - /* special */ ")(][}{><\u25B7\u25C1\u203E'\u061B\u02D9\u00BF\u00A1\\/,"; - - static { - if (NORMAL_CHARS.length() != UPSIDE_DOWN_CHARS.length()) { - throw new AssertionError("Char maps do not match in length!"); - } - } - - private static boolean isFormatTokenChar(char c) { - return Character.isDigit(c) || c == '%' || c == '$' || c == 's' || c == 'd'; - } - - private String toUpsideDown(String normal) { - int formatIndex = 1; - ArrayList ud = new ArrayList<>(); - for (int i = 0; i < normal.length(); i++) { - char c = normal.charAt(i); - if (c == '%') { - String fmtArg = ""; - while (isFormatTokenChar(c)) { - if (fmtArg.equals("%") && c == 's') { - fmtArg = "%" + formatIndex + "$s"; - formatIndex++; - i++; - break; - } else if (c == '$') { - formatIndex++; - } - fmtArg += c; - i++; - c = i == normal.length() ? 0 : normal.charAt(i); - } - i--; - for (int j = fmtArg.length() - 1; j >= 0; j--) { - ud.addFirst(fmtArg.charAt(j)); - } - continue; - } - int lookup = NORMAL_CHARS.indexOf(c); - if (lookup >= 0) { - c = UPSIDE_DOWN_CHARS.charAt(lookup); - } - ud.addFirst(c); - } - StringBuilder builder = new StringBuilder(ud.size()); - for (Character ch : ud) { - builder.append(ch); - } - return builder.toString(); - } - - @Override - public void add(String key, String value) { - super.add(key, value); - upsideDown.add(key, toUpsideDown(value)); - } - - @Override - public CompletableFuture run(CachedOutput cache) { - return CompletableFuture.allOf(super.run(cache), upsideDown.run(cache)); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt new file mode 100644 index 0000000..83c33f0 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt @@ -0,0 +1,128 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.TranslationSource.Kind +import com.modularmc.registrate.localization.index.IndexedTranslations +import com.modularmc.registrate.localization.resolution.TranslationRegistry +import com.modularmc.registrate.providers.core.LanguageOutput +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.core.RegistrateProvider +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.Registry +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.core.registries.Registries +import net.minecraft.data.CachedOutput +import net.minecraft.data.PackOutput +import net.minecraft.network.chat.contents.TranslatableContents +import net.minecraft.resources.ResourceKey +import net.minecraft.world.entity.EntityType +import net.minecraft.world.item.CreativeModeTab +import net.minecraft.world.item.Item +import net.minecraft.world.level.ItemLike +import net.minecraft.world.level.block.Block +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.data.LanguageProvider + +import org.apache.commons.lang3.StringUtils + +import java.util.concurrent.CompletableFuture +import java.util.regex.Pattern + +open class RegistrateLangProvider(private val owner: AbstractRegistrate<*>, private val packOutput: PackOutput) : + LanguageProvider(packOutput, owner.modid, "en_us"), + RegistrateProvider { + private class Operation(val key: String, val value: String) + + private val operations = ArrayList() + + override fun getSide(): LogicalSide = LogicalSide.CLIENT + + override fun getName(): String = "Registrate language declarations" + + override fun addTranslations() { + owner.genData(ProviderType.LANG, this) + } + + @Suppress("UNCHECKED_CAST") + open fun getAutomaticName(supplier: NonNullSupplier, registry: ResourceKey>): String { + val entries = BuiltInRegistries.REGISTRY.get(registry.location()) as Registry + return toEnglishName(entries.getKey(supplier.get())!!.path) + } + + open fun addBlock(block: NonNullSupplier) { + addBlock(block, getAutomaticName(block, Registries.BLOCK)) + } + + open fun addBlockWithTooltip(block: NonNullSupplier, tooltip: String) { + addBlock(block) + addTooltip(block, tooltip) + } + + open fun addBlockWithTooltip(block: NonNullSupplier, name: String, tooltip: String) { + addBlock(block, name) + addTooltip(block, tooltip) + } + + open fun addItem(item: NonNullSupplier) { + addItem(item, getAutomaticName(item, Registries.ITEM)) + } + + open fun addItemWithTooltip(item: NonNullSupplier, name: String, tooltip: List) { + addItem(item, name) + addTooltip(item, tooltip) + } + + open fun addTooltip(item: NonNullSupplier, tooltip: String) { + add("${item.get().asItem().descriptionId}.desc", tooltip) + } + + open fun addTooltip(item: NonNullSupplier, tooltip: List) { + if (tooltip.isEmpty()) return + val prefix = "${item.get().asItem().descriptionId}.desc." + tooltip.forEachIndexed { index, text -> add("$prefix$index", text) } + } + + open fun add(tab: CreativeModeTab, name: String) { + add((tab.displayName.contents as TranslatableContents).key, name) + } + + override fun add(key: String, value: String) { + operations.add(Operation(key, value)) + } + + open fun collect(registry: TranslationRegistry) { + val modId = owner.modid + val locale = owner.requireSourceLocale() + owner.collectEntryTranslations(registry, locale) + addTranslations() + for (operation in operations) { + val key = operation.key + val source = TranslationSource(Kind.DECLARED, "[$modId] ProviderType.LANG ($key)") + registry.add(TranslationKey(modId, key), locale, LocalizationDeclaration.sourceText(operation.value), source) + } + operations.clear() + owner.collectRawTranslations(registry, locale) + IndexedTranslations.collect(modId, locale, registry) + } + + open fun addEntityType(entity: NonNullSupplier>) { + addEntityType(entity, getAutomaticName(entity, Registries.ENTITY_TYPE)) + } + + override fun run(cache: CachedOutput): CompletableFuture<*> { + val registry = TranslationRegistry() + collect(registry) + return LanguageOutput.write(cache, packOutput, registry) + } + + companion object { + private val underscores = Pattern.compile("_") + + @JvmStatic + fun toEnglishName(internalName: String): String = underscores.split(internalName.lowercase()).joinToString(" ", transform = StringUtils::capitalize) + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java b/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java deleted file mode 100644 index 12ca1b4..0000000 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.modularmc.registrate.providers; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.core.RegistrateLookupFillerProvider; - -import net.minecraft.core.HolderLookup; -import net.minecraft.core.Registry; -import net.minecraft.data.PackOutput; -import net.minecraft.data.tags.IntrinsicHolderTagsProvider; -import net.minecraft.data.tags.IntrinsicHolderTagsProvider.IntrinsicTagAppender; -import net.minecraft.data.tags.TagsProvider; -import net.minecraft.data.tags.TagsProvider.TagAppender; -import net.minecraft.resources.ResourceKey; -import net.minecraft.tags.TagBuilder; -import net.minecraft.tags.TagKey; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.data.ExistingFileHelper; - -import java.util.concurrent.CompletableFuture; -import java.util.function.Function; - -public interface RegistrateTagsProvider extends RegistrateLookupFillerProvider { - - CompletableFuture> contentsGetter(); - - ResourceKey> registry(); - - TagBuilder rawBuilder(TagKey key); - - interface Key extends RegistrateTagsProvider { - - TagAppender tag(TagKey key); - } - - interface Intrinsic extends RegistrateTagsProvider { - - IntrinsicTagAppender tag(TagKey key); - } - - class KeyTags extends TagsProvider implements RegistrateTagsProvider.Key { - - private final AbstractRegistrate owner; - private final ProviderType> type; - private final String name; - - public KeyTags(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup, ExistingFileHelper fileHelper) { - super(packOutput, registryIn, registriesLookup, owner.getModid(), fileHelper); - - this.owner = owner; - this.type = type; - this.name = name; - } - - @Override - public String getName() { - return "Tags (%s)".formatted(name); - } - - @Override - protected void addTags(HolderLookup.Provider provider) { - owner.genData(type, this); - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } - - @Override - public TagBuilder rawBuilder(final TagKey key) { - return super.getOrCreateRawBuilder(key); - } - - @Override - public TagAppender tag(TagKey key) { - return super.tag(key); - } - - @Override - public CompletableFuture getFilledProvider() { - return createContentsProvider(); - } - - @Override - public ResourceKey> registry() { - return registryKey; - } - } - - class IntrinsicTags extends IntrinsicHolderTagsProvider implements RegistrateTagsProvider.Intrinsic { - - private final AbstractRegistrate owner; - private final ProviderType> type; - private final String name; - - public IntrinsicTags(AbstractRegistrate owner, ProviderType> type, String name, PackOutput packOutput, ResourceKey> registryIn, CompletableFuture registriesLookup, Function> keyExtractor, ExistingFileHelper fileHelper) { - super(packOutput, registryIn, registriesLookup, keyExtractor, owner.getModid(), fileHelper); - - this.owner = owner; - this.type = type; - this.name = name; - } - - @Override - public String getName() { - return "Tags (%s)".formatted(name); - } - - @Override - protected void addTags(HolderLookup.Provider provider) { - owner.genData(type, this); - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } - - @Override - public TagBuilder rawBuilder(TagKey key) { - return super.getOrCreateRawBuilder(key); - } - - @Override - public IntrinsicTagAppender tag(final TagKey key) { - return super.tag(key); - } - - @Override - public CompletableFuture getFilledProvider() { - return createContentsProvider(); - } - - @Override - public ResourceKey> registry() { - return registryKey; - } - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.kt new file mode 100644 index 0000000..5edd763 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateTagsProvider.kt @@ -0,0 +1,96 @@ +package com.modularmc.registrate.providers + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.core.RegistrateLookupFillerProvider + +import net.minecraft.core.HolderLookup +import net.minecraft.core.Registry +import net.minecraft.data.PackOutput +import net.minecraft.data.tags.IntrinsicHolderTagsProvider +import net.minecraft.data.tags.IntrinsicHolderTagsProvider.IntrinsicTagAppender +import net.minecraft.data.tags.TagsProvider +import net.minecraft.data.tags.TagsProvider.TagAppender +import net.minecraft.data.tags.TagsProvider.TagLookup +import net.minecraft.resources.ResourceKey +import net.minecraft.tags.TagBuilder +import net.minecraft.tags.TagKey +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.data.ExistingFileHelper + +import java.util.concurrent.CompletableFuture +import java.util.function.Function + +/** A provider for one registry's tags. Tag builders are populated during the provider's DataGen callback. */ +interface RegistrateTagsProvider : RegistrateLookupFillerProvider { + fun contentsGetter(): CompletableFuture> + + fun registry(): ResourceKey> + + fun rawBuilder(key: TagKey): TagBuilder + + /** Appends entries using their registry keys. */ + interface Key : RegistrateTagsProvider { + fun tag(key: TagKey): TagAppender + } + + /** Appends entries by obtaining their registry keys from the objects themselves. */ + interface Intrinsic : RegistrateTagsProvider { + fun tag(key: TagKey): IntrinsicTagAppender + } + + open class KeyTags( + private val owner: AbstractRegistrate<*>, + private val type: ProviderType>, + private val name: String, + output: PackOutput, + registry: ResourceKey>, + lookup: CompletableFuture, + fileHelper: ExistingFileHelper, + ) : TagsProvider(output, registry, lookup, owner.modid, fileHelper), + Key { + override fun getName(): String = "Tags ($name)" + + override fun addTags(provider: HolderLookup.Provider) { + owner.genData(type, this) + } + + override fun getSide(): LogicalSide = LogicalSide.SERVER + + override fun rawBuilder(key: TagKey): TagBuilder = super.getOrCreateRawBuilder(key) + + override fun tag(key: TagKey): TagAppender = super.tag(key) + + override fun getFilledProvider(): CompletableFuture = createContentsProvider() + + override fun registry(): ResourceKey> = registryKey + } + + open class IntrinsicTags( + private val owner: AbstractRegistrate<*>, + private val type: ProviderType>, + private val name: String, + output: PackOutput, + registry: ResourceKey>, + lookup: CompletableFuture, + keyExtractor: Function>, + fileHelper: ExistingFileHelper, + ) : IntrinsicHolderTagsProvider(output, registry, lookup, keyExtractor, owner.modid, fileHelper), + Intrinsic { + override fun getName(): String = "Tags ($name)" + + override fun addTags(provider: HolderLookup.Provider) { + owner.genData(type, this) + } + + override fun getSide(): LogicalSide = LogicalSide.SERVER + + override fun rawBuilder(key: TagKey): TagBuilder = super.getOrCreateRawBuilder(key) + + override fun tag(key: TagKey): IntrinsicTagAppender = super.tag(key) + + override fun getFilledProvider(): CompletableFuture = createContentsProvider() + + override fun registry(): ResourceKey> = registryKey + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt b/src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt new file mode 100644 index 0000000..d3779dc --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt @@ -0,0 +1,48 @@ +package com.modularmc.registrate.providers.core + +import com.modularmc.registrate.localization.resolution.TranslationRegistry + +import net.minecraft.data.CachedOutput +import net.minecraft.data.DataProvider +import net.minecraft.data.PackOutput +import net.neoforged.neoforge.data.event.GatherDataEvent + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap + +import java.nio.file.Path +import java.util.concurrent.CompletableFuture + +/** Groups the providers attached to the same output before NeoForge starts the DataGen run. */ +internal class DataGenBatch private constructor(private val output: PackOutput, private val root: Path) : DataProvider { + private val participants = ArrayList() + + override fun run(cache: CachedOutput): CompletableFuture<*> { + synchronized(pending) { pending.remove(root) } + participants.sortBy(RegistrateDataProvider::getName) + return run(cache, output, participants) + } + + override fun getName(): String = "Registrate data and languages" + + companion object { + private val pending = Object2ObjectOpenHashMap() + + fun attach(event: GatherDataEvent, provider: RegistrateDataProvider) { + val output = event.generator.packOutput + val root = output.outputFolder.toAbsolutePath().normalize() + synchronized(pending) { + val batch = pending.getOrPut(root) { event.addProvider(DataGenBatch(output, root)) } + batch.participants.add(provider) + } + } + + fun run(cache: CachedOutput, output: PackOutput, participants: List): CompletableFuture<*> { + val runs = Array(participants.size) { participants[it].runResources(cache) } + return CompletableFuture.allOf(*runs).thenCompose { + val translations = TranslationRegistry() + for (provider in participants) provider.collectTranslations(translations) + LanguageOutput.write(cache, output, translations) + } + } + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java b/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java deleted file mode 100644 index 2113cbd..0000000 --- a/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.modularmc.registrate.providers.core; - -import net.minecraft.core.Registry; -import net.minecraft.core.RegistrySetBuilder; -import net.minecraft.resources.ResourceKey; - -import org.jspecify.annotations.Nullable; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -public class DataProviderInitializer { - - private final RegistrySetBuilder datapackEntryProvider = new RegistrySetBuilder(); - - private final Map, ProviderType> providerDependencies = new ConcurrentHashMap<>(); - - public DataProviderInitializer() { - addDependency(ProviderType.ITEM_TAGS, ProviderType.BLOCK_TAGS); - } - - public RegistrySetBuilder getDatapackRegistryProviders() { - return datapackEntryProvider; - } - - protected List getSortedProviders() { - List ans = new ArrayList<>(); - Set> added = new HashSet<>(); - List>> remain = new ArrayList<>(RegistrateDataProvider.TYPES.entrySet()); - while (!remain.isEmpty()) { - if (!remain.removeIf(e -> { - ProviderType type = e.getValue(); - var parent = providerDependencies.get(type); - if (parent == null || added.contains(parent)) { - ans.add(new Sorted(e.getKey(), type, parent)); - added.add(type); - return true; - } - return false; - })) throw new IllegalStateException("Looping dependency detected: " + remain); - } - return ans; - } - - public void add(ResourceKey> registry, RegistrySetBuilder.RegistryBootstrap provider) { - datapackEntryProvider.add(registry, provider); - } - - public void addDependency(ProviderType dependent, ProviderType parent) { - var old = providerDependencies.put(dependent, parent); - if (old != null) throw new IllegalStateException("Providers can have only 1 prerequisite"); - } - - public record Sorted( - String id, ProviderType type, - @Nullable ProviderType parent) {} -} diff --git a/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.kt b/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.kt new file mode 100644 index 0000000..0003543 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/DataProviderInitializer.kt @@ -0,0 +1,52 @@ +package com.modularmc.registrate.providers.core + +import net.minecraft.core.Registry +import net.minecraft.core.RegistrySetBuilder +import net.minecraft.resources.ResourceKey + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.concurrent.ConcurrentHashMap + +open class DataProviderInitializer { + private val datapackEntries = RegistrySetBuilder() + private val dependencies = ConcurrentHashMap, ProviderType>() + + init { + addDependency(ProviderType.ITEM_TAGS, ProviderType.BLOCK_TAGS) + } + + open fun getDatapackRegistryProviders(): RegistrySetBuilder = datapackEntries + + open fun getSortedProviders(): List { + val remaining = RegistrateDataProvider.TYPES.entries.sortedBy { it.key }.toMutableList() + val result = ArrayList(remaining.size) + val added = ObjectOpenHashSet>(remaining.size) + while (remaining.isNotEmpty()) { + val previousSize = remaining.size + val iterator = remaining.iterator() + while (iterator.hasNext()) { + val (id, type) = iterator.next() + val parent = dependencies[type] + if (parent == null || parent in added) { + result.add(Sorted(id, type, parent)) + added.add(type) + iterator.remove() + } + } + check(remaining.size != previousSize) { "Looping dependency detected: $remaining" } + } + return result + } + + open fun add(registry: ResourceKey>, provider: RegistrySetBuilder.RegistryBootstrap) { + datapackEntries.add(registry, provider) + } + + open fun addDependency(dependent: ProviderType<*>, parent: ProviderType) { + check(dependencies.putIfAbsent(dependent, parent) == null) { "Providers can have only 1 prerequisite" } + } + + @JvmRecord + data class Sorted(val id: String, val type: ProviderType<*>, val parent: ProviderType?) +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java b/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java deleted file mode 100644 index 9c156c0..0000000 --- a/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.java +++ /dev/null @@ -1,3 +0,0 @@ -package com.modularmc.registrate.providers.core; - -public interface GeneratorType {} diff --git a/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.kt b/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.kt new file mode 100644 index 0000000..69b1816 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/GeneratorType.kt @@ -0,0 +1,4 @@ +package com.modularmc.registrate.providers.core + +/** Typed key for callbacks that run against a provider or one of its generators. */ +interface GeneratorType diff --git a/src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt b/src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt new file mode 100644 index 0000000..886aa50 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt @@ -0,0 +1,30 @@ +package com.modularmc.registrate.providers.core + +import com.modularmc.registrate.localization.resolution.TranslationRegistry + +import net.minecraft.data.CachedOutput +import net.minecraft.data.DataProvider +import net.minecraft.data.PackOutput +import net.minecraft.data.PackOutput.Target +import net.minecraft.resources.ResourceLocation + +import com.google.gson.JsonObject + +import java.util.concurrent.CompletableFuture + +object LanguageOutput { + @JvmStatic + fun write(cache: CachedOutput, output: PackOutput, registry: TranslationRegistry): CompletableFuture<*> { + val paths = output.createPathProvider(Target.RESOURCE_PACK, "lang") + val files = registry.resolve() + val entries = files.entries.iterator() + val writes = Array(files.size) { + val (file, texts) = entries.next() + val path = paths.json(ResourceLocation.fromNamespaceAndPath(file.namespace, file.locale.code())) + val language = JsonObject() + texts.forEach(language::addProperty) + DataProvider.saveStable(cache, language, path) + } + return CompletableFuture.allOf(*writes) + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java deleted file mode 100644 index 484d360..0000000 --- a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.modularmc.registrate.providers.core; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.RegistrateAdvancementProvider; -import com.modularmc.registrate.providers.RegistrateDataMapProvider; -import com.modularmc.registrate.providers.RegistrateDatapackProvider; -import com.modularmc.registrate.providers.RegistrateGenericProvider; -import com.modularmc.registrate.providers.RegistrateItemTagsProvider; -import com.modularmc.registrate.providers.RegistrateLangProvider; -import com.modularmc.registrate.providers.RegistrateTagsProvider; -import com.modularmc.registrate.providers.RegistrateTagsProvider.IntrinsicTags; -import com.modularmc.registrate.providers.RegistrateTagsProvider.KeyTags; -import com.modularmc.registrate.providers.generators.RegistrateBlockModelGenerator; -import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator; -import com.modularmc.registrate.providers.generators.RegistrateModelProvider; -import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; -import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.HolderLookup; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.item.enchantment.Enchantment; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.material.Fluid; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.data.ExistingFileHelper; -import net.neoforged.neoforge.data.loading.DatagenModLoader; - -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.function.Function; - -/** - * Represents a type of data that can be generated, and specifies a factory for the provider. - *

- * Used as a key for data generator callbacks. - *

- * This file also defines the built-in provider types, but third-party types can be created with - * {@link #registerProvider(String, ProviderType)}. - * - * @param The type of the provider - */ -@FunctionalInterface -public interface ProviderType extends GeneratorType { - - // SERVER DATA - ProviderType DYNAMIC = registerServerData("dynamic", RegistrateDatapackProvider::new); - ProviderType DATA_MAP = registerServerData("data_map", RegistrateDataMapProvider::new); - ProviderType RECIPE = registerServerData("recipe", RegistrateRecipeProvider::new); - ProviderType ADVANCEMENT = registerServerData("advancement", RegistrateAdvancementProvider::new); - ProviderType LOOT = registerServerData("loot", RegistrateLootTableProvider::new); - ProviderType> BLOCK_TAGS = registerIntrinsicTag("tags/block", "blocks", Registries.BLOCK, BuiltInRegistries.BLOCK); - ProviderType> ENCHANTMENT_TAGS = registerDynamicTag("tags/enchantment", "enchantments", Registries.ENCHANTMENT); - ProviderType ITEM_TAGS = registerTag("tags/item", Registries.ITEM, c -> new RegistrateItemTagsProvider(c.parent(), c.type(), "items", c.output(), c.provider(), c.require(BLOCK_TAGS).contentsGetter(), c.fileHelper())); - ProviderType> FLUID_TAGS = registerIntrinsicTag("tags/fluid", "fluids", Registries.FLUID, BuiltInRegistries.FLUID); - ProviderType>> ENTITY_TAGS = registerIntrinsicTag("tags/entity", "entity_types", Registries.ENTITY_TYPE, BuiltInRegistries.ENTITY_TYPE); - ProviderType GENERIC_SERVER = registerProvider("registrate_generic_server_provider", c -> new RegistrateGenericProvider(c.parent(), c.output(), c.provider(), LogicalSide.SERVER, c.type())); - - // CLIENT DATA - ProviderType MODEL = registerClientProvider("model", () -> c -> new RegistrateModelProvider(c.parent(), c.output(), c.fileHelper())); - ProviderType LANG = registerClientProvider("lang", () -> c -> new RegistrateLangProvider(c.parent(), c.output())); - ProviderType GENERIC_CLIENT = registerClientProvider("registrate_generic_client_provider", () -> c -> new RegistrateGenericProvider(c.parent(), c.output(), c.provider(), LogicalSide.CLIENT, c.type())); - - GeneratorType BLOCKSTATE = MODEL.createGenerator("blockstate"); - GeneratorType ITEM_MODEL = MODEL.createGenerator("item_model"); - - record Context(ProviderType type, AbstractRegistrate parent, - Map, RegistrateProvider> existing, - PackOutput output, - CompletableFuture provider, - ExistingFileHelper fileHelper) { - - public R require(ProviderType other) { - return other.cast(Objects.requireNonNull( - existing().get(other), - () -> "Missing provider dependency for " + RegistrateDataProvider.getTypeName(other))); - } - } - - T create(Context context); - - @SuppressWarnings("unchecked") - default T cast(RegistrateProvider provider) { - return (T) provider; - } - - default GeneratorType createGenerator(String type) { - return new GeneratorType<>() { - - public String toString() { - return type; - } - }; - } - - interface SimpleServerDataFactory extends ProviderType { - - T create(AbstractRegistrate parent, PackOutput output, CompletableFuture provider); - - @Override - default T create(Context context) { - return create(context.parent(), context.output(), context.provider()); - } - - default ProviderType asProvider() { - return this; - } - } - - static ProviderType registerServerData(String name, SimpleServerDataFactory factory) { - return registerProvider(name, factory.asProvider()); - } - - static ProviderType registerProvider(String name, ProviderType type) { - RegistrateDataProvider.TYPES.put(name, type); - return type; - } - - static ProviderType registerClientProvider(String name, NonNullSupplier> supplier) { - ProviderType type = DatagenModLoader.isRunningDataGen() ? supplier.get() : context -> { - throw new IllegalStateException("Client datagen provider '" + name + "' is unavailable outside datagen"); - }; - RegistrateDataProvider.TYPES.put(name, type); - return type; - } - - @SuppressWarnings("unchecked") - static > ProviderType registerTag(String name, ResourceKey> key, ProviderType type) { - if (RegistrateDataProvider.TAG_TYPES.containsKey(key)) { - return (ProviderType) RegistrateDataProvider.TAG_TYPES.get(key); - } - RegistrateDataProvider.TAG_TYPES.put(key, type); - RegistrateDataProvider.TYPES.put(name, type); - return type; - } - - static ProviderType> registerIntrinsicTag(String providerName, String typeName, ResourceKey> registryKey, Registry registry) { - return registerTag(providerName, registryKey, c -> new IntrinsicTags<>(c.parent(), c.type(), typeName, c.output(), registryKey, c.provider(), keyExtractor(registry, typeName), c.fileHelper())); - } - - static ProviderType> registerDynamicTag(String providerName, String typeName, ResourceKey> registry) { - return registerTag(providerName, registry, c -> new KeyTags<>(c.parent(), c.type(), typeName, c.output(), registry, c.provider(), c.fileHelper())); - } - - static T create(ProviderType type, AbstractRegistrate parent, Map, RegistrateProvider> existing, PackOutput output, CompletableFuture provider, ExistingFileHelper fileHelper) { - return type.create(new Context<>(type, parent, existing, output, provider, fileHelper)); - } - - private static Function> keyExtractor(Registry registry, String typeName) { - return value -> registry.getResourceKey(value) - .orElseThrow(() -> new IllegalStateException("Cannot generate tags for unregistered " + typeName + " entry: " + value)); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt new file mode 100644 index 0000000..6b908d7 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt @@ -0,0 +1,190 @@ +package com.modularmc.registrate.providers.core + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.RegistrateAdvancementProvider +import com.modularmc.registrate.providers.RegistrateDataMapProvider +import com.modularmc.registrate.providers.RegistrateDatapackProvider +import com.modularmc.registrate.providers.RegistrateGenericProvider +import com.modularmc.registrate.providers.RegistrateItemTagsProvider +import com.modularmc.registrate.providers.RegistrateLangProvider +import com.modularmc.registrate.providers.RegistrateTagsProvider +import com.modularmc.registrate.providers.RegistrateTagsProvider.IntrinsicTags +import com.modularmc.registrate.providers.RegistrateTagsProvider.KeyTags +import com.modularmc.registrate.providers.generators.RegistrateBlockModelGenerator +import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator +import com.modularmc.registrate.providers.generators.RegistrateModelProvider +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider +import com.modularmc.registrate.providers.loot.RegistrateLootTableProvider +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.HolderLookup +import net.minecraft.core.Registry +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.core.registries.Registries +import net.minecraft.data.PackOutput +import net.minecraft.resources.ResourceKey +import net.minecraft.world.item.Item +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.data.ExistingFileHelper +import net.neoforged.neoforge.data.loading.DatagenModLoader + +import java.util.concurrent.CompletableFuture +import java.util.function.Function + +/** A typed key and factory for a provider created during GatherData. */ +fun interface ProviderType : GeneratorType { + /** Creates this provider with lookups and already-constructed dependencies from this DataGen run. */ + fun create(context: Context): T + + @Suppress("UNCHECKED_CAST") + fun cast(provider: RegistrateProvider): T = provider as T + + fun createGenerator(type: String): GeneratorType = object : GeneratorType { + override fun toString(): String = type + } + + @JvmRecord + data class Context( + val type: ProviderType, + val parent: AbstractRegistrate<*>, + val existing: Map, RegistrateProvider>, + val output: PackOutput, + val provider: CompletableFuture, + val fileHelper: ExistingFileHelper, + ) { + fun require(other: ProviderType): R = other.cast(existing.getValue(other)) + } + + /** Creates a server provider from its owning Registrate, output and registry lookups. */ + fun interface SimpleServerDataFactory : ProviderType { + fun create(parent: AbstractRegistrate<*>, output: PackOutput, provider: CompletableFuture): T + + override fun create(context: Context): T = create(context.parent, context.output, context.provider) + + fun asProvider(): ProviderType = this + } + + companion object { + @JvmField + val DYNAMIC = registerServerData("dynamic", ::RegistrateDatapackProvider) + + @JvmField + val DATA_MAP = registerServerData("data_map", ::RegistrateDataMapProvider) + + @JvmField + val RECIPE = registerServerData("recipe", ::RegistrateRecipeProvider) + + @JvmField + val ADVANCEMENT = registerServerData("advancement", ::RegistrateAdvancementProvider) + + @JvmField + val LOOT = registerServerData("loot", ::RegistrateLootTableProvider) + + @JvmField + val BLOCK_TAGS = registerIntrinsicTag("tags/block", "blocks", Registries.BLOCK, BuiltInRegistries.BLOCK) + + @JvmField + val ENCHANTMENT_TAGS = registerDynamicTag("tags/enchantment", "enchantments", Registries.ENCHANTMENT) + + @JvmField + val ITEM_TAGS = registerTag( + "tags/item", + Registries.ITEM, + ) { + RegistrateItemTagsProvider( + it.parent, + it.type, + "items", + it.output, + it.provider, + it.require(BLOCK_TAGS).contentsGetter(), + it.fileHelper, + ) + } + + @JvmField + val FLUID_TAGS = registerIntrinsicTag("tags/fluid", "fluids", Registries.FLUID, BuiltInRegistries.FLUID) + + @JvmField + val ENTITY_TAGS = registerIntrinsicTag("tags/entity", "entity_types", Registries.ENTITY_TYPE, BuiltInRegistries.ENTITY_TYPE) + + @JvmField + val GENERIC_SERVER = registerProvider( + "registrate_generic_server_provider", + ) { + RegistrateGenericProvider(it.parent, it.output, it.provider, LogicalSide.SERVER, it.type) + } + + @JvmField + val MODEL = registerClientProvider("model") { + ProviderType { RegistrateModelProvider(it.parent, it.output, it.fileHelper) } + } + + @JvmField + val LANG = registerClientProvider("lang") { + ProviderType { RegistrateLangProvider(it.parent, it.output) } + } + + @JvmField + val GENERIC_CLIENT = registerClientProvider("registrate_generic_client_provider") { + ProviderType { RegistrateGenericProvider(it.parent, it.output, it.provider, LogicalSide.CLIENT, it.type) } + } + + @JvmField + val BLOCKSTATE = MODEL.createGenerator("blockstate") + + @JvmField + val ITEM_MODEL = MODEL.createGenerator("item_model") + + @JvmStatic + fun registerServerData(name: String, factory: SimpleServerDataFactory): ProviderType = registerProvider(name, factory.asProvider()) + + @JvmStatic + fun registerProvider(name: String, type: ProviderType): ProviderType { + RegistrateDataProvider.TYPES[name] = type + return type + } + + @JvmStatic + fun registerClientProvider(name: String, supplier: NonNullSupplier>): ProviderType { + val type = if (DatagenModLoader.isRunningDataGen()) { + supplier.get() + } else { + ProviderType { + error("Client datagen provider '$name' is unavailable outside datagen") + } + } + RegistrateDataProvider.CLIENT_TYPES.add(type) + return registerProvider(name, type) + } + + @JvmStatic + @Suppress("UNCHECKED_CAST") + fun > registerTag(name: String, key: ResourceKey>, type: ProviderType): ProviderType { + val existing = RegistrateDataProvider.TAG_TYPES.putIfAbsent(key, type) + return if (existing == null) registerProvider(name, type) else existing as ProviderType + } + + @JvmStatic + fun registerIntrinsicTag(providerName: String, typeName: String, registryKey: ResourceKey>, registry: Registry): ProviderType> { + val key = Function> { value -> + registry.getResourceKey(value).orElseThrow { IllegalStateException("Cannot generate tags for unregistered $typeName entry: $value") } + } + return registerTag(providerName, registryKey) { IntrinsicTags(it.parent, it.type, typeName, it.output, registryKey, it.provider, key, it.fileHelper) } + } + + @JvmStatic + fun registerDynamicTag(providerName: String, typeName: String, registry: ResourceKey>): ProviderType> = + registerTag(providerName, registry) { KeyTags(it.parent, it.type, typeName, it.output, registry, it.provider, it.fileHelper) } + + @JvmStatic + fun create( + type: ProviderType, + parent: AbstractRegistrate<*>, + existing: Map, RegistrateProvider>, + output: PackOutput, + provider: CompletableFuture, + fileHelper: ExistingFileHelper, + ): T = type.create(Context(type, parent, existing, output, provider, fileHelper)) + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java deleted file mode 100644 index d942a5e..0000000 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.modularmc.registrate.providers.core; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.internal.util.DebugMarkers; -import com.modularmc.registrate.internal.util.RegistrateLogger; -import com.modularmc.registrate.providers.RegistrateTagsProvider; - -import net.minecraft.core.HolderLookup; -import net.minecraft.core.Registry; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataProvider; -import net.minecraft.resources.ResourceKey; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.data.event.GatherDataEvent; - -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.Lists; -import org.apache.logging.log4j.Logger; -import org.jspecify.annotations.Nullable; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -public class RegistrateDataProvider implements DataProvider { - - private static final Logger LOGGER = RegistrateLogger.datagen(); - - @SuppressWarnings("null") - static final BiMap> TYPES = HashBiMap.create(); - - static final Map>, ProviderType> TAG_TYPES = new ConcurrentHashMap<>(); - - public static @Nullable String getTypeName(GeneratorType type) { - if (type instanceof ProviderType prov) - return TYPES.inverse().get(prov); - return type.toString(); - } - - private final String mod; - private final Map, RegistrateProvider> subProviders = new LinkedHashMap<>(); - private final Map, Object> subGenerators = new ConcurrentHashMap<>(); - private final CompletableFuture registriesLookup; - - public RegistrateDataProvider(AbstractRegistrate parent, String modid, GatherDataEvent event) { - this.mod = modid; - this.registriesLookup = event.getLookupProvider(); - - LOGGER.debug(DebugMarkers.DATA, RegistrateLogger.modMessage("Collecting datagen providers"), mod); - Map, RegistrateProvider> known = new HashMap<>(); - for (DataProviderInitializer.Sorted sorted : parent.getDataGenInitializer().getSortedProviders()) { - ProviderType type = sorted.type(); - var lookup = registriesLookup; - if (sorted.parent() != null) lookup = ((RegistrateLookupFillerProvider) known.get(sorted.parent())).getFilledProvider(); - RegistrateProvider prov = ProviderType.create(type, parent, known, event.getGenerator().getPackOutput(), lookup, event.getExistingFileHelper()); - if (prov instanceof RegistrateTagsProvider tagsProvider && TAG_TYPES.get(tagsProvider.registry()) != type) { - throw new IllegalStateException("Tag providers must be registered through ProviderType::registerTag"); - } - known.put(type, prov); - if (prov.getSide() == LogicalSide.CLIENT ? event.includeClient() : event.includeServer()) { - LOGGER.debug( - DebugMarkers.DATA, - RegistrateLogger.modMessage("Added datagen provider {}"), - mod, - sorted.id()); - subProviders.put(type, prov); - } - } - } - - @Override - public CompletableFuture run(CachedOutput cache) { - return registriesLookup.thenCompose(provider -> { - var list = Lists.>newArrayList(); - - for (Map.Entry, RegistrateProvider> e : subProviders.entrySet()) { - LOGGER.debug( - DebugMarkers.DATA, - RegistrateLogger.modMessage("Running datagen provider {}"), - mod, - getTypeName(e.getKey())); - list.add(e.getValue().run(cache)); - } - - return CompletableFuture.allOf(list.toArray(CompletableFuture[]::new)); - }); - } - - @Override - public String getName() { - return "Registrate Provider for " + mod + " [" + subProviders.values().stream().map(DataProvider::getName).collect(Collectors.joining(", ")) + "]"; - } - - @SuppressWarnings("unchecked") - public

Optional

getSubProvider(GeneratorType

type) { - if (type instanceof ProviderType prov) - return Optional.ofNullable((P) subProviders.get(prov)); - return Optional.ofNullable((P) subGenerators.get(type)); - } - - public void putSubProvider(GeneratorType type, T gen) { - if (!(type instanceof ProviderType)) { - subGenerators.put(type, gen); - } - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt new file mode 100644 index 0000000..1ba814b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt @@ -0,0 +1,106 @@ +package com.modularmc.registrate.providers.core + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.internal.util.DebugMarkers +import com.modularmc.registrate.internal.util.RegistrateLogger +import com.modularmc.registrate.localization.resolution.TranslationRegistry +import com.modularmc.registrate.providers.RegistrateLangProvider +import com.modularmc.registrate.providers.RegistrateTagsProvider + +import net.minecraft.core.HolderLookup +import net.minecraft.core.Registry +import net.minecraft.data.CachedOutput +import net.minecraft.data.DataProvider +import net.minecraft.resources.ResourceKey +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.data.event.GatherDataEvent + +import com.google.common.collect.HashBiMap +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet + +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ConcurrentHashMap + +open class RegistrateDataProvider(parent: AbstractRegistrate<*>, private val mod: String, event: GatherDataEvent) : DataProvider { + private val output = event.generator.packOutput + private val registriesLookup: CompletableFuture = event.lookupProvider + private val subProviders = Object2ObjectLinkedOpenHashMap, RegistrateProvider>() + private val prerequisites = Object2ObjectOpenHashMap, ProviderType<*>>() + private val subGenerators = ConcurrentHashMap, Any>() + + init { + LOGGER.debug(DebugMarkers.DATA, RegistrateLogger.modMessage("Collecting datagen providers"), mod) + val sortedProviders = parent.dataGenInitializer.getSortedProviders() + val known = Object2ObjectOpenHashMap, RegistrateProvider>(sortedProviders.size) + for ((id, type, prerequisite) in sortedProviders) { + if (type in CLIENT_TYPES && !event.includeClient()) continue + + val dependency = known[prerequisite] as? RegistrateLookupFillerProvider + val lookup = dependency?.getFilledProvider() ?: registriesLookup + val provider = ProviderType.create(type, parent, known, output, lookup, event.existingFileHelper) + check(provider !is RegistrateTagsProvider<*> || TAG_TYPES[provider.registry()] === type) { + "Tag providers must be registered through ProviderType::registerTag" + } + known[type] = provider + val enabled = if (provider.getSide() == LogicalSide.CLIENT) event.includeClient() else event.includeServer() + if (enabled) { + if (prerequisite != null) { + check(subProviders.containsKey(prerequisite)) { "[$mod] Provider $id requires disabled provider ${getTypeName(prerequisite)}" } + prerequisites[type] = prerequisite + } + LOGGER.debug(DebugMarkers.DATA, RegistrateLogger.modMessage("Added datagen provider {}"), mod, id) + subProviders[type] = provider + } + } + } + + override fun run(cache: CachedOutput): CompletableFuture<*> = DataGenBatch.run(cache, output, listOf(this)) + + open fun attach(event: GatherDataEvent) { + DataGenBatch.attach(event, this) + } + + internal fun runResources(cache: CachedOutput): CompletableFuture<*> = registriesLookup.thenCompose { + val runs = Object2ObjectOpenHashMap, CompletableFuture<*>>(subProviders.size) + val iterator = subProviders.object2ObjectEntrySet().fastIterator() + while (iterator.hasNext()) { + val entry = iterator.next() + val type = entry.key + if (type === ProviderType.LANG) continue + + val provider = entry.value + val dependency = prerequisites[type] + runs[type] = if (dependency == null) provider.run(cache) else runs.getValue(dependency).thenCompose { provider.run(cache) } + } + CompletableFuture.allOf(*runs.values.toTypedArray()) + } + + internal fun collectTranslations(registry: TranslationRegistry) { + (subProviders[ProviderType.LANG] as? RegistrateLangProvider)?.collect(registry) + } + + override fun getName(): String = "Registrate Provider for $mod" + + @Suppress("UNCHECKED_CAST") + open fun

getSubProvider(type: GeneratorType

): Optional

{ + val provider = if (type is ProviderType<*>) subProviders[type] else subGenerators[type] + return Optional.ofNullable(provider as P?) + } + + open fun putSubProvider(type: GeneratorType, generator: T) { + if (type !is ProviderType<*>) subGenerators[type] = generator + } + + companion object { + private val LOGGER = RegistrateLogger.datagen() + internal val TYPES = HashBiMap.create>() + internal val TAG_TYPES = ConcurrentHashMap>, ProviderType<*>>() + internal val CLIENT_TYPES = ObjectOpenHashSet>() + + @JvmStatic + fun getTypeName(type: GeneratorType<*>): String? = if (type is ProviderType<*>) TYPES.inverse()[type] else type.toString() + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java deleted file mode 100644 index 84a7a40..0000000 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.modularmc.registrate.providers.core; - -import net.minecraft.core.HolderLookup; - -import java.util.concurrent.CompletableFuture; - -public interface RegistrateLookupFillerProvider extends RegistrateProvider { - - CompletableFuture getFilledProvider(); -} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.kt b/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.kt new file mode 100644 index 0000000..8664dc7 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateLookupFillerProvider.kt @@ -0,0 +1,10 @@ +package com.modularmc.registrate.providers.core + +import net.minecraft.core.HolderLookup + +import java.util.concurrent.CompletableFuture + +/** Supplies the registry lookups to use by dependent providers during DataGen. */ +interface RegistrateLookupFillerProvider : RegistrateProvider { + fun getFilledProvider(): CompletableFuture +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java deleted file mode 100644 index 46c9d06..0000000 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.modularmc.registrate.providers.core; - -import net.minecraft.data.DataProvider; -import net.neoforged.fml.LogicalSide; - -public interface RegistrateProvider extends DataProvider { - - LogicalSide getSide(); -} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.kt b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.kt new file mode 100644 index 0000000..4561c05 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProvider.kt @@ -0,0 +1,9 @@ +package com.modularmc.registrate.providers.core + +import net.minecraft.data.DataProvider +import net.neoforged.fml.LogicalSide + +/** A DataGen provider selected by the logical side requested by NeoForge. */ +interface RegistrateProvider : DataProvider { + fun getSide(): LogicalSide +} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java deleted file mode 100644 index 3e20c95..0000000 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.modularmc.registrate.providers.core; - -import net.minecraft.data.DataProvider; -import net.minecraft.resources.ResourceLocation; - -public interface RegistrateProviderDelegate extends DataProvider { - - String getName(); - - ResourceLocation getId(); - - T getEntry(); -} diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.kt b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.kt new file mode 100644 index 0000000..adfb5b4 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateProviderDelegate.kt @@ -0,0 +1,13 @@ +package com.modularmc.registrate.providers.core + +import net.minecraft.data.DataProvider +import net.minecraft.resources.ResourceLocation + +/** A provider delegate associated with a particular registered entry. */ +interface RegistrateProviderDelegate : DataProvider { + override fun getName(): String + + fun getId(): ResourceLocation + + fun getEntry(): T +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java deleted file mode 100644 index cb4ebeb..0000000 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.modularmc.registrate.providers.generators; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; - -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.Block; -import net.neoforged.neoforge.client.model.generators.BlockStateProvider; -import net.neoforged.neoforge.client.model.generators.MultiPartBlockStateBuilder; -import net.neoforged.neoforge.client.model.generators.VariantBlockStateBuilder; -import net.neoforged.neoforge.common.data.ExistingFileHelper; - -import com.google.gson.JsonElement; - -import java.util.Optional; - -public class RegistrateBlockModelGenerator extends BlockStateProvider { - - private final AbstractRegistrate parent; - private final RegistrateItemModelGenerator itemModels; - - public RegistrateBlockModelGenerator(AbstractRegistrate parent, PackOutput output, ExistingFileHelper fileHelper) { - super(output, parent.getModid(), fileHelper); - this.parent = parent; - this.itemModels = new RegistrateItemModelGenerator(parent, output, fileHelper); - } - - @Override - protected void registerStatesAndModels() { - parent.genData(ProviderType.BLOCKSTATE, this); - itemModels.registerModels(); - } - - @Override - public RegistrateItemModelGenerator itemModels() { - return itemModels; - } - - public void create(Block block, ResourceLocation model) { - simpleBlock(block, models().getExistingFile(model)); - } - - public void createTrivialCube(Block block) { - simpleBlock(block, models().cubeAll(modelLocation(block).getPath(), blockTexture(block))); - } - - public ResourceLocation mcBlockTexture(String path) { - return mcLoc("block/" + path); - } - - public ResourceLocation modBlockTexture(String path) { - return modLoc("block/" + path); - } - - public ResourceLocation blockTexture(Block block, String suffix) { - return blockTexture(block).withSuffix(suffix); - } - - public static ResourceLocation modelLocation(Block block) { - return BuiltInRegistries.BLOCK.getKey(block).withPrefix("block/"); - } - - public Optional getExistingVariantBuilder(Block block) { - return Optional.ofNullable(registeredBlocks.get(block)) - .filter(VariantBlockStateBuilder.class::isInstance) - .map(VariantBlockStateBuilder.class::cast); - } - - public Optional getExistingMultipartBuilder(Block block) { - return Optional.ofNullable(registeredBlocks.get(block)) - .filter(MultiPartBlockStateBuilder.class::isInstance) - .map(MultiPartBlockStateBuilder.class::cast); - } - - public Optional getSingleVariantModel(Block block) { - return getExistingVariantBuilder(block) - .map(builder -> builder.getModels().get(builder.partialState())) - .map(ConfiguredModelList::toJSON) - .filter(JsonElement::isJsonObject) - .map(json -> json.getAsJsonObject().get("model")) - .map(JsonElement::getAsString) - .map(ResourceLocation::parse); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.kt b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.kt new file mode 100644 index 0000000..0665f81 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateBlockModelGenerator.kt @@ -0,0 +1,57 @@ +package com.modularmc.registrate.providers.generators + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType + +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.data.PackOutput +import net.minecraft.resources.ResourceLocation +import net.minecraft.world.level.block.Block +import net.neoforged.neoforge.client.model.generators.BlockStateProvider +import net.neoforged.neoforge.client.model.generators.MultiPartBlockStateBuilder +import net.neoforged.neoforge.client.model.generators.VariantBlockStateBuilder +import net.neoforged.neoforge.common.data.ExistingFileHelper + +import com.google.gson.JsonElement + +import java.util.Optional + +open class RegistrateBlockModelGenerator(private val parent: AbstractRegistrate<*>, output: PackOutput, fileHelper: ExistingFileHelper) : BlockStateProvider(output, parent.modid, fileHelper) { + private val itemModels: RegistrateItemModelGenerator = RegistrateItemModelGenerator(parent, output, fileHelper) + + override fun registerStatesAndModels() { + parent.genData(ProviderType.BLOCKSTATE, this) + itemModels.registerModels() + } + + override fun itemModels(): RegistrateItemModelGenerator = itemModels + + fun create(block: Block, model: ResourceLocation) { + simpleBlock(block, models().getExistingFile(model)) + } + + fun createTrivialCube(block: Block) { + simpleBlock(block, models().cubeAll(modelLocation(block).path, blockTexture(block))) + } + + fun mcBlockTexture(path: String): ResourceLocation = mcLoc("block/$path") + + fun modBlockTexture(path: String): ResourceLocation = modLoc("block/$path") + + fun blockTexture(block: Block, suffix: String): ResourceLocation = blockTexture(block).withSuffix(suffix) + + open fun getExistingVariantBuilder(block: Block): Optional = Optional.ofNullable(registeredBlocks[block] as? VariantBlockStateBuilder) + + open fun getExistingMultipartBuilder(block: Block): Optional = Optional.ofNullable(registeredBlocks[block] as? MultiPartBlockStateBuilder) + + open fun getSingleVariantModel(block: Block): Optional = getExistingVariantBuilder(block) + .map { it.models[it.partialState()]?.toJSON() } + .filter(JsonElement::isJsonObject) + .map { it.asJsonObject.get("model") } + .map { ResourceLocation.parse(it.asString) } + + companion object { + @JvmStatic + fun modelLocation(block: Block): ResourceLocation = BuiltInRegistries.BLOCK.getKey(block).withPrefix("block/") + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java deleted file mode 100644 index 0e6c97c..0000000 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.modularmc.registrate.providers.generators; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.data.PackOutput; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.material.Fluid; -import net.neoforged.neoforge.client.model.generators.ItemModelBuilder; -import net.neoforged.neoforge.client.model.generators.ItemModelProvider; -import net.neoforged.neoforge.client.model.generators.loaders.DynamicFluidContainerModelBuilder; -import net.neoforged.neoforge.common.data.ExistingFileHelper; - -import java.util.function.UnaryOperator; - -public class RegistrateItemModelGenerator extends ItemModelProvider { - - private final AbstractRegistrate parent; - - public RegistrateItemModelGenerator(AbstractRegistrate parent, PackOutput output, ExistingFileHelper fileHelper) { - super(output, parent.getModid(), fileHelper); - this.parent = parent; - } - - @Override - protected void registerModels() { - parent.genData(ProviderType.ITEM_MODEL, this); - } - - public boolean hasModel(Item item) { - return generatedModels.containsKey(itemLocation(item)); - } - - public ItemModelBuilder createWithExistingModel(Item item, ResourceLocation model) { - return withExistingParent(itemLocation(item).toString(), model); - } - - public ItemModelBuilder generateFlatItem(Item item, ResourceLocation texture) { - return generateFlatItem(item, mcLoc("item/generated"), texture); - } - - public ItemModelBuilder generateFlatItem(Item item, ResourceLocation parentModel, ResourceLocation texture) { - return createWithExistingModel(item, parentModel).texture("layer0", texture); - } - - public ItemModelBuilder generateFlatBlockItem(BlockItem item) { - return generateFlatBlockItem(item, ""); - } - - public ItemModelBuilder generateFlatBlockItem(BlockItem item, String suffix) { - return generateFlatItem(item, RegistrateBlockModelGenerator.modelLocation(item.getBlock()).withSuffix(suffix)); - } - - public ItemModelBuilder generateBlockItem(BlockItem item, UnaryOperator modelMapper) { - return createWithExistingModel(item, modelMapper.apply(RegistrateBlockModelGenerator.modelLocation(item.getBlock()))); - } - - public ItemModelBuilder generateBlockItem(BlockItem item, String suffix) { - return generateBlockItem(item, model -> model.withSuffix(suffix)); - } - - public ResourceLocation mcBlockTexture(String path) { - return mcLoc("block/" + path); - } - - public ResourceLocation modBlockTexture(String path) { - return modLoc("block/" + path); - } - - public ResourceLocation mcItemTexture(String path) { - return mcLoc("item/" + path); - } - - public ResourceLocation modItemTexture(String path) { - return modLoc("item/" + path); - } - - public String modid(NonNullSupplier item) { - return BuiltInRegistries.ITEM.getKey(item.get().asItem()).getNamespace(); - } - - public String name(NonNullSupplier item) { - return BuiltInRegistries.ITEM.getKey(item.get().asItem()).getPath(); - } - - public void generateFluidBucket(Item item, Fluid fluid) { - getBuilder(itemLocation(item).toString()) - .texture("particle", mcItemTexture("bucket")) - .texture("base", mcItemTexture("bucket")) - .texture("fluid", ResourceLocation.fromNamespaceAndPath("neoforge", "item/mask/bucket_fluid")) - .customLoader(DynamicFluidContainerModelBuilder::begin) - .fluid(fluid) - .flipGas(true) - .applyFluidLuminosity(true) - .end(); - } - - private static ResourceLocation itemLocation(Item item) { - return BuiltInRegistries.ITEM.getKey(item).withPrefix("item/"); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.kt b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.kt new file mode 100644 index 0000000..4acb43c --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateItemModelGenerator.kt @@ -0,0 +1,75 @@ +package com.modularmc.registrate.providers.generators + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.data.PackOutput +import net.minecraft.resources.ResourceLocation +import net.minecraft.world.item.BlockItem +import net.minecraft.world.item.Item +import net.minecraft.world.level.ItemLike +import net.minecraft.world.level.material.Fluid +import net.neoforged.neoforge.client.model.generators.ItemModelBuilder +import net.neoforged.neoforge.client.model.generators.ItemModelProvider +import net.neoforged.neoforge.client.model.generators.loaders.DynamicFluidContainerModelBuilder +import net.neoforged.neoforge.common.data.ExistingFileHelper + +import java.util.function.UnaryOperator + +open class RegistrateItemModelGenerator(private val parent: AbstractRegistrate<*>, output: PackOutput, private val fileHelper: ExistingFileHelper) : + ItemModelProvider(output, parent.modid, fileHelper) { + public override fun registerModels() { + parent.genData(ProviderType.ITEM_MODEL, this) + } + + fun hasModel(item: Item): Boolean = generatedModels.containsKey(itemLocation(item)) + + fun createWithExistingModel(item: Item, model: ResourceLocation): ItemModelBuilder = withExistingParent(itemLocation(item).toString(), model) + + fun generateFlatItem(item: Item, texture: ResourceLocation): ItemModelBuilder = generateFlatItem(item, mcLoc("item/generated"), texture) + + fun generateFlatItem(item: Item, parentModel: ResourceLocation, texture: ResourceLocation): ItemModelBuilder = createWithExistingModel(item, parentModel).texture("layer0", texture) + + @JvmOverloads + fun generateFlatBlockItem(item: BlockItem, suffix: String = ""): ItemModelBuilder = generateFlatItem( + item, + RegistrateBlockModelGenerator.modelLocation(item.block).withSuffix(suffix), + ) + + fun generateBlockItem(item: BlockItem, modelMapper: UnaryOperator): ItemModelBuilder = createWithExistingModel( + item, + modelMapper.apply(RegistrateBlockModelGenerator.modelLocation(item.block)), + ) + + fun generateBlockItem(item: BlockItem, suffix: String): ItemModelBuilder = generateBlockItem(item) { model: ResourceLocation -> model.withSuffix(suffix) } + + fun mcBlockTexture(path: String): ResourceLocation = mcLoc("block/$path") + + fun modBlockTexture(path: String): ResourceLocation = modLoc("block/$path") + + fun mcItemTexture(path: String): ResourceLocation = mcLoc("item/$path") + + fun modItemTexture(path: String): ResourceLocation = modLoc("item/$path") + + fun modid(item: NonNullSupplier): String = BuiltInRegistries.ITEM.getKey(item.get().asItem()).namespace + + fun name(item: NonNullSupplier): String = BuiltInRegistries.ITEM.getKey(item.get().asItem()).path + + fun generateFluidBucket(item: Item, fluid: Fluid) { + getBuilder(itemLocation(item).toString()) + .texture("particle", mcItemTexture("bucket")) + .texture("base", mcItemTexture("bucket")) + .texture("fluid", ResourceLocation.fromNamespaceAndPath("neoforge", "item/mask/bucket_fluid")) + .customLoader { model, _ -> DynamicFluidContainerModelBuilder.begin(model, fileHelper) } + .fluid(fluid) + .flipGas(true) + .applyFluidLuminosity(true) + .end() + } + + companion object { + private fun itemLocation(item: Item): ResourceLocation = BuiltInRegistries.ITEM.getKey(item).withPrefix("item/") + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java deleted file mode 100644 index c3656b0..0000000 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.modularmc.registrate.providers.generators; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.RegistrateProvider; - -import net.minecraft.data.PackOutput; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.data.ExistingFileHelper; - -public class RegistrateModelProvider extends RegistrateBlockModelGenerator implements RegistrateProvider { - - public RegistrateModelProvider(AbstractRegistrate parent, PackOutput output, ExistingFileHelper fileHelper) { - super(parent, output, fileHelper); - } - - @Override - public String getName() { - return "Blockstates and item models"; - } - - @Override - public LogicalSide getSide() { - return LogicalSide.CLIENT; - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.kt b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.kt new file mode 100644 index 0000000..5816ee3 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateModelProvider.kt @@ -0,0 +1,16 @@ +package com.modularmc.registrate.providers.generators + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.RegistrateProvider + +import net.minecraft.data.PackOutput +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.data.ExistingFileHelper + +open class RegistrateModelProvider(parent: AbstractRegistrate<*>, output: PackOutput, fileHelper: ExistingFileHelper) : + RegistrateBlockModelGenerator(parent, output, fileHelper), + RegistrateProvider { + override fun getName(): String = "Blockstates and item models" + + override fun getSide(): LogicalSide = LogicalSide.CLIENT +} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java deleted file mode 100644 index 515a542..0000000 --- a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.java +++ /dev/null @@ -1,636 +0,0 @@ -package com.modularmc.registrate.providers.generators; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.core.RegistrateProvider; -import com.modularmc.registrate.util.DataIngredient; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.advancements.Advancement; -import net.minecraft.advancements.AdvancementHolder; -import net.minecraft.advancements.Criterion; -import net.minecraft.advancements.critereon.EnterBlockTrigger; -import net.minecraft.advancements.critereon.InventoryChangeTrigger; -import net.minecraft.advancements.critereon.ItemPredicate; -import net.minecraft.advancements.critereon.MinMaxBounds; -import net.minecraft.core.Holder; -import net.minecraft.core.HolderLookup; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.BlockFamily; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.PackOutput; -import net.minecraft.data.recipes.RecipeBuilder; -import net.minecraft.data.recipes.RecipeCategory; -import net.minecraft.data.recipes.RecipeOutput; -import net.minecraft.data.recipes.RecipeProvider; -import net.minecraft.data.recipes.ShapedRecipeBuilder; -import net.minecraft.data.recipes.ShapelessRecipeBuilder; -import net.minecraft.data.recipes.SimpleCookingRecipeBuilder; -import net.minecraft.data.recipes.SingleItemRecipeBuilder; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.crafting.*; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.neoforged.fml.LogicalSide; -import net.neoforged.neoforge.common.Tags; -import net.neoforged.neoforge.common.conditions.ICondition; - -import com.google.common.collect.ImmutableMap; -import org.jspecify.annotations.Nullable; - -import java.util.List; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.function.Supplier; - -import javax.annotation.CheckReturnValue; -import javax.annotation.processing.Generated; - -public class RegistrateRecipeProvider extends RecipeProvider implements RegistrateProvider, RecipeOutput { - - private final AbstractRegistrate owner; - private final CompletableFuture lookupProvider; - private @Nullable RecipeOutput callback; - - public RegistrateRecipeProvider(AbstractRegistrate owner, PackOutput output, CompletableFuture lookupProvider) { - super(output, lookupProvider); - this.owner = owner; - this.lookupProvider = lookupProvider; - } - - public HolderLookup.Provider registries() { - return Objects.requireNonNull(lookupProvider.getNow(null), "Recipe registry lookup is not ready"); - } - - public HolderLookup itemLookup() { - return registries().lookupOrThrow(Registries.ITEM); - } - - public HolderLookup blockLookup() { - return registries().lookupOrThrow(Registries.BLOCK); - } - - public HolderLookup> entityLookup() { - return registries().lookupOrThrow(Registries.ENTITY_TYPE); - } - - public Holder resolve(ResourceKey key) { - return registries().lookupOrThrow(key.registryKey()).getOrThrow(key); - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } - - @Override - public void accept(ResourceLocation id, Recipe recipe, @Nullable AdvancementHolder advancement, ICondition... conditions) { - recipeOutput().accept(id, recipe, advancement, conditions); - } - - @Override - public Advancement.Builder advancement() { - return recipeOutput().advancement(); - } - - private RecipeOutput recipeOutput() { - return Objects.requireNonNull(callback, "Recipe output is only available inside a recipe callback"); - } - - @Override - protected void buildRecipes(RecipeOutput output) { - callback = output; - try { - owner.genData(ProviderType.RECIPE, this); - } finally { - callback = null; - } - } - - public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike result) { - return ShapedRecipeBuilder.shaped(category, result); - } - - public ShapedRecipeBuilder shaped(RecipeCategory category, ItemLike result, int count) { - return ShapedRecipeBuilder.shaped(category, result, count); - } - - public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike result) { - return ShapelessRecipeBuilder.shapeless(category, result); - } - - public ShapelessRecipeBuilder shapeless(RecipeCategory category, ItemLike result, int count) { - return ShapelessRecipeBuilder.shapeless(category, result, count); - } - - public ResourceLocation safeId(ResourceLocation id) { - return ResourceLocation.fromNamespaceAndPath(owner.getModid(), safeName(id)); - } - - public ResourceLocation safeId(DataIngredient source) { - return safeId(source.getId()); - } - - public ResourceLocation safeId(ItemLike registryEntry) { - return safeId(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); - } - - public String safeName(ResourceLocation id) { - return id.getPath().replace('/', '_'); - } - - public String safeName(DataIngredient source) { - return safeName(source.getId()); - } - - public String safeName(ItemLike registryEntry) { - return safeName(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())); - } - - public static final int DEFAULT_SMELT_TIME = 200; - public static final int DEFAULT_BLAST_TIME = DEFAULT_SMELT_TIME / 2; - public static final int DEFAULT_SMOKE_TIME = DEFAULT_BLAST_TIME; - public static final int DEFAULT_CAMPFIRE_TIME = DEFAULT_SMELT_TIME * 3; - - private static final ImmutableMap, String> COOKING_TYPE_NAMES = ImmutableMap., String>builder() - .put(RecipeSerializer.SMELTING_RECIPE, "smelting") - .put(RecipeSerializer.BLASTING_RECIPE, "blasting") - .put(RecipeSerializer.SMOKING_RECIPE, "smoking") - .put(RecipeSerializer.CAMPFIRE_COOKING_RECIPE, "campfire") - .build(); - - public void cooking(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime, RecipeSerializer serializer, AbstractCookingRecipe.Factory factory) { - cooking(source, category, result, experience, cookingTime, COOKING_TYPE_NAMES.get(serializer), serializer, factory); - } - - public void cooking(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime, String typeName, RecipeSerializer serializer, AbstractCookingRecipe.Factory factory) { - SimpleCookingRecipeBuilder.generic(source.toVanilla(), category, result.get(), experience, cookingTime, serializer, factory) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get()) + "_from_" + safeName(source) + "_" + typeName); - } - - public void smelting(DataIngredient source, RecipeCategory category, Supplier result, float experience) { - smelting(source, category, result, experience, DEFAULT_SMELT_TIME); - } - - public void smelting(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { - cooking(source, category, result, experience, cookingTime, RecipeSerializer.SMELTING_RECIPE, SmeltingRecipe::new); - } - - public void blasting(DataIngredient source, RecipeCategory category, Supplier result, float experience) { - blasting(source, category, result, experience, DEFAULT_BLAST_TIME); - } - - public void blasting(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { - cooking(source, category, result, experience, cookingTime, RecipeSerializer.BLASTING_RECIPE, BlastingRecipe::new); - } - - public void smoking(DataIngredient source, RecipeCategory category, Supplier result, float experience) { - smoking(source, category, result, experience, DEFAULT_SMOKE_TIME); - } - - public void smoking(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { - cooking(source, category, result, experience, cookingTime, RecipeSerializer.SMOKING_RECIPE, SmokingRecipe::new); - } - - public void campfire(DataIngredient source, RecipeCategory category, Supplier result, float experience) { - campfire(source, category, result, experience, DEFAULT_CAMPFIRE_TIME); - } - - public void campfire(DataIngredient source, RecipeCategory category, Supplier result, float experience, int cookingTime) { - cooking(source, category, result, experience, cookingTime, RecipeSerializer.CAMPFIRE_COOKING_RECIPE, CampfireCookingRecipe::new); - } - - public void stonecutting(DataIngredient source, RecipeCategory category, Supplier result) { - stonecutting(source, category, result, 1); - } - - public void stonecutting(DataIngredient source, RecipeCategory category, Supplier result, int resultAmount) { - SingleItemRecipeBuilder.stonecutting(source.toVanilla(), category, result.get(), resultAmount) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get()) + "_from_" + safeName(source) + "_stonecutting"); - } - - public void smeltingAndBlasting(DataIngredient source, RecipeCategory category, Supplier result, float xp) { - smelting(source, category, result, xp); - blasting(source, category, result, xp); - } - - public void food(DataIngredient source, RecipeCategory category, Supplier result, float xp) { - smelting(source, category, result, xp); - smoking(source, category, result, xp); - campfire(source, category, result, xp); - } - - public void square(DataIngredient source, RecipeCategory category, Supplier output, boolean small) { - ShapedRecipeBuilder builder = ShapedRecipeBuilder.shaped(category, output.get()) - .define('X', source.toVanilla()); - if (small) { - builder.pattern("XX").pattern("XX"); - } else { - builder.pattern("XXX").pattern("XXX").pattern("XXX"); - } - builder.unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(output.get())); - } - - /** - * @param - * @param source - * @param output - * @deprecated Broken, use {@link #storage(NonNullSupplier, RecipeCategory, NonNullSupplier)} or - * {@link #storage(DataIngredient, RecipeCategory, NonNullSupplier, DataIngredient, NonNullSupplier)}. - */ - @Deprecated - public void storage(DataIngredient source, RecipeCategory category, NonNullSupplier output) { - square(source, category, output, false); - // This is backwards, but leaving in for binary compat - singleItemUnfinished(source, category, output, 1, 9) - .save(this, safeId(source) + "_from_" + safeName(output.get())); - } - - public void storage(NonNullSupplier source, RecipeCategory category, NonNullSupplier output) { - storage(DataIngredient.items(source), category, source, DataIngredient.items(output), output); - } - - public void storage(DataIngredient sourceIngredient, RecipeCategory category, NonNullSupplier source, DataIngredient outputIngredient, NonNullSupplier output) { - square(sourceIngredient, category, output, false); - singleItemUnfinished(outputIngredient, category, source, 1, 9) - .save(this, safeId(sourceIngredient) + "_from_" + safeName(output.get())); - } - - @CheckReturnValue - public ShapelessRecipeBuilder singleItemUnfinished(DataIngredient source, RecipeCategory category, Supplier result, int required, int amount) { - return ShapelessRecipeBuilder.shapeless(category, result.get(), amount) - .requires(source.toVanilla(), required) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)); - } - - public void singleItem(DataIngredient source, RecipeCategory category, Supplier result, int required, int amount) { - singleItemUnfinished(source, category, result, required, amount).save(this, safeId(result.get())); - } - - public void planks(DataIngredient source, RecipeCategory category, Supplier result) { - singleItemUnfinished(source, category, result, 1, 4) - .group("planks") - .save(this, safeId(result.get())); - } - - public void stairs(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group, boolean stone) { - ShapedRecipeBuilder.shaped(category, result.get(), 4) - .pattern("X ").pattern("XX ").pattern("XXX") - .define('X', source.toVanilla()) - .group(group) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get())); - if (stone) { - stonecutting(source, category, result); - } - } - - public void slab(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group, boolean stone) { - ShapedRecipeBuilder.shaped(category, result.get(), 6) - .pattern("XXX") - .define('X', source.toVanilla()) - .group(group) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get())); - if (stone) { - stonecutting(source, category, result, 2); - } - } - - public void fence(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - ShapedRecipeBuilder.shaped(category, result.get(), 3) - .pattern("W#W").pattern("W#W") - .define('W', source.toVanilla()) - .define('#', Tags.Items.RODS_WOODEN) - .group(group) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get())); - } - - public void fenceGate(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - ShapedRecipeBuilder.shaped(category, result.get()) - .pattern("#W#").pattern("#W#") - .define('W', source.toVanilla()) - .define('#', Tags.Items.RODS_WOODEN) - .group(group) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get())); - } - - public void wall(DataIngredient source, RecipeCategory category, Supplier result) { - ShapedRecipeBuilder.shaped(category, result.get(), 6) - .pattern("XXX").pattern("XXX") - .define('X', source.toVanilla()) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get())); - stonecutting(source, category, result); - } - - public void door(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - ShapedRecipeBuilder.shaped(category, result.get(), 3) - .pattern("XX").pattern("XX").pattern("XX") - .define('X', source.toVanilla()) - .group(group) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get())); - } - - public void trapDoor(DataIngredient source, RecipeCategory category, Supplier result, @Nullable String group) { - ShapedRecipeBuilder.shaped(category, result.get(), 2) - .pattern("XXX").pattern("XXX") - .define('X', source.toVanilla()) - .group(group) - .unlockedBy("has_" + safeName(source), source.getCriterion(this)) - .save(this, safeId(result.get())); - } - - // @formatter:off - // GENERATED START - DO NOT EDIT BELOW THIS LINE - - /** Generated override to expose protected method: {@link RecipeProvider#buildAdvancement} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public CompletableFuture buildAdvancement(CachedOutput output, HolderLookup.Provider registries, AdvancementHolder advancement) { return super.buildAdvancement(output, registries, advancement); } - - /** Generated override to expose protected method: {@link RecipeProvider#buildAdvancement} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public CompletableFuture buildAdvancement(CachedOutput output, HolderLookup.Provider registries, AdvancementHolder advancement, ICondition... conditions) { return super.buildAdvancement(output, registries, advancement, conditions); } - - /** Generated override to expose protected method: {@link RecipeProvider#buildRecipes} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public void buildRecipes(RecipeOutput p_recipeOutput, HolderLookup.Provider holderLookup) { super.buildRecipes(p_recipeOutput, holderLookup); } - - /** Generated override to expose protected method: {@link RecipeProvider#generateForEnabledBlockFamilies} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public void generateForEnabledBlockFamilies(RecipeOutput enabledFeatures, FeatureFlagSet p_251836_) { super.generateForEnabledBlockFamilies(enabledFeatures, p_251836_); } - - /** Generated override to expose protected method: {@link RecipeProvider#netheriteSmithing} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void netheriteSmithing(RecipeOutput recipeOutput, Item ingredientItem, RecipeCategory category, Item resultItem) { RecipeProvider.netheriteSmithing(recipeOutput, ingredientItem, category, resultItem); } - - /** Generated override to expose protected method: {@link RecipeProvider#trimSmithing} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void trimSmithing(RecipeOutput recipeOutput, Item ingredientItem, ResourceLocation location) { RecipeProvider.trimSmithing(recipeOutput, ingredientItem, location); } - - /** Generated override to expose protected method: {@link RecipeProvider#twoByTwoPacker} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void twoByTwoPacker(RecipeOutput recipeOutput, RecipeCategory category, ItemLike packed, ItemLike unpacked) { RecipeProvider.twoByTwoPacker(recipeOutput, category, packed, unpacked); } - - /** Generated override to expose protected method: {@link RecipeProvider#threeByThreePacker} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void threeByThreePacker(RecipeOutput recipeOutput, RecipeCategory category, ItemLike packed, ItemLike unpacked, String criterionName) { RecipeProvider.threeByThreePacker(recipeOutput, category, packed, unpacked, criterionName); } - - /** Generated override to expose protected method: {@link RecipeProvider#threeByThreePacker} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void threeByThreePacker(RecipeOutput recipeOutput, RecipeCategory category, ItemLike packed, ItemLike unpacked) { RecipeProvider.threeByThreePacker(recipeOutput, category, packed, unpacked); } - - /** Generated override to expose protected method: {@link RecipeProvider#planksFromLog} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void planksFromLog(RecipeOutput recipeOutput, ItemLike planks, TagKey logs, int resultCount) { RecipeProvider.planksFromLog(recipeOutput, planks, logs, resultCount); } - - /** Generated override to expose protected method: {@link RecipeProvider#planksFromLogs} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void planksFromLogs(RecipeOutput recipeOutput, ItemLike planks, TagKey logs, int result) { RecipeProvider.planksFromLogs(recipeOutput, planks, logs, result); } - - /** Generated override to expose protected method: {@link RecipeProvider#woodFromLogs} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void woodFromLogs(RecipeOutput recipeOutput, ItemLike wood, ItemLike log) { RecipeProvider.woodFromLogs(recipeOutput, wood, log); } - - /** Generated override to expose protected method: {@link RecipeProvider#woodenBoat} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void woodenBoat(RecipeOutput recipeOutput, ItemLike boat, ItemLike material) { RecipeProvider.woodenBoat(recipeOutput, boat, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#chestBoat} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void chestBoat(RecipeOutput recipeOutput, ItemLike boat, ItemLike material) { RecipeProvider.chestBoat(recipeOutput, boat, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#buttonBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder buttonBuilder(ItemLike button, Ingredient material) { return RecipeProvider.buttonBuilder(button, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#doorBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder doorBuilder(ItemLike door, Ingredient material) { return RecipeProvider.doorBuilder(door, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#fenceBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder fenceBuilder(ItemLike fence, Ingredient material) { return RecipeProvider.fenceBuilder(fence, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#fenceGateBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder fenceGateBuilder(ItemLike fenceGate, Ingredient material) { return RecipeProvider.fenceGateBuilder(fenceGate, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#pressurePlate} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void pressurePlate(RecipeOutput recipeOutput, ItemLike pressurePlate, ItemLike material) { RecipeProvider.pressurePlate(recipeOutput, pressurePlate, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#pressurePlateBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder pressurePlateBuilder(RecipeCategory category, ItemLike pressurePlate, Ingredient material) { return RecipeProvider.pressurePlateBuilder(category, pressurePlate, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#slab} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void slab(RecipeOutput recipeOutput, RecipeCategory category, ItemLike slab, ItemLike material) { RecipeProvider.slab(recipeOutput, category, slab, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#slabBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder slabBuilder(RecipeCategory category, ItemLike slab, Ingredient material) { return RecipeProvider.slabBuilder(category, slab, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#stairBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder stairBuilder(ItemLike stairs, Ingredient material) { return RecipeProvider.stairBuilder(stairs, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#trapdoorBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder trapdoorBuilder(ItemLike trapdoor, Ingredient material) { return RecipeProvider.trapdoorBuilder(trapdoor, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#signBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder signBuilder(ItemLike sign, Ingredient material) { return RecipeProvider.signBuilder(sign, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#hangingSign} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void hangingSign(RecipeOutput recipeOutput, ItemLike sign, ItemLike material) { RecipeProvider.hangingSign(recipeOutput, sign, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#colorBlockWithDye} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void colorBlockWithDye(RecipeOutput recipeOutput, List dyes, List dyeableItems, String group) { RecipeProvider.colorBlockWithDye(recipeOutput, dyes, dyeableItems, group); } - - /** Generated override to expose protected method: {@link RecipeProvider#carpet} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void carpet(RecipeOutput recipeOutput, ItemLike carpet, ItemLike material) { RecipeProvider.carpet(recipeOutput, carpet, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#bedFromPlanksAndWool} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void bedFromPlanksAndWool(RecipeOutput recipeOutput, ItemLike bed, ItemLike wool) { RecipeProvider.bedFromPlanksAndWool(recipeOutput, bed, wool); } - - /** Generated override to expose protected method: {@link RecipeProvider#banner} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void banner(RecipeOutput recipeOutput, ItemLike banner, ItemLike material) { RecipeProvider.banner(recipeOutput, banner, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassFromGlassAndDye} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void stainedGlassFromGlassAndDye(RecipeOutput recipeOutput, ItemLike stainedGlass, ItemLike dye) { RecipeProvider.stainedGlassFromGlassAndDye(recipeOutput, stainedGlass, dye); } - - /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassPaneFromStainedGlass} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void stainedGlassPaneFromStainedGlass(RecipeOutput recipeOutput, ItemLike stainedGlassPane, ItemLike stainedGlass) { RecipeProvider.stainedGlassPaneFromStainedGlass(recipeOutput, stainedGlassPane, stainedGlass); } - - /** Generated override to expose protected method: {@link RecipeProvider#stainedGlassPaneFromGlassPaneAndDye} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void stainedGlassPaneFromGlassPaneAndDye(RecipeOutput recipeOutput, ItemLike stainedGlassPane, ItemLike dye) { RecipeProvider.stainedGlassPaneFromGlassPaneAndDye(recipeOutput, stainedGlassPane, dye); } - - /** Generated override to expose protected method: {@link RecipeProvider#coloredTerracottaFromTerracottaAndDye} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void coloredTerracottaFromTerracottaAndDye(RecipeOutput recipeOutput, ItemLike terracotta, ItemLike dye) { RecipeProvider.coloredTerracottaFromTerracottaAndDye(recipeOutput, terracotta, dye); } - - /** Generated override to expose protected method: {@link RecipeProvider#concretePowder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void concretePowder(RecipeOutput recipeOutput, ItemLike concretePowder, ItemLike dye) { RecipeProvider.concretePowder(recipeOutput, concretePowder, dye); } - - /** Generated override to expose protected method: {@link RecipeProvider#candle} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void candle(RecipeOutput recipeOutput, ItemLike candle, ItemLike dye) { RecipeProvider.candle(recipeOutput, candle, dye); } - - /** Generated override to expose protected method: {@link RecipeProvider#wall} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void wall(RecipeOutput recipeOutput, RecipeCategory category, ItemLike wall, ItemLike material) { RecipeProvider.wall(recipeOutput, category, wall, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#wallBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder wallBuilder(RecipeCategory category, ItemLike wall, Ingredient material) { return RecipeProvider.wallBuilder(category, wall, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#polished} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void polished(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material) { RecipeProvider.polished(recipeOutput, category, result, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#polishedBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static RecipeBuilder polishedBuilder(RecipeCategory category, ItemLike result, Ingredient material) { return RecipeProvider.polishedBuilder(category, result, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#cut} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void cut(RecipeOutput recipeOutput, RecipeCategory category, ItemLike cutResult, ItemLike material) { RecipeProvider.cut(recipeOutput, category, cutResult, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#cutBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static ShapedRecipeBuilder cutBuilder(RecipeCategory category, ItemLike cutResult, Ingredient material) { return RecipeProvider.cutBuilder(category, cutResult, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#chiseled} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void chiseled(RecipeOutput recipeOutput, RecipeCategory category, ItemLike chiseledResult, ItemLike material) { RecipeProvider.chiseled(recipeOutput, category, chiseledResult, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#mosaicBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void mosaicBuilder(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material) { RecipeProvider.mosaicBuilder(recipeOutput, category, result, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#chiseledBuilder} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static ShapedRecipeBuilder chiseledBuilder(RecipeCategory category, ItemLike chiseledResult, Ingredient material) { return RecipeProvider.chiseledBuilder(category, chiseledResult, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#stonecutterResultFromBase} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void stonecutterResultFromBase(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material) { RecipeProvider.stonecutterResultFromBase(recipeOutput, category, result, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#stonecutterResultFromBase} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void stonecutterResultFromBase(RecipeOutput recipeOutput, RecipeCategory category, ItemLike result, ItemLike material, int resultCount) { RecipeProvider.stonecutterResultFromBase(recipeOutput, category, result, material, resultCount); } - - /** Generated override to expose protected method: {@link RecipeProvider#smeltingResultFromBase} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void smeltingResultFromBase(RecipeOutput recipeOutput, ItemLike result, ItemLike ingredient) { RecipeProvider.smeltingResultFromBase(recipeOutput, result, ingredient); } - - /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void copySmithingTemplate(RecipeOutput recipeOutput, ItemLike template, TagKey baseMaterial) { RecipeProvider.copySmithingTemplate(recipeOutput, template, baseMaterial); } - - /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void copySmithingTemplate(RecipeOutput recipeOutput, ItemLike template, ItemLike baseItem) { RecipeProvider.copySmithingTemplate(recipeOutput, template, baseItem); } - - /** Generated override to expose protected method: {@link RecipeProvider#copySmithingTemplate} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void copySmithingTemplate(RecipeOutput recipeOutput, ItemLike template, Ingredient baseItem) { RecipeProvider.copySmithingTemplate(recipeOutput, template, baseItem); } - - /** Generated override to expose protected method: {@link RecipeProvider#waxRecipes} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void waxRecipes(RecipeOutput recipeOutput, FeatureFlagSet requiredFeatures) { RecipeProvider.waxRecipes(recipeOutput, requiredFeatures); } - - /** Generated override to expose protected method: {@link RecipeProvider#grate} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void grate(RecipeOutput recipeOutput, Block grateBlock, Block material) { RecipeProvider.grate(recipeOutput, grateBlock, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#copperBulb} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void copperBulb(RecipeOutput recipeOutput, Block bulbBlock, Block material) { RecipeProvider.copperBulb(recipeOutput, bulbBlock, material); } - - /** Generated override to expose protected method: {@link RecipeProvider#generateRecipes} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static void generateRecipes(RecipeOutput recipeOutput, BlockFamily blockFamily, FeatureFlagSet requiredFeatures) { RecipeProvider.generateRecipes(recipeOutput, blockFamily, requiredFeatures); } - - /** Generated override to expose protected method: {@link RecipeProvider#getBaseBlock} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static Block getBaseBlock(BlockFamily family, BlockFamily.Variant variant) { return RecipeProvider.getBaseBlock(family, variant); } - - /** Generated override to expose protected method: {@link RecipeProvider#insideOf} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static Criterion insideOf(Block block) { return RecipeProvider.insideOf(block); } - - /** Generated override to expose protected method: {@link RecipeProvider#has} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static Criterion has(MinMaxBounds.Ints count, ItemLike item) { return RecipeProvider.has(count, item); } - - /** Generated override to expose protected method: {@link RecipeProvider#has} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static Criterion has(ItemLike itemLike) { return RecipeProvider.has(itemLike); } - - /** Generated override to expose protected method: {@link RecipeProvider#has} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static Criterion has(TagKey tag) { return RecipeProvider.has(tag); } - - /** Generated override to expose protected method: {@link RecipeProvider#inventoryTrigger} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static Criterion inventoryTrigger(ItemPredicate.Builder... items) { return RecipeProvider.inventoryTrigger(items); } - - /** Generated override to expose protected method: {@link RecipeProvider#inventoryTrigger} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static Criterion inventoryTrigger(ItemPredicate... predicates) { return RecipeProvider.inventoryTrigger(predicates); } - - /** Generated override to expose protected method: {@link RecipeProvider#getHasName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static String getHasName(ItemLike itemLike) { return RecipeProvider.getHasName(itemLike); } - - /** Generated override to expose protected method: {@link RecipeProvider#getItemName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static String getItemName(ItemLike itemLike) { return RecipeProvider.getItemName(itemLike); } - - /** Generated override to expose protected method: {@link RecipeProvider#getSimpleRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static String getSimpleRecipeName(ItemLike itemLike) { return RecipeProvider.getSimpleRecipeName(itemLike); } - - /** Generated override to expose protected method: {@link RecipeProvider#getConversionRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static String getConversionRecipeName(ItemLike result, ItemLike ingredient) { return RecipeProvider.getConversionRecipeName(result, ingredient); } - - /** Generated override to expose protected method: {@link RecipeProvider#getSmeltingRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static String getSmeltingRecipeName(ItemLike itemLike) { return RecipeProvider.getSmeltingRecipeName(itemLike); } - - /** Generated override to expose protected method: {@link RecipeProvider#getBlastingRecipeName} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateRecipeProvider", date = "Tue, 28 Apr 2026 01:45:28 GMT") - public static String getBlastingRecipeName(ItemLike itemLike) { return RecipeProvider.getBlastingRecipeName(itemLike); } - - // GENERATED END -} diff --git a/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.kt b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.kt new file mode 100644 index 0000000..8cdbf20 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.kt @@ -0,0 +1,810 @@ +// Preserve Java's public static bridges to inherited protected static methods. +@file:Suppress("ACCIDENTAL_OVERRIDE") + +package com.modularmc.registrate.providers.generators + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.core.RegistrateProvider +import com.modularmc.registrate.util.DataIngredient +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.advancements.Advancement +import net.minecraft.advancements.AdvancementHolder +import net.minecraft.advancements.Criterion +import net.minecraft.advancements.critereon.EnterBlockTrigger +import net.minecraft.advancements.critereon.InventoryChangeTrigger +import net.minecraft.advancements.critereon.ItemPredicate +import net.minecraft.advancements.critereon.MinMaxBounds +import net.minecraft.core.Holder +import net.minecraft.core.HolderLookup +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.core.registries.Registries +import net.minecraft.data.BlockFamily +import net.minecraft.data.CachedOutput +import net.minecraft.data.PackOutput +import net.minecraft.data.recipes.RecipeBuilder +import net.minecraft.data.recipes.RecipeCategory +import net.minecraft.data.recipes.RecipeOutput +import net.minecraft.data.recipes.RecipeProvider +import net.minecraft.data.recipes.ShapedRecipeBuilder +import net.minecraft.data.recipes.ShapelessRecipeBuilder +import net.minecraft.data.recipes.SimpleCookingRecipeBuilder +import net.minecraft.data.recipes.SingleItemRecipeBuilder +import net.minecraft.resources.ResourceKey +import net.minecraft.resources.ResourceLocation +import net.minecraft.tags.TagKey +import net.minecraft.world.flag.FeatureFlagSet +import net.minecraft.world.item.Item +import net.minecraft.world.item.crafting.AbstractCookingRecipe +import net.minecraft.world.item.crafting.BlastingRecipe +import net.minecraft.world.item.crafting.CampfireCookingRecipe +import net.minecraft.world.item.crafting.Ingredient +import net.minecraft.world.item.crafting.Recipe +import net.minecraft.world.item.crafting.RecipeSerializer +import net.minecraft.world.item.crafting.SmeltingRecipe +import net.minecraft.world.item.crafting.SmokingRecipe +import net.minecraft.world.level.ItemLike +import net.minecraft.world.level.block.Block +import net.neoforged.fml.LogicalSide +import net.neoforged.neoforge.common.Tags +import net.neoforged.neoforge.common.conditions.ICondition + +import com.google.common.collect.ImmutableMap + +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.function.Supplier +import javax.annotation.CheckReturnValue +import javax.annotation.processing.Generated + +open class RegistrateRecipeProvider(private val owner: AbstractRegistrate<*>, output: PackOutput, private val lookupProvider: CompletableFuture) : + RecipeProvider(output, lookupProvider), + RegistrateProvider, + RecipeOutput { + private var callback: RecipeOutput? = null + + fun registries() = Objects.requireNonNull( + lookupProvider.getNow(null), + "Recipe registry lookup is not ready", + ) + + fun itemLookup() = registries().lookupOrThrow(Registries.ITEM) + + fun blockLookup() = registries().lookupOrThrow(Registries.BLOCK) + + fun entityLookup() = registries().lookupOrThrow(Registries.ENTITY_TYPE) + + fun resolve(key: ResourceKey): Holder = registries().lookupOrThrow(key.registryKey()).getOrThrow(key) + + override fun getSide(): LogicalSide = LogicalSide.SERVER + + override fun accept(id: ResourceLocation, recipe: Recipe<*>, advancement: AdvancementHolder?, vararg conditions: ICondition) { + recipeOutput().accept(id, recipe, advancement, *conditions) + } + + override fun advancement(): Advancement.Builder = recipeOutput().advancement() + + private fun recipeOutput() = Objects.requireNonNull( + callback, + "Recipe output is only available inside a recipe callback", + )!! + + override fun buildRecipes(output: RecipeOutput) { + callback = output + try { + owner.genData(ProviderType.RECIPE, this) + } finally { + callback = null + } + } + + fun shaped(category: RecipeCategory, result: ItemLike): ShapedRecipeBuilder = ShapedRecipeBuilder.shaped(category, result) + + fun shaped(category: RecipeCategory, result: ItemLike, count: Int): ShapedRecipeBuilder = ShapedRecipeBuilder.shaped(category, result, count) + + fun shapeless(category: RecipeCategory, result: ItemLike): ShapelessRecipeBuilder = ShapelessRecipeBuilder.shapeless(category, result) + + fun shapeless(category: RecipeCategory, result: ItemLike, count: Int): ShapelessRecipeBuilder = ShapelessRecipeBuilder.shapeless(category, result, count) + + fun safeId(id: ResourceLocation): ResourceLocation = ResourceLocation.fromNamespaceAndPath(owner.modid, safeName(id)) + + fun safeId(source: DataIngredient): ResourceLocation = safeId(source.id) + + fun safeId(registryEntry: ItemLike): ResourceLocation = safeId(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())) + + fun safeName(id: ResourceLocation): String = id.path.replace('/', '_') + + fun safeName(source: DataIngredient): String = safeName(source.id) + + fun safeName(registryEntry: ItemLike): String = safeName(BuiltInRegistries.ITEM.getKey(registryEntry.asItem())) + + fun cooking( + source: DataIngredient, + category: RecipeCategory, + result: Supplier, + experience: Float, + cookingTime: Int, + serializer: RecipeSerializer, + factory: AbstractCookingRecipe.Factory, + ) { + cooking( + source, + category, + result, + experience, + cookingTime, + COOKING_TYPE_NAMES[serializer]!!, + serializer, + factory, + ) + } + + fun cooking( + source: DataIngredient, + category: RecipeCategory, + result: Supplier, + experience: Float, + cookingTime: Int, + typeName: String, + serializer: RecipeSerializer, + factory: AbstractCookingRecipe.Factory, + ) { + SimpleCookingRecipeBuilder.generic( + source.toVanilla(), + category, + result.get(), + experience, + cookingTime, + serializer, + factory, + ) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get()).toString() + "_from_" + safeName(source) + "_" + typeName) + } + + fun smelting(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float) { + smelting(source, category, result, experience, DEFAULT_SMELT_TIME) + } + + fun smelting(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float, cookingTime: Int) { + cooking( + source, + category, + result, + experience, + cookingTime, + RecipeSerializer.SMELTING_RECIPE, + ::SmeltingRecipe, + ) + } + + fun blasting(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float) { + blasting(source, category, result, experience, DEFAULT_BLAST_TIME) + } + + fun blasting(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float, cookingTime: Int) { + cooking( + source, + category, + result, + experience, + cookingTime, + RecipeSerializer.BLASTING_RECIPE, + ::BlastingRecipe, + ) + } + + fun smoking(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float) { + smoking(source, category, result, experience, DEFAULT_SMOKE_TIME) + } + + fun smoking(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float, cookingTime: Int) { + cooking( + source, + category, + result, + experience, + cookingTime, + RecipeSerializer.SMOKING_RECIPE, + ::SmokingRecipe, + ) + } + + fun campfire(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float) { + campfire(source, category, result, experience, DEFAULT_CAMPFIRE_TIME) + } + + fun campfire(source: DataIngredient, category: RecipeCategory, result: Supplier, experience: Float, cookingTime: Int) { + cooking( + source, + category, + result, + experience, + cookingTime, + RecipeSerializer.CAMPFIRE_COOKING_RECIPE, + ::CampfireCookingRecipe, + ) + } + + fun stonecutting(source: DataIngredient, category: RecipeCategory, result: Supplier) { + stonecutting(source, category, result, 1) + } + + fun stonecutting(source: DataIngredient, category: RecipeCategory, result: Supplier, resultAmount: Int) { + SingleItemRecipeBuilder.stonecutting(source.toVanilla(), category, result.get(), resultAmount) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get()).toString() + "_from_" + safeName(source) + "_stonecutting") + } + + fun smeltingAndBlasting(source: DataIngredient, category: RecipeCategory, result: Supplier, xp: Float) { + smelting(source, category, result, xp) + blasting(source, category, result, xp) + } + + fun food(source: DataIngredient, category: RecipeCategory, result: Supplier, xp: Float) { + smelting(source, category, result, xp) + smoking(source, category, result, xp) + campfire(source, category, result, xp) + } + + fun square(source: DataIngredient, category: RecipeCategory, output: Supplier, small: Boolean) { + val builder = ShapedRecipeBuilder.shaped(category, output.get()) + .define('X', source.toVanilla()) + if (small) { + builder.pattern("XX").pattern("XX") + } else { + builder.pattern("XXX").pattern("XXX").pattern("XXX") + } + builder.unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(output.get())) + } + + /** + * @param + * @param source + * @param output + */ + @Deprecated( + """Broken, use {@link #storage(NonNullSupplier, RecipeCategory, NonNullSupplier)} or + {@link #storage(DataIngredient, RecipeCategory, NonNullSupplier, DataIngredient, NonNullSupplier)}.""", + ) + fun storage(source: DataIngredient, category: RecipeCategory, output: NonNullSupplier) { + square(source, category, output, false) + // This is backwards, but leaving in for binary compat + singleItemUnfinished(source, category, output, 1, 9) + .save(this, safeId(source).toString() + "_from_" + safeName(output.get())) + } + + fun storage(source: NonNullSupplier, category: RecipeCategory, output: NonNullSupplier) { + storage(DataIngredient.items(source), category, source, DataIngredient.items(output), output) + } + + fun storage(sourceIngredient: DataIngredient, category: RecipeCategory, source: NonNullSupplier, outputIngredient: DataIngredient, output: NonNullSupplier) { + square(sourceIngredient, category, output, false) + singleItemUnfinished(outputIngredient, category, source, 1, 9) + .save(this, safeId(sourceIngredient).toString() + "_from_" + safeName(output.get())) + } + + @CheckReturnValue + fun singleItemUnfinished(source: DataIngredient, category: RecipeCategory, result: Supplier, required: Int, amount: Int): ShapelessRecipeBuilder = + ShapelessRecipeBuilder.shapeless(category, result.get(), amount) + .requires(source.toVanilla(), required) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + + fun singleItem(source: DataIngredient, category: RecipeCategory, result: Supplier, required: Int, amount: Int) { + singleItemUnfinished(source, category, result, required, amount).save(this, safeId(result.get())) + } + + fun planks(source: DataIngredient, category: RecipeCategory, result: Supplier) { + singleItemUnfinished(source, category, result, 1, 4) + .group("planks") + .save(this, safeId(result.get())) + } + + fun stairs(source: DataIngredient, category: RecipeCategory, result: Supplier, group: String?, stone: Boolean) { + ShapedRecipeBuilder.shaped(category, result.get(), 4) + .pattern("X ").pattern("XX ").pattern("XXX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get())) + if (stone) { + stonecutting(source, category, result) + } + } + + fun slab(source: DataIngredient, category: RecipeCategory, result: Supplier, group: String?, stone: Boolean) { + ShapedRecipeBuilder.shaped(category, result.get(), 6) + .pattern("XXX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get())) + if (stone) { + stonecutting(source, category, result, 2) + } + } + + fun fence(source: DataIngredient, category: RecipeCategory, result: Supplier, group: String?) { + ShapedRecipeBuilder.shaped(category, result.get(), 3) + .pattern("W#W").pattern("W#W") + .define('W', source.toVanilla()) + .define('#', Tags.Items.RODS_WOODEN) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get())) + } + + fun fenceGate(source: DataIngredient, category: RecipeCategory, result: Supplier, group: String?) { + ShapedRecipeBuilder.shaped(category, result.get()) + .pattern("#W#").pattern("#W#") + .define('W', source.toVanilla()) + .define('#', Tags.Items.RODS_WOODEN) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get())) + } + + fun wall(source: DataIngredient, category: RecipeCategory, result: Supplier) { + ShapedRecipeBuilder.shaped(category, result.get(), 6) + .pattern("XXX").pattern("XXX") + .define('X', source.toVanilla()) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get())) + stonecutting(source, category, result) + } + + fun door(source: DataIngredient, category: RecipeCategory, result: Supplier, group: String?) { + ShapedRecipeBuilder.shaped(category, result.get(), 3) + .pattern("XX").pattern("XX").pattern("XX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get())) + } + + fun trapDoor(source: DataIngredient, category: RecipeCategory, result: Supplier, group: String?) { + ShapedRecipeBuilder.shaped(category, result.get(), 2) + .pattern("XXX").pattern("XXX") + .define('X', source.toVanilla()) + .group(group) + .unlockedBy("has_" + safeName(source), source.getCriterion(this)) + .save(this, safeId(result.get())) + } + + // @formatter:off + // GENERATED OVERRIDE START + + /** Generated override to expose protected method: [RecipeProvider.buildAdvancement] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + public override fun buildAdvancement(output: CachedOutput, registries: HolderLookup.Provider, advancement: AdvancementHolder): CompletableFuture<*> = + super.buildAdvancement(output, registries, advancement) + + /** Generated override to expose protected method: [RecipeProvider.buildAdvancement] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + public override fun buildAdvancement(output: CachedOutput, registries: HolderLookup.Provider, advancement: AdvancementHolder, vararg conditions: ICondition): CompletableFuture<*> = + super.buildAdvancement(output, registries, advancement, *conditions) + + /** Generated override to expose protected method: [RecipeProvider.buildRecipes] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + public override fun buildRecipes(output: RecipeOutput, holderLookup: HolderLookup.Provider) = super.buildRecipes(output, holderLookup) + + /** Generated override to expose protected method: [RecipeProvider.generateForEnabledBlockFamilies] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + public override fun generateForEnabledBlockFamilies(enabledFeatures: RecipeOutput, flagSet: FeatureFlagSet) = super.generateForEnabledBlockFamilies(enabledFeatures, flagSet) + // GENERATED OVERRIDE END + + companion object { + const val DEFAULT_SMELT_TIME: Int = 200 + const val DEFAULT_BLAST_TIME: Int = DEFAULT_SMELT_TIME / 2 + const val DEFAULT_SMOKE_TIME: Int = DEFAULT_BLAST_TIME + const val DEFAULT_CAMPFIRE_TIME: Int = DEFAULT_SMELT_TIME * 3 + + private val COOKING_TYPE_NAMES: ImmutableMap, String> = ImmutableMap.builder, String>() + .put(RecipeSerializer.SMELTING_RECIPE, "smelting") + .put(RecipeSerializer.BLASTING_RECIPE, "blasting") + .put(RecipeSerializer.SMOKING_RECIPE, "smoking") + .put(RecipeSerializer.CAMPFIRE_COOKING_RECIPE, "campfire") + .build() + + // GENERATED STATIC START + + /** Generated override to expose protected method: [RecipeProvider.netheriteSmithing] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun netheriteSmithing(recipeOutput: RecipeOutput, ingredientItem: Item, category: RecipeCategory, resultItem: Item) { + RecipeProvider.netheriteSmithing(recipeOutput, ingredientItem, category, resultItem) + } + + /** Generated override to expose protected method: [RecipeProvider.trimSmithing] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun trimSmithing(recipeOutput: RecipeOutput, ingredientItem: Item, location: ResourceLocation) { + RecipeProvider.trimSmithing(recipeOutput, ingredientItem, location) + } + + /** Generated override to expose protected method: [RecipeProvider.twoByTwoPacker] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun twoByTwoPacker(recipeOutput: RecipeOutput, category: RecipeCategory, packed: ItemLike, unpacked: ItemLike) { + RecipeProvider.twoByTwoPacker(recipeOutput, category, packed, unpacked) + } + + /** Generated override to expose protected method: [RecipeProvider.threeByThreePacker] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun threeByThreePacker(recipeOutput: RecipeOutput, category: RecipeCategory, packed: ItemLike, unpacked: ItemLike, criterionName: String) { + RecipeProvider.threeByThreePacker(recipeOutput, category, packed, unpacked, criterionName) + } + + /** Generated override to expose protected method: [RecipeProvider.threeByThreePacker] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun threeByThreePacker(recipeOutput: RecipeOutput, category: RecipeCategory, packed: ItemLike, unpacked: ItemLike) { + RecipeProvider.threeByThreePacker(recipeOutput, category, packed, unpacked) + } + + /** Generated override to expose protected method: [RecipeProvider.planksFromLog] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun planksFromLog(recipeOutput: RecipeOutput, planks: ItemLike, logs: TagKey, resultCount: Int) { + RecipeProvider.planksFromLog(recipeOutput, planks, logs, resultCount) + } + + /** Generated override to expose protected method: [RecipeProvider.planksFromLogs] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun planksFromLogs(recipeOutput: RecipeOutput, planks: ItemLike, logs: TagKey, result: Int) { + RecipeProvider.planksFromLogs(recipeOutput, planks, logs, result) + } + + /** Generated override to expose protected method: [RecipeProvider.woodFromLogs] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun woodFromLogs(recipeOutput: RecipeOutput, wood: ItemLike, log: ItemLike) { + RecipeProvider.woodFromLogs(recipeOutput, wood, log) + } + + /** Generated override to expose protected method: [RecipeProvider.woodenBoat] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun woodenBoat(recipeOutput: RecipeOutput, boat: ItemLike, material: ItemLike) { + RecipeProvider.woodenBoat(recipeOutput, boat, material) + } + + /** Generated override to expose protected method: [RecipeProvider.chestBoat] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun chestBoat(recipeOutput: RecipeOutput, boat: ItemLike, material: ItemLike) { + RecipeProvider.chestBoat(recipeOutput, boat, material) + } + + /** Generated override to expose protected method: [RecipeProvider.buttonBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun buttonBuilder(button: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.buttonBuilder(button, material) + + /** Generated override to expose protected method: [RecipeProvider.doorBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun doorBuilder(door: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.doorBuilder(door, material) + + /** Generated override to expose protected method: [RecipeProvider.fenceBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun fenceBuilder(fence: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.fenceBuilder(fence, material) + + /** Generated override to expose protected method: [RecipeProvider.fenceGateBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun fenceGateBuilder(fenceGate: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.fenceGateBuilder(fenceGate, material) + + /** Generated override to expose protected method: [RecipeProvider.pressurePlate] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun pressurePlate(recipeOutput: RecipeOutput, pressurePlate: ItemLike, material: ItemLike) { + RecipeProvider.pressurePlate(recipeOutput, pressurePlate, material) + } + + /** Generated override to expose protected method: [RecipeProvider.pressurePlateBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun pressurePlateBuilder(category: RecipeCategory, pressurePlate: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.pressurePlateBuilder(category, pressurePlate, material) + + /** Generated override to expose protected method: [RecipeProvider.slab] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun slab(recipeOutput: RecipeOutput, category: RecipeCategory, slab: ItemLike, material: ItemLike) { + RecipeProvider.slab(recipeOutput, category, slab, material) + } + + /** Generated override to expose protected method: [RecipeProvider.slabBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun slabBuilder(category: RecipeCategory, slab: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.slabBuilder(category, slab, material) + + /** Generated override to expose protected method: [RecipeProvider.stairBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun stairBuilder(stairs: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.stairBuilder(stairs, material) + + /** Generated override to expose protected method: [RecipeProvider.trapdoorBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun trapdoorBuilder(trapdoor: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.trapdoorBuilder(trapdoor, material) + + /** Generated override to expose protected method: [RecipeProvider.signBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun signBuilder(sign: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.signBuilder(sign, material) + + /** Generated override to expose protected method: [RecipeProvider.hangingSign] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun hangingSign(recipeOutput: RecipeOutput, sign: ItemLike, material: ItemLike) { + RecipeProvider.hangingSign(recipeOutput, sign, material) + } + + /** Generated override to expose protected method: [RecipeProvider.colorBlockWithDye] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun colorBlockWithDye(recipeOutput: RecipeOutput, dyes: MutableList, dyeableItems: MutableList, group: String) { + RecipeProvider.colorBlockWithDye(recipeOutput, dyes, dyeableItems, group) + } + + /** Generated override to expose protected method: [RecipeProvider.carpet] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun carpet(recipeOutput: RecipeOutput, carpet: ItemLike, material: ItemLike) { + RecipeProvider.carpet(recipeOutput, carpet, material) + } + + /** Generated override to expose protected method: [RecipeProvider.bedFromPlanksAndWool] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun bedFromPlanksAndWool(recipeOutput: RecipeOutput, bed: ItemLike, wool: ItemLike) { + RecipeProvider.bedFromPlanksAndWool(recipeOutput, bed, wool) + } + + /** Generated override to expose protected method: [RecipeProvider.banner] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun banner(recipeOutput: RecipeOutput, banner: ItemLike, material: ItemLike) { + RecipeProvider.banner(recipeOutput, banner, material) + } + + /** Generated override to expose protected method: [RecipeProvider.stainedGlassFromGlassAndDye] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun stainedGlassFromGlassAndDye(recipeOutput: RecipeOutput, stainedGlass: ItemLike, dye: ItemLike) { + RecipeProvider.stainedGlassFromGlassAndDye(recipeOutput, stainedGlass, dye) + } + + /** Generated override to expose protected method: [RecipeProvider.stainedGlassPaneFromStainedGlass] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun stainedGlassPaneFromStainedGlass(recipeOutput: RecipeOutput, stainedGlassPane: ItemLike, stainedGlass: ItemLike) { + RecipeProvider.stainedGlassPaneFromStainedGlass(recipeOutput, stainedGlassPane, stainedGlass) + } + + /** Generated override to expose protected method: [RecipeProvider.stainedGlassPaneFromGlassPaneAndDye] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun stainedGlassPaneFromGlassPaneAndDye(recipeOutput: RecipeOutput, stainedGlassPane: ItemLike, dye: ItemLike) { + RecipeProvider.stainedGlassPaneFromGlassPaneAndDye(recipeOutput, stainedGlassPane, dye) + } + + /** Generated override to expose protected method: [RecipeProvider.coloredTerracottaFromTerracottaAndDye] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun coloredTerracottaFromTerracottaAndDye(recipeOutput: RecipeOutput, terracotta: ItemLike, dye: ItemLike) { + RecipeProvider.coloredTerracottaFromTerracottaAndDye(recipeOutput, terracotta, dye) + } + + /** Generated override to expose protected method: [RecipeProvider.concretePowder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun concretePowder(recipeOutput: RecipeOutput, concretePowder: ItemLike, dye: ItemLike) { + RecipeProvider.concretePowder(recipeOutput, concretePowder, dye) + } + + /** Generated override to expose protected method: [RecipeProvider.candle] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun candle(recipeOutput: RecipeOutput, candle: ItemLike, dye: ItemLike) { + RecipeProvider.candle(recipeOutput, candle, dye) + } + + /** Generated override to expose protected method: [RecipeProvider.wall] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun wall(recipeOutput: RecipeOutput, category: RecipeCategory, wall: ItemLike, material: ItemLike) { + RecipeProvider.wall(recipeOutput, category, wall, material) + } + + /** Generated override to expose protected method: [RecipeProvider.wallBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun wallBuilder(category: RecipeCategory, wall: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.wallBuilder(category, wall, material) + + /** Generated override to expose protected method: [RecipeProvider.polished] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun polished(recipeOutput: RecipeOutput, category: RecipeCategory, result: ItemLike, material: ItemLike) { + RecipeProvider.polished(recipeOutput, category, result, material) + } + + /** Generated override to expose protected method: [RecipeProvider.polishedBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun polishedBuilder(category: RecipeCategory, result: ItemLike, material: Ingredient): RecipeBuilder = RecipeProvider.polishedBuilder(category, result, material) + + /** Generated override to expose protected method: [RecipeProvider.cut] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun cut(recipeOutput: RecipeOutput, category: RecipeCategory, cutResult: ItemLike, material: ItemLike) { + RecipeProvider.cut(recipeOutput, category, cutResult, material) + } + + /** Generated override to expose protected method: [RecipeProvider.cutBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun cutBuilder(category: RecipeCategory, cutResult: ItemLike, material: Ingredient): ShapedRecipeBuilder = RecipeProvider.cutBuilder(category, cutResult, material) + + /** Generated override to expose protected method: [RecipeProvider.chiseled] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun chiseled(recipeOutput: RecipeOutput, category: RecipeCategory, chiseledResult: ItemLike, material: ItemLike) { + RecipeProvider.chiseled(recipeOutput, category, chiseledResult, material) + } + + /** Generated override to expose protected method: [RecipeProvider.mosaicBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun mosaicBuilder(recipeOutput: RecipeOutput, category: RecipeCategory, result: ItemLike, material: ItemLike) { + RecipeProvider.mosaicBuilder(recipeOutput, category, result, material) + } + + /** Generated override to expose protected method: [RecipeProvider.chiseledBuilder] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun chiseledBuilder(category: RecipeCategory, chiseledResult: ItemLike, material: Ingredient): ShapedRecipeBuilder = RecipeProvider.chiseledBuilder(category, chiseledResult, material) + + /** Generated override to expose protected method: [RecipeProvider.stonecutterResultFromBase] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun stonecutterResultFromBase(recipeOutput: RecipeOutput, category: RecipeCategory, result: ItemLike, material: ItemLike) { + RecipeProvider.stonecutterResultFromBase(recipeOutput, category, result, material) + } + + /** Generated override to expose protected method: [RecipeProvider.stonecutterResultFromBase] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun stonecutterResultFromBase(recipeOutput: RecipeOutput, category: RecipeCategory, result: ItemLike, material: ItemLike, resultCount: Int) { + RecipeProvider.stonecutterResultFromBase(recipeOutput, category, result, material, resultCount) + } + + /** Generated override to expose protected method: [RecipeProvider.smeltingResultFromBase] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun smeltingResultFromBase(recipeOutput: RecipeOutput, result: ItemLike, ingredient: ItemLike) { + RecipeProvider.smeltingResultFromBase(recipeOutput, result, ingredient) + } + + /** Generated override to expose protected method: [RecipeProvider.copySmithingTemplate] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun copySmithingTemplate(recipeOutput: RecipeOutput, template: ItemLike, baseMaterial: TagKey) { + RecipeProvider.copySmithingTemplate(recipeOutput, template, baseMaterial) + } + + /** Generated override to expose protected method: [RecipeProvider.copySmithingTemplate] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun copySmithingTemplate(recipeOutput: RecipeOutput, template: ItemLike, baseItem: ItemLike) { + RecipeProvider.copySmithingTemplate(recipeOutput, template, baseItem) + } + + /** Generated override to expose protected method: [RecipeProvider.copySmithingTemplate] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun copySmithingTemplate(recipeOutput: RecipeOutput, template: ItemLike, baseItem: Ingredient) { + RecipeProvider.copySmithingTemplate(recipeOutput, template, baseItem) + } + + /** Generated override to expose protected method: [RecipeProvider.waxRecipes] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun waxRecipes(recipeOutput: RecipeOutput, requiredFeatures: FeatureFlagSet) { + RecipeProvider.waxRecipes(recipeOutput, requiredFeatures) + } + + /** Generated override to expose protected method: [RecipeProvider.grate] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun grate(recipeOutput: RecipeOutput, grateBlock: Block, material: Block) { + RecipeProvider.grate(recipeOutput, grateBlock, material) + } + + /** Generated override to expose protected method: [RecipeProvider.copperBulb] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun copperBulb(recipeOutput: RecipeOutput, bulbBlock: Block, material: Block) { + RecipeProvider.copperBulb(recipeOutput, bulbBlock, material) + } + + /** Generated override to expose protected method: [RecipeProvider.generateRecipes] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun generateRecipes(recipeOutput: RecipeOutput, blockFamily: BlockFamily, requiredFeatures: FeatureFlagSet) { + RecipeProvider.generateRecipes(recipeOutput, blockFamily, requiredFeatures) + } + + /** Generated override to expose protected method: [RecipeProvider.getBaseBlock] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun getBaseBlock(family: BlockFamily, variant: BlockFamily.Variant): Block = RecipeProvider.getBaseBlock(family, variant) + + /** Generated override to expose protected method: [RecipeProvider.insideOf] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun insideOf(block: Block): Criterion = RecipeProvider.insideOf(block) + + /** Generated override to expose protected method: [RecipeProvider.has] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun has(count: MinMaxBounds.Ints, item: ItemLike): Criterion = RecipeProvider.has(count, item) + + /** Generated override to expose protected method: [RecipeProvider.has] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun has(itemLike: ItemLike): Criterion = RecipeProvider.has(itemLike) + + /** Generated override to expose protected method: [RecipeProvider.has] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun has(tag: TagKey): Criterion = RecipeProvider.has(tag) + + /** Generated override to expose protected method: [RecipeProvider.inventoryTrigger] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun inventoryTrigger(vararg items: ItemPredicate.Builder): Criterion = RecipeProvider.inventoryTrigger(*items) + + /** Generated override to expose protected method: [RecipeProvider.inventoryTrigger] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun inventoryTrigger(vararg predicates: ItemPredicate): Criterion = RecipeProvider.inventoryTrigger(*predicates) + + /** Generated override to expose protected method: [RecipeProvider.getHasName] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun getHasName(itemLike: ItemLike): String = RecipeProvider.getHasName(itemLike) + + /** Generated override to expose protected method: [RecipeProvider.getItemName] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun getItemName(itemLike: ItemLike): String = RecipeProvider.getItemName(itemLike) + + /** Generated override to expose protected method: [RecipeProvider.getSimpleRecipeName] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun getSimpleRecipeName(itemLike: ItemLike): String = RecipeProvider.getSimpleRecipeName(itemLike) + + /** Generated override to expose protected method: [RecipeProvider.getConversionRecipeName] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun getConversionRecipeName(result: ItemLike, ingredient: ItemLike): String = RecipeProvider.getConversionRecipeName(result, ingredient) + + /** Generated override to expose protected method: [RecipeProvider.getSmeltingRecipeName] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun getSmeltingRecipeName(itemLike: ItemLike): String = RecipeProvider.getSmeltingRecipeName(itemLike) + + /** Generated override to expose protected method: [RecipeProvider.getBlastingRecipeName] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateRecipeProvider"], date = "Tue, 28 Apr 2026 01:45:28 GMT") + @JvmStatic + fun getBlastingRecipeName(itemLike: ItemLike): String = RecipeProvider.getBlastingRecipeName(itemLike) + // GENERATED STATIC END + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java deleted file mode 100644 index 8880c2f..0000000 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.java +++ /dev/null @@ -1,283 +0,0 @@ -package com.modularmc.registrate.providers.loot; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.core.HolderLookup; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.loot.BlockLootSubProvider; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.flag.FeatureFlags; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; -import net.minecraft.world.level.storage.loot.functions.FunctionUserBuilder; -import net.minecraft.world.level.storage.loot.predicates.ConditionUserBuilder; -import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; - -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -import javax.annotation.processing.Generated; - -public class RegistrateBlockLootTables extends BlockLootSubProvider implements RegistrateLootTables { - - private final AbstractRegistrate parent; - private final Consumer callback; - - private final HolderLookup itemLookup; - private final HolderLookup blockLookup; - private final HolderLookup> entityLookup; - - public RegistrateBlockLootTables(HolderLookup.Provider provider, AbstractRegistrate parent, Consumer callback) { - super(Set.of(), FeatureFlags.REGISTRY.allFlags(), provider); - this.parent = parent; - this.callback = callback; - itemLookup = registries.lookupOrThrow(Registries.ITEM); - blockLookup = registries.lookupOrThrow(Registries.BLOCK); - entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE); - } - - @Override - protected void generate() { - callback.accept(this); - } - - @Override - protected Iterable getKnownBlocks() { - return parent.getAll(Registries.BLOCK).stream().map(Supplier::get).collect(Collectors.toList()); - } - - public HolderLookup.Provider getRegistries() { - return this.registries; - } - - public HolderLookup itemLookup() { - return itemLookup; - } - - public HolderLookup blockLookup() { - return blockLookup; - } - - public HolderLookup> entityLookup() { - return entityLookup; - } - - // @formatter:off - // GENERATED START - DO NOT EDIT BELOW THIS LINE - - /** Generated override to expose protected method: {@link BlockLootSubProvider#applyExplosionDecay} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public > T applyExplosionDecay(ItemLike item, FunctionUserBuilder functionBuilder) { return super.applyExplosionDecay(item, functionBuilder); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#applyExplosionCondition} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public > T applyExplosionCondition(ItemLike item, ConditionUserBuilder conditionBuilder) { return super.applyExplosionCondition(item, conditionBuilder); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchDispatchTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createSilkTouchDispatchTable(Block block, LootPoolEntryContainer.Builder builder) { return super.createSilkTouchDispatchTable(block, builder); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsDispatchTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createShearsDispatchTable(Block block, LootPoolEntryContainer.Builder builder) { return super.createShearsDispatchTable(block, builder); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchOrShearsDispatchTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createSilkTouchOrShearsDispatchTable(Block block, LootPoolEntryContainer.Builder builder) { return super.createSilkTouchOrShearsDispatchTable(block, builder); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTableWithSilkTouch} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createSingleItemTableWithSilkTouch(Block block, ItemLike item) { return super.createSingleItemTableWithSilkTouch(block, item); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createSingleItemTable(ItemLike item, NumberProvider count) { return super.createSingleItemTable(item, count); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSingleItemTableWithSilkTouch} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createSingleItemTableWithSilkTouch(Block block, ItemLike item, NumberProvider count) { return super.createSingleItemTableWithSilkTouch(block, item, count); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSilkTouchOnlyTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createSilkTouchOnlyTable(ItemLike item) { return super.createSilkTouchOnlyTable(item); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createPotFlowerItemTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createPotFlowerItemTable(ItemLike item) { return super.createPotFlowerItemTable(item); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createSlabItemTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createSlabItemTable(Block block) { return super.createSlabItemTable(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createNameableBlockEntityTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createNameableBlockEntityTable(Block block) { return super.createNameableBlockEntityTable(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createShulkerBoxDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createShulkerBoxDrop(Block block) { return super.createShulkerBoxDrop(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createCopperOreDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createCopperOreDrops(Block block) { return super.createCopperOreDrops(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createLapisOreDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createLapisOreDrops(Block block) { return super.createLapisOreDrops(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createRedstoneOreDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createRedstoneOreDrops(Block block) { return super.createRedstoneOreDrops(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createBannerDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createBannerDrop(Block block) { return super.createBannerDrop(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createBeeNestDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createBeeNestDrop(Block block) { return super.createBeeNestDrop(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createBeeHiveDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createBeeHiveDrop(Block block) { return super.createBeeHiveDrop(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createCaveVinesDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createCaveVinesDrop(Block block) { return super.createCaveVinesDrop(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createOreDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createOreDrop(Block block, Item item) { return super.createOreDrop(block, item); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createMushroomBlockDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createMushroomBlockDrop(Block block, ItemLike item) { return super.createMushroomBlockDrop(block, item); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createGrassDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createGrassDrops(Block block) { return super.createGrassDrops(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createShearsOnlyDrop} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public static LootTable.Builder createShearsOnlyDrop(ItemLike item) { return BlockLootSubProvider.createShearsOnlyDrop(item); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createMultifaceBlockDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createMultifaceBlockDrops(Block block, LootItemCondition.Builder builder) { return super.createMultifaceBlockDrops(block, builder); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createLeavesDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createLeavesDrops(Block leavesBlock, Block saplingBlock, float... chances) { return super.createLeavesDrops(leavesBlock, saplingBlock, chances); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createOakLeavesDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createOakLeavesDrops(Block oakLeavesBlock, Block saplingBlock, float... chances) { return super.createOakLeavesDrops(oakLeavesBlock, saplingBlock, chances); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createMangroveLeavesDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createMangroveLeavesDrops(Block block) { return super.createMangroveLeavesDrops(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createCropDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createCropDrops(Block cropBlock, Item grownCropItem, Item seedsItem, LootItemCondition.Builder dropGrownCropCondition) { return super.createCropDrops(cropBlock, grownCropItem, seedsItem, dropGrownCropCondition); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoublePlantShearsDrop} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createDoublePlantShearsDrop(Block sheared) { return super.createDoublePlantShearsDrop(sheared); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoublePlantWithSeedDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createDoublePlantWithSeedDrops(Block block, Block sheared) { return super.createDoublePlantWithSeedDrops(block, sheared); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createCandleDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createCandleDrops(Block candleBlock) { return super.createCandleDrops(candleBlock); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createPetalsDrops} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createPetalsDrops(Block petalBlock) { return super.createPetalsDrops(petalBlock); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createCandleCakeDrops} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public static LootTable.Builder createCandleCakeDrops(Block candleCakeBlock) { return BlockLootSubProvider.createCandleCakeDrops(candleCakeBlock); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#addNetherVinesDropTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public void addNetherVinesDropTable(Block vines, Block plant) { super.addNetherVinesDropTable(vines, plant); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#createDoorTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public LootTable.Builder createDoorTable(Block doorBlock) { return super.createDoorTable(doorBlock); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#dropPottedContents} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public void dropPottedContents(Block flowerPot) { super.dropPottedContents(flowerPot); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#otherWhenSilkTouch} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public void otherWhenSilkTouch(Block block, Block other) { super.otherWhenSilkTouch(block, other); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#dropOther} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public void dropOther(Block block, ItemLike item) { super.dropOther(block, item); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#dropWhenSilkTouch} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public void dropWhenSilkTouch(Block block) { super.dropWhenSilkTouch(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#dropSelf} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public void dropSelf(Block block) { super.dropSelf(block); } - - /** Generated override to expose protected method: {@link BlockLootSubProvider#add} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateBlockLootTables", date = "Tue, 28 Apr 2026 01:43:43 GMT") - public void add(Block block, LootTable.Builder builder) { super.add(block, builder); } - - // GENERATED END -} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.kt b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.kt new file mode 100644 index 0000000..2c51226 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.kt @@ -0,0 +1,225 @@ +// Preserve Java's public static bridges to inherited protected static methods. +@file:Suppress("ACCIDENTAL_OVERRIDE") + +package com.modularmc.registrate.providers.loot + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.core.HolderLookup +import net.minecraft.core.registries.Registries +import net.minecraft.data.loot.BlockLootSubProvider +import net.minecraft.world.entity.EntityType +import net.minecraft.world.flag.FeatureFlags +import net.minecraft.world.item.Item +import net.minecraft.world.level.ItemLike +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.storage.loot.LootTable +import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer +import net.minecraft.world.level.storage.loot.functions.FunctionUserBuilder +import net.minecraft.world.level.storage.loot.predicates.ConditionUserBuilder +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition +import net.minecraft.world.level.storage.loot.providers.number.NumberProvider + +import java.util.function.Consumer +import javax.annotation.processing.Generated + +open class RegistrateBlockLootTables(provider: HolderLookup.Provider, private val parent: AbstractRegistrate<*>, private val callback: Consumer) : + BlockLootSubProvider(mutableSetOf(), FeatureFlags.REGISTRY.allFlags(), provider), + RegistrateLootTables { + private val itemLookup = registries.lookupOrThrow(Registries.ITEM) + private val blockLookup = registries.lookupOrThrow(Registries.BLOCK) + private val entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE) + + override fun generate() { + callback.accept(this) + } + + override fun getKnownBlocks(): Iterable = parent.getAll(Registries.BLOCK).map { it.get() } + + fun getRegistries(): HolderLookup.Provider = registries + + fun itemLookup(): HolderLookup = itemLookup + + fun blockLookup(): HolderLookup = blockLookup + + fun entityLookup(): HolderLookup> = entityLookup + + // @formatter:off + // GENERATED OVERRIDE START + + /** Generated override to expose protected method: [BlockLootSubProvider.applyExplosionDecay] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun > applyExplosionDecay(item: ItemLike, functionBuilder: FunctionUserBuilder): T = super.applyExplosionDecay(item, functionBuilder) + + /** Generated override to expose protected method: [BlockLootSubProvider.applyExplosionCondition] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun > applyExplosionCondition(item: ItemLike, conditionBuilder: ConditionUserBuilder): T = super.applyExplosionCondition(item, conditionBuilder) + + /** Generated override to expose protected method: [BlockLootSubProvider.createSilkTouchDispatchTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createSilkTouchDispatchTable(block: Block, builder: LootPoolEntryContainer.Builder<*>): LootTable.Builder = super.createSilkTouchDispatchTable(block, builder) + + /** Generated override to expose protected method: [BlockLootSubProvider.createShearsDispatchTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createShearsDispatchTable(block: Block, builder: LootPoolEntryContainer.Builder<*>): LootTable.Builder = super.createShearsDispatchTable(block, builder) + + /** Generated override to expose protected method: [BlockLootSubProvider.createSilkTouchOrShearsDispatchTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createSilkTouchOrShearsDispatchTable(block: Block, builder: LootPoolEntryContainer.Builder<*>): LootTable.Builder = super.createSilkTouchOrShearsDispatchTable(block, builder) + + /** Generated override to expose protected method: [BlockLootSubProvider.createSingleItemTableWithSilkTouch] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createSingleItemTableWithSilkTouch(block: Block, item: ItemLike): LootTable.Builder = super.createSingleItemTableWithSilkTouch(block, item) + + /** Generated override to expose protected method: [BlockLootSubProvider.createSingleItemTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createSingleItemTable(item: ItemLike, count: NumberProvider): LootTable.Builder = super.createSingleItemTable(item, count) + + /** Generated override to expose protected method: [BlockLootSubProvider.createSingleItemTableWithSilkTouch] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createSingleItemTableWithSilkTouch(block: Block, item: ItemLike, count: NumberProvider): LootTable.Builder = super.createSingleItemTableWithSilkTouch(block, item, count) + + /** Generated override to expose protected method: [BlockLootSubProvider.createSilkTouchOnlyTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createSilkTouchOnlyTable(item: ItemLike): LootTable.Builder = super.createSilkTouchOnlyTable(item) + + /** Generated override to expose protected method: [BlockLootSubProvider.createPotFlowerItemTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createPotFlowerItemTable(item: ItemLike): LootTable.Builder = super.createPotFlowerItemTable(item) + + /** Generated override to expose protected method: [BlockLootSubProvider.createSlabItemTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createSlabItemTable(block: Block): LootTable.Builder = super.createSlabItemTable(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createNameableBlockEntityTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createNameableBlockEntityTable(block: Block): LootTable.Builder = super.createNameableBlockEntityTable(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createShulkerBoxDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createShulkerBoxDrop(block: Block): LootTable.Builder = super.createShulkerBoxDrop(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createCopperOreDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createCopperOreDrops(block: Block): LootTable.Builder = super.createCopperOreDrops(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createLapisOreDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createLapisOreDrops(block: Block): LootTable.Builder = super.createLapisOreDrops(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createRedstoneOreDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createRedstoneOreDrops(block: Block): LootTable.Builder = super.createRedstoneOreDrops(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createBannerDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createBannerDrop(block: Block): LootTable.Builder = super.createBannerDrop(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createBeeNestDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createBeeNestDrop(block: Block): LootTable.Builder = super.createBeeNestDrop(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createBeeHiveDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createBeeHiveDrop(block: Block): LootTable.Builder = super.createBeeHiveDrop(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createCaveVinesDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createCaveVinesDrop(block: Block): LootTable.Builder = super.createCaveVinesDrop(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createOreDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createOreDrop(block: Block, item: Item): LootTable.Builder = super.createOreDrop(block, item) + + /** Generated override to expose protected method: [BlockLootSubProvider.createMushroomBlockDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createMushroomBlockDrop(block: Block, item: ItemLike): LootTable.Builder = super.createMushroomBlockDrop(block, item) + + /** Generated override to expose protected method: [BlockLootSubProvider.createGrassDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createGrassDrops(block: Block): LootTable.Builder = super.createGrassDrops(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createMultifaceBlockDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createMultifaceBlockDrops(block: Block, builder: LootItemCondition.Builder): LootTable.Builder = super.createMultifaceBlockDrops(block, builder) + + /** Generated override to expose protected method: [BlockLootSubProvider.createLeavesDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createLeavesDrops(leavesBlock: Block, saplingBlock: Block, vararg chances: Float): LootTable.Builder = super.createLeavesDrops(leavesBlock, saplingBlock, *chances) + + /** Generated override to expose protected method: [BlockLootSubProvider.createOakLeavesDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createOakLeavesDrops(oakLeavesBlock: Block, saplingBlock: Block, vararg chances: Float): LootTable.Builder = super.createOakLeavesDrops(oakLeavesBlock, saplingBlock, *chances) + + /** Generated override to expose protected method: [BlockLootSubProvider.createMangroveLeavesDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createMangroveLeavesDrops(block: Block): LootTable.Builder = super.createMangroveLeavesDrops(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.createCropDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createCropDrops(cropBlock: Block, grownCropItem: Item, seedsItem: Item, dropGrownCropCondition: LootItemCondition.Builder): LootTable.Builder = + super.createCropDrops(cropBlock, grownCropItem, seedsItem, dropGrownCropCondition) + + /** Generated override to expose protected method: [BlockLootSubProvider.createDoublePlantShearsDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createDoublePlantShearsDrop(sheared: Block): LootTable.Builder = super.createDoublePlantShearsDrop(sheared) + + /** Generated override to expose protected method: [BlockLootSubProvider.createDoublePlantWithSeedDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createDoublePlantWithSeedDrops(block: Block, sheared: Block): LootTable.Builder = super.createDoublePlantWithSeedDrops(block, sheared) + + /** Generated override to expose protected method: [BlockLootSubProvider.createCandleDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createCandleDrops(candleBlock: Block): LootTable.Builder = super.createCandleDrops(candleBlock) + + /** Generated override to expose protected method: [BlockLootSubProvider.createPetalsDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createPetalsDrops(petalBlock: Block): LootTable.Builder = super.createPetalsDrops(petalBlock) + + /** Generated override to expose protected method: [BlockLootSubProvider.addNetherVinesDropTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun addNetherVinesDropTable(vines: Block, plant: Block) = super.addNetherVinesDropTable(vines, plant) + + /** Generated override to expose protected method: [BlockLootSubProvider.createDoorTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun createDoorTable(doorBlock: Block): LootTable.Builder = super.createDoorTable(doorBlock) + + /** Generated override to expose protected method: [BlockLootSubProvider.dropPottedContents] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun dropPottedContents(flowerPot: Block) = super.dropPottedContents(flowerPot) + + /** Generated override to expose protected method: [BlockLootSubProvider.otherWhenSilkTouch] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun otherWhenSilkTouch(block: Block, other: Block) = super.otherWhenSilkTouch(block, other) + + /** Generated override to expose protected method: [BlockLootSubProvider.dropOther] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun dropOther(block: Block, item: ItemLike) = super.dropOther(block, item) + + /** Generated override to expose protected method: [BlockLootSubProvider.dropWhenSilkTouch] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun dropWhenSilkTouch(block: Block) = super.dropWhenSilkTouch(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.dropSelf] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun dropSelf(block: Block) = super.dropSelf(block) + + /** Generated override to expose protected method: [BlockLootSubProvider.add] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + public override fun add(block: Block, builder: LootTable.Builder) = super.add(block, builder) + // GENERATED OVERRIDE END + + companion object { + // GENERATED STATIC START + /** Generated override to expose protected method: [BlockLootSubProvider.createShearsOnlyDrop] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + @JvmStatic + fun createShearsOnlyDrop(item: ItemLike): LootTable.Builder = BlockLootSubProvider.createShearsOnlyDrop(item) + + /** Generated override to expose protected method: [BlockLootSubProvider.createCandleCakeDrops] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateBlockLootTables"], date = "Tue, 28 Apr 2026 01:43:43 GMT") + @JvmStatic + fun createCandleCakeDrops(candleCakeBlock: Block): LootTable.Builder = BlockLootSubProvider.createCandleCakeDrops(candleCakeBlock) + // GENERATED STATIC END + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java deleted file mode 100644 index 592dfdb..0000000 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.modularmc.registrate.providers.loot; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.core.HolderLookup; -import net.minecraft.core.registries.Registries; -import net.minecraft.data.loot.EntityLootSubProvider; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.animal.FrogVariant; -import net.minecraft.world.flag.FeatureFlags; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; - -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import javax.annotation.processing.Generated; - -public class RegistrateEntityLootTables extends EntityLootSubProvider implements RegistrateLootTables { - - private final AbstractRegistrate parent; - private final Consumer callback; - - private final HolderLookup itemLookup; - private final HolderLookup blockLookup; - private final HolderLookup> entityLookup; - - public RegistrateEntityLootTables(HolderLookup.Provider p_346214_, AbstractRegistrate parent, Consumer callback) { - super(FeatureFlags.REGISTRY.allFlags(), p_346214_); - this.parent = parent; - this.callback = callback; - itemLookup = registries.lookupOrThrow(Registries.ITEM); - blockLookup = registries.lookupOrThrow(Registries.BLOCK); - entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE); - } - - @Override - public void generate() { - callback.accept(this); - } - - @Override - protected Stream> getKnownEntityTypes() { - return parent.getAll(Registries.ENTITY_TYPE).stream().map(Supplier::get); - } - - public HolderLookup.Provider getRegistries() { - return this.registries; - } - - public HolderLookup itemLookup() { - return itemLookup; - } - - public HolderLookup blockLookup() { - return blockLookup; - } - - public HolderLookup> entityLookup() { - return entityLookup; - } - - // @formatter:off - // GENERATED START - DO NOT EDIT BELOW THIS LINE - - /** Generated override to expose protected method: {@link EntityLootSubProvider#createSheepTable} */ - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") - public static LootTable.Builder createSheepTable(ItemLike woolItem) { return EntityLootSubProvider.createSheepTable(woolItem); } - - /** Generated override to expose protected method: {@link EntityLootSubProvider#canHaveLootTable} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") - public boolean canHaveLootTable(EntityType p_249029_) { return super.canHaveLootTable(p_249029_); } - - /** Generated override to expose protected method: {@link EntityLootSubProvider#killedByFrogVariant} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") - public LootItemCondition.Builder killedByFrogVariant(ResourceKey frogVariant) { return super.killedByFrogVariant(frogVariant); } - - /** Generated override to expose protected method: {@link EntityLootSubProvider#add} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") - public void add(EntityType entityType, LootTable.Builder builder) { super.add(entityType, builder); } - - /** Generated override to expose protected method: {@link EntityLootSubProvider#add} */ - @Override - @Generated(value = "com.modularmc.registrate.test.meta.UpdateEntityLootTables", date = "Tue, 28 Apr 2026 01:45:14 GMT") - public void add(EntityType entityType, ResourceKey defaultLootTable, LootTable.Builder builder) { super.add(entityType, defaultLootTable, builder); } - - // GENERATED END -} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.kt b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.kt new file mode 100644 index 0000000..4e9ed12 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.kt @@ -0,0 +1,91 @@ +// Preserve Java's public static bridges to inherited protected static methods. +@file:Suppress("ACCIDENTAL_OVERRIDE") + +package com.modularmc.registrate.providers.loot + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.core.HolderLookup +import net.minecraft.core.registries.Registries +import net.minecraft.data.loot.EntityLootSubProvider +import net.minecraft.resources.ResourceKey +import net.minecraft.world.entity.EntityType +import net.minecraft.world.entity.animal.FrogVariant +import net.minecraft.world.flag.FeatureFlags +import net.minecraft.world.item.Item +import net.minecraft.world.level.ItemLike +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.storage.loot.LootTable +import net.minecraft.world.level.storage.loot.predicates.LootItemCondition + +import java.util.function.Consumer +import java.util.stream.Stream +import javax.annotation.processing.Generated + +open class RegistrateEntityLootTables(provider: HolderLookup.Provider, private val parent: AbstractRegistrate<*>, private val callback: Consumer) : + EntityLootSubProvider(FeatureFlags.REGISTRY.allFlags(), provider), + RegistrateLootTables { + private val itemLookup = registries.lookupOrThrow(Registries.ITEM) + private val blockLookup = registries.lookupOrThrow(Registries.BLOCK) + private val entityLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE) + + override fun generate() { + callback.accept(this) + } + + override fun getKnownEntityTypes(): Stream> = parent.getAll, EntityType<*>>(Registries.ENTITY_TYPE).stream() + .map { it.get() } + + fun getRegistries(): HolderLookup.Provider = registries + + fun itemLookup(): HolderLookup = itemLookup + + fun blockLookup(): HolderLookup = blockLookup + + fun entityLookup(): HolderLookup> = entityLookup + + // GENERATED OVERRIDE START + + /** Generated override to expose protected method: [EntityLootSubProvider.canHaveLootTable] */ + @Generated( + value = ["com.modularmc.registrate.test.meta.UpdateEntityLootTables"], + date = "Tue, 28 Apr 2026 01:45:14 GMT", + ) + public override fun canHaveLootTable(entityType: EntityType<*>): Boolean = super.canHaveLootTable(entityType) + + /** Generated override to expose protected method: [EntityLootSubProvider.killedByFrogVariant] */ + @Generated( + value = ["com.modularmc.registrate.test.meta.UpdateEntityLootTables"], + date = "Tue, 28 Apr 2026 01:45:14 GMT", + ) + public override fun killedByFrogVariant(frogVariant: ResourceKey): LootItemCondition.Builder = super.killedByFrogVariant(frogVariant) + + /** Generated override to expose protected method: [EntityLootSubProvider.add] */ + @Generated( + value = ["com.modularmc.registrate.test.meta.UpdateEntityLootTables"], + date = "Tue, 28 Apr 2026 01:45:14 GMT", + ) + public override fun add(entityType: EntityType<*>, builder: LootTable.Builder) { + super.add(entityType, builder) + } + + /** Generated override to expose protected method: [EntityLootSubProvider.add] */ + @Generated( + value = ["com.modularmc.registrate.test.meta.UpdateEntityLootTables"], + date = "Tue, 28 Apr 2026 01:45:14 GMT", + ) + public override fun add(entityType: EntityType<*>, defaultLootTable: ResourceKey, builder: LootTable.Builder) { + super.add(entityType, defaultLootTable, builder) + } + // GENERATED OVERRIDE END + + companion object { + // @formatter:off + // GENERATED STATIC START + /** Generated override to expose protected method: [EntityLootSubProvider.createSheepTable] */ + @Generated(value = ["com.modularmc.registrate.test.meta.UpdateEntityLootTables"], date = "Tue, 28 Apr 2026 01:45:14 GMT") + @JvmStatic + fun createSheepTable(woolItem: ItemLike): LootTable.Builder = EntityLootSubProvider.createSheepTable(woolItem) + // GENERATED STATIC END + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java deleted file mode 100644 index decd171..0000000 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.modularmc.registrate.providers.loot; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.providers.core.ProviderType; -import com.modularmc.registrate.providers.core.RegistrateProvider; -import com.modularmc.registrate.util.nullness.NonNullConsumer; - -import net.minecraft.core.Holder; -import net.minecraft.core.HolderLookup; -import net.minecraft.core.WritableRegistry; -import net.minecraft.data.PackOutput; -import net.minecraft.data.loot.LootTableProvider; -import net.minecraft.data.loot.LootTableSubProvider; -import net.minecraft.resources.ResourceKey; -import net.minecraft.util.ProblemReporter; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.ValidationContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; -import net.neoforged.fml.LogicalSide; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Multimap; -import org.apache.commons.lang3.function.TriFunction; - -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.function.BiConsumer; -import java.util.function.Consumer; - -public class RegistrateLootTableProvider extends LootTableProvider implements RegistrateProvider { - - public interface LootType { - - static LootType BLOCK = register("block", LootContextParamSets.BLOCK, RegistrateBlockLootTables::new); - static LootType ENTITY = register("entity", LootContextParamSets.ENTITY, RegistrateEntityLootTables::new); - - T getLootCreator(HolderLookup.Provider provider, AbstractRegistrate parent, Consumer callback); - - LootContextParamSet getLootSet(); - - static LootType register(String name, LootContextParamSet set, TriFunction, Consumer, T> factory) { - LootType type = new LootType() { - - @Override - public T getLootCreator(HolderLookup.Provider provider, AbstractRegistrate parent, Consumer callback) { - return factory.apply(provider, parent, callback); - } - - @Override - public LootContextParamSet getLootSet() { - return set; - } - }; - LOOT_TYPES.put(name, type); - return type; - } - } - - private static final Map> LOOT_TYPES = new HashMap<>(); - - private final AbstractRegistrate parent; - - private final Multimap, Consumer> specialLootActions = HashMultimap.create(); - private final Multimap, LootTable.Builder>>> lootActions = HashMultimap.create(); - private final Set currentLootCreators = new HashSet<>(); - - private final CompletableFuture provider; - - public RegistrateLootTableProvider(AbstractRegistrate parent, PackOutput packOutput, CompletableFuture provider) { - super(packOutput, Set.of(), List.of(), provider); - this.parent = parent; - this.provider = provider; - } - - public HolderLookup.Provider getProvider() { - return Objects.requireNonNull(provider.getNow(null), "Loot table registry lookup is not ready"); - } - - public Holder resolve(ResourceKey key) { - return getProvider().lookupOrThrow(key.registryKey()).getOrThrow(key); - } - - @Override - public LogicalSide getSide() { - return LogicalSide.SERVER; - } - - @Override - protected void validate(WritableRegistry tables, ValidationContext validationContext, ProblemReporter.Collector problems) { - super.validate(tables, validationContext, problems); - currentLootCreators.forEach(c -> c.validate(tables, validationContext)); - } - - @SuppressWarnings("unchecked") - public void addLootAction(LootType type, NonNullConsumer action) { - this.specialLootActions.put(type, (Consumer) action); - } - - public void addLootAction(LootContextParamSet set, Consumer, LootTable.Builder>> action) { - this.lootActions.put(set, action); - } - - private LootTableSubProvider getLootCreator(HolderLookup.Provider provider, AbstractRegistrate parent, LootType type) { - RegistrateLootTables creator = type.getLootCreator(provider, parent, cons -> specialLootActions.get(type).forEach(c -> c.accept(cons))); - currentLootCreators.add(creator); - return creator; - } - - @Override - public List getTables() { - parent.genData(ProviderType.LOOT, this); - currentLootCreators.clear(); - ImmutableList.Builder builder = ImmutableList.builder(); - for (LootType type : LOOT_TYPES.values()) { - builder.add(new SubProviderEntry(provider -> getLootCreator(provider, parent, type), type.getLootSet())); - } - lootActions.asMap().forEach((set, actions) -> builder.add( - new SubProviderEntry(provider -> callback -> actions.forEach(action -> action.accept(callback)), set))); - return builder.build(); - } -} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.kt b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.kt new file mode 100644 index 0000000..c602833 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTableProvider.kt @@ -0,0 +1,108 @@ +package com.modularmc.registrate.providers.loot + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.providers.core.RegistrateProvider +import com.modularmc.registrate.util.nullness.NonNullConsumer + +import net.minecraft.core.Holder +import net.minecraft.core.HolderLookup +import net.minecraft.core.WritableRegistry +import net.minecraft.data.PackOutput +import net.minecraft.data.loot.LootTableProvider +import net.minecraft.data.loot.LootTableSubProvider +import net.minecraft.resources.ResourceKey +import net.minecraft.util.ProblemReporter +import net.minecraft.world.level.storage.loot.LootTable +import net.minecraft.world.level.storage.loot.ValidationContext +import net.minecraft.world.level.storage.loot.parameters.LootContextParamSet +import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets +import net.neoforged.fml.LogicalSide + +import com.google.common.collect.HashMultimap +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet +import org.apache.commons.lang3.function.TriFunction + +import java.util.concurrent.CompletableFuture +import java.util.function.BiConsumer +import java.util.function.Consumer + +open class RegistrateLootTableProvider(private val parent: AbstractRegistrate<*>, output: PackOutput, private val lookup: CompletableFuture) : + LootTableProvider(output, emptySet(), emptyList(), lookup), + RegistrateProvider { + /** Defines the context and factory for a family of loot tables. */ + interface LootType { + fun getLootCreator(provider: HolderLookup.Provider, parent: AbstractRegistrate<*>, callback: Consumer): T + + fun getLootSet(): LootContextParamSet + + companion object { + @JvmField + val BLOCK = register("block", LootContextParamSets.BLOCK, ::RegistrateBlockLootTables) + + @JvmField + val ENTITY = register("entity", LootContextParamSets.ENTITY, ::RegistrateEntityLootTables) + + @JvmStatic + fun register(name: String, set: LootContextParamSet, factory: TriFunction, Consumer, T>): LootType { + val type = object : LootType { + override fun getLootCreator(provider: HolderLookup.Provider, parent: AbstractRegistrate<*>, callback: Consumer): T = factory.apply(provider, parent, callback) + + override fun getLootSet(): LootContextParamSet = set + } + lootTypes[name] = type + return type + } + } + } + + private val specialLootActions = HashMultimap.create, Consumer>() + private val lootActions = HashMultimap.create, LootTable.Builder>>>() + private val currentLootCreators = ObjectOpenHashSet() + + open fun getProvider(): HolderLookup.Provider = checkNotNull(lookup.getNow(null)) { "Loot table registry lookup is not ready" } + + open fun resolve(key: ResourceKey): Holder = getProvider().lookupOrThrow(key.registryKey()).getOrThrow(key) + + override fun getSide(): LogicalSide = LogicalSide.SERVER + + override fun validate(tables: WritableRegistry, validationContext: ValidationContext, problems: ProblemReporter.Collector) { + super.validate(tables, validationContext, problems) + for (creator in currentLootCreators) creator.validate(tables, validationContext) + } + + @Suppress("UNCHECKED_CAST") + open fun addLootAction(type: LootType, action: NonNullConsumer) { + specialLootActions.put(type, action as Consumer) + } + + open fun addLootAction(set: LootContextParamSet, action: Consumer, LootTable.Builder>>) { + lootActions.put(set, action) + } + + private fun getLootCreator(provider: HolderLookup.Provider, type: LootType): LootTableSubProvider { + val creator = type.getLootCreator(provider, parent) { tables -> + for (action in specialLootActions[type]) action.accept(tables) + } + currentLootCreators.add(creator) + return creator + } + + override fun getTables(): List { + parent.genData(ProviderType.LOOT, this) + currentLootCreators.clear() + return buildList(lootTypes.size + lootActions.keySet().size) { + for (type in lootTypes.values) { + add(SubProviderEntry({ getLootCreator(it, type) }, type.getLootSet())) + } + for ((set, actions) in lootActions.asMap()) { + add(SubProviderEntry({ LootTableSubProvider { callback -> actions.forEach { it.accept(callback) } } }, set)) + } + } + } + + companion object { + private val lootTypes = Object2ObjectOpenHashMap>() + } +} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java deleted file mode 100644 index 1b5a5e3..0000000 --- a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.modularmc.registrate.providers.loot; - -import net.minecraft.core.WritableRegistry; -import net.minecraft.data.loot.LootTableSubProvider; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.ValidationContext; - -/** - * A loot subprovider with an optional validation step after all tables are collected. - * Implementations generate and validate tables during the same datagen run. - */ -public interface RegistrateLootTables extends LootTableSubProvider { - - /** Validates generated tables and reports problems into the supplied context. */ - default void validate(WritableRegistry tables, ValidationContext validationContext) {} -} diff --git a/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.kt b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.kt new file mode 100644 index 0000000..b884c75 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/providers/loot/RegistrateLootTables.kt @@ -0,0 +1,15 @@ +package com.modularmc.registrate.providers.loot + +import net.minecraft.core.WritableRegistry +import net.minecraft.data.loot.LootTableSubProvider +import net.minecraft.world.level.storage.loot.LootTable +import net.minecraft.world.level.storage.loot.ValidationContext + +/** + * A loot subprovider with an optional validation step after all tables are collected. + * Implementations generate and validate tables during the same datagen run. + */ +interface RegistrateLootTables : LootTableSubProvider { + /** Validates generated tables and reports problems into the supplied context. */ + fun validate(tables: WritableRegistry, validationContext: ValidationContext) {} +} diff --git a/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java b/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java deleted file mode 100644 index 58cb1cb..0000000 --- a/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.modularmc.registrate.util; - -import net.minecraft.world.flag.FeatureFlagSet; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.ItemLike; - -import org.jetbrains.annotations.ApiStatus; - -import java.util.function.BiConsumer; -import java.util.function.BooleanSupplier; -import java.util.function.Supplier; - -public final class CreativeModeTabModifier implements CreativeModeTab.Output { - - private final Supplier flags; - private final BooleanSupplier hasPermissions; - private final BiConsumer acceptFunc; - private final Supplier parameters; - - @ApiStatus.Internal - public CreativeModeTabModifier(Supplier flags, BooleanSupplier hasPermissions, BiConsumer acceptFunc, Supplier parameters) { - this.flags = flags; - this.hasPermissions = hasPermissions; - this.acceptFunc = acceptFunc; - this.parameters = parameters; - } - - public FeatureFlagSet getFlags() { - return flags.get(); - } - - public CreativeModeTab.ItemDisplayParameters getParameters() { - return parameters.get(); - } - - public boolean hasPermissions() { - return hasPermissions.getAsBoolean(); - } - - @Override - public void accept(ItemStack stack, CreativeModeTab.TabVisibility visibility) { - acceptFunc.accept(stack, visibility); - } - - public void accept(Supplier item, CreativeModeTab.TabVisibility visibility) { - accept(item.get(), visibility); - } - - public void accept(Supplier item) { - accept(item.get()); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.kt b/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.kt new file mode 100644 index 0000000..6196bad --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/CreativeModeTabModifier.kt @@ -0,0 +1,39 @@ +package com.modularmc.registrate.util + +import net.minecraft.world.flag.FeatureFlagSet +import net.minecraft.world.item.CreativeModeTab +import net.minecraft.world.item.CreativeModeTab.ItemDisplayParameters +import net.minecraft.world.item.CreativeModeTab.TabVisibility +import net.minecraft.world.item.ItemStack +import net.minecraft.world.level.ItemLike + +import org.jetbrains.annotations.ApiStatus + +import java.util.function.BiConsumer +import java.util.function.BooleanSupplier +import java.util.function.Supplier + +class CreativeModeTabModifier @ApiStatus.Internal constructor( + private val flags: Supplier, + private val hasPermissions: BooleanSupplier, + private val acceptFunc: BiConsumer, + private val parameters: Supplier, +) : CreativeModeTab.Output { + fun getFlags(): FeatureFlagSet = flags.get() + + fun getParameters(): ItemDisplayParameters = parameters.get() + + fun hasPermissions(): Boolean = hasPermissions.asBoolean + + override fun accept(stack: ItemStack, visibility: TabVisibility) { + acceptFunc.accept(stack, visibility) + } + + fun accept(item: Supplier, visibility: TabVisibility) { + accept(item.get(), visibility) + } + + fun accept(item: Supplier) { + accept(item.get()) + } +} diff --git a/src/main/java/com/modularmc/registrate/util/DataIngredient.java b/src/main/java/com/modularmc/registrate/util/DataIngredient.java deleted file mode 100644 index 0a507e8..0000000 --- a/src/main/java/com/modularmc/registrate/util/DataIngredient.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.modularmc.registrate.util; - -import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.advancements.Criterion; -import net.minecraft.advancements.critereon.InventoryChangeTrigger; -import net.minecraft.advancements.critereon.ItemPredicate; -import net.minecraft.core.HolderSet; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.level.ItemLike; - -import com.google.common.collect.ObjectArrays; -import lombok.Getter; - -import java.util.Arrays; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * A helper for data generation when using ingredients as input(s) to recipes.
- * It remembers the name of the primary ingredient for use in creating recipe names/criteria. - *

- * Create an instance of this class with the various factory methods such as {@link #items(ItemLike, ItemLike...)} and - * {@link #tag(TagKey)}. - *

- * This class should not be used for any purpose other than data generation, it will throw an exception - * if it is serialized to a packet buffer. - */ -public final class DataIngredient { - - private final Ingredient parent; - @Getter - private final ResourceLocation id; - private final Function> criteriaFactory; - - private DataIngredient(Ingredient parent, ItemLike item) { - this.parent = parent; - this.id = BuiltInRegistries.ITEM.getKey(item.asItem()); - this.criteriaFactory = ignored -> RegistrateRecipeProvider.has(item); - } - - private DataIngredient(Ingredient parent, TagKey tag) { - this.parent = parent; - this.id = tag.location(); - this.criteriaFactory = ignored -> RegistrateRecipeProvider.has(tag); - } - - private DataIngredient(Ingredient parent, ResourceLocation id, ItemPredicate... predicates) { - this.parent = parent; - this.id = id; - this.criteriaFactory = ignored -> RegistrateRecipeProvider.inventoryTrigger(predicates); - } - - public Criterion getCriterion(RegistrateRecipeProvider prov) { - return criteriaFactory.apply(prov); - } - - @SuppressWarnings("unchecked") - @SafeVarargs - public static DataIngredient items(NonNullSupplier first, NonNullSupplier... others) { - return items(first.get(), (T[]) Arrays.stream(others).map(Supplier::get).toArray(ItemLike[]::new)); - } - - @SafeVarargs - public static DataIngredient items(T first, T... others) { - return ingredient(Ingredient.of(ObjectArrays.concat(first, others)), first); - } - - public static DataIngredient tag(HolderSet.Named tag) { - return tag(tag.key()); - } - - public static DataIngredient tag(TagKey tag) { - return ingredient(Ingredient.of(tag), tag); - } - - public static DataIngredient ingredient(Ingredient parent, ItemLike required) { - return new DataIngredient(parent, required); - } - - public static DataIngredient ingredient(Ingredient parent, TagKey required) { - return new DataIngredient(parent, required); - } - - public static DataIngredient ingredient(Ingredient parent, ResourceLocation id, ItemPredicate... criteria) { - return new DataIngredient(parent, id, criteria); - } - - public Ingredient toVanilla() { - return parent; - } -} diff --git a/src/main/java/com/modularmc/registrate/util/DataIngredient.kt b/src/main/java/com/modularmc/registrate/util/DataIngredient.kt new file mode 100644 index 0000000..fdcf80b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/DataIngredient.kt @@ -0,0 +1,57 @@ +package com.modularmc.registrate.util + +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider.Companion.has +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider.Companion.inventoryTrigger +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.advancements.Criterion +import net.minecraft.advancements.critereon.InventoryChangeTrigger.TriggerInstance +import net.minecraft.advancements.critereon.ItemPredicate +import net.minecraft.core.HolderSet +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.resources.ResourceLocation +import net.minecraft.tags.TagKey +import net.minecraft.world.item.Item +import net.minecraft.world.item.crafting.Ingredient +import net.minecraft.world.level.ItemLike + +import java.util.function.Supplier + +/** A vanilla ingredient with the recipe ID and criterion used during DataGen. */ +class DataIngredient private constructor(private val ingredient: Ingredient, val id: ResourceLocation, private val criterion: Supplier>) { + @Suppress("UNUSED_PARAMETER") + fun getCriterion(provider: RegistrateRecipeProvider): Criterion = criterion.get() + + fun toVanilla(): Ingredient = ingredient + + companion object { + @JvmStatic + fun items(first: NonNullSupplier, vararg others: NonNullSupplier): DataIngredient { + val required = first.get() + val inputs = Array(others.size + 1) { index -> if (index == 0) required else others[index - 1].get() } + return ingredient(Ingredient.of(*inputs), required) + } + + @JvmStatic + fun items(first: T, vararg others: T): DataIngredient { + val inputs = Array(others.size + 1) { index -> if (index == 0) first else others[index - 1] } + return ingredient(Ingredient.of(*inputs), first) + } + + @JvmStatic + fun tag(tag: HolderSet.Named): DataIngredient = tag(tag.key()) + + @JvmStatic + fun tag(tag: TagKey): DataIngredient = ingredient(Ingredient.of(tag), tag) + + @JvmStatic + fun ingredient(ingredient: Ingredient, required: ItemLike): DataIngredient = DataIngredient(ingredient, BuiltInRegistries.ITEM.getKey(required.asItem())) { has(required) } + + @JvmStatic + fun ingredient(ingredient: Ingredient, required: TagKey): DataIngredient = DataIngredient(ingredient, required.location()) { has(required) } + + @JvmStatic + fun ingredient(ingredient: Ingredient, id: ResourceLocation, vararg criteria: ItemPredicate): DataIngredient = DataIngredient(ingredient, id) { inventoryTrigger(*criteria) } + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java b/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java deleted file mode 100644 index 269c64b..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.neoforge.registries.DeferredHolder; - -import org.jspecify.annotations.Nullable; - -import java.util.Optional; - -public class BlockEntityEntry extends RegistryEntry, BlockEntityType> { - - public BlockEntityEntry(AbstractRegistrate owner, DeferredHolder, BlockEntityType> delegate) { - super(owner, delegate); - } - - /** - * Create a "default" instance of this {@link BlockEntity} via the {@link BlockEntityType}. - * - * @return The instance - */ - public T create(BlockPos pos, BlockState state) { - return get().create(pos, state); - } - - /** - * Check that the given {@link BlockEntity} is an instance of this type. - * - * @param t - * The {@link BlockEntity} instance - * @return {@code true} if the type matches, {@code false} otherwise. - */ - public boolean is(@Nullable BlockEntity t) { - return t != null && t.getType() == get(); - } - - /** - * Get an instance of this {@link BlockEntity} from the world. - * - * @param world - * The world to look for the instance in - * @param pos - * The position of the instance - * @return An {@link Optional} containing the instance, if it exists and matches this type. Otherwise, - * {@link Optional#empty()}. - */ - public Optional get(BlockGetter world, BlockPos pos) { - return Optional.ofNullable(getNullable(world, pos)); - } - - /** - * Get an instance of this {@link BlockEntity} from the world. - * - * @param world - * The world to look for the instance in - * @param pos - * The position of the instance - * @return The instance, if it exists and matches this type. Otherwise, {@code null}. - */ - @SuppressWarnings("unchecked") - public @Nullable T getNullable(BlockGetter world, BlockPos pos) { - BlockEntity be = world.getBlockEntity(pos); - return is(be) ? (T) be : null; - } - - public static BlockEntityEntry cast(RegistryEntry, BlockEntityType> entry) { - return RegistryEntry.cast(BlockEntityEntry.class, entry); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.kt new file mode 100644 index 0000000..c24f580 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/BlockEntityEntry.kt @@ -0,0 +1,33 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.core.BlockPos +import net.minecraft.world.level.BlockGetter +import net.minecraft.world.level.block.entity.BlockEntity +import net.minecraft.world.level.block.entity.BlockEntityType +import net.minecraft.world.level.block.state.BlockState +import net.neoforged.neoforge.registries.DeferredHolder + +import java.util.Optional + +open class BlockEntityEntry(owner: AbstractRegistrate<*>, delegate: DeferredHolder, BlockEntityType>) : + RegistryEntry, BlockEntityType>(owner, delegate) { + open fun create(pos: BlockPos, state: BlockState): T? = get().create(pos, state) + + open fun `is`(entity: BlockEntity?): Boolean = entity != null && entity.type === get() + + open fun get(world: BlockGetter, pos: BlockPos): Optional = Optional.ofNullable(getNullable(world, pos)) + + @Suppress("UNCHECKED_CAST") + open fun getNullable(world: BlockGetter, pos: BlockPos): T? { + val entity = world.getBlockEntity(pos) + return if (`is`(entity)) entity as T else null + } + + companion object { + @JvmStatic + @Suppress("UNCHECKED_CAST") + fun cast(entry: RegistryEntry, BlockEntityType>): BlockEntityEntry = entry as BlockEntityEntry + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java b/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java deleted file mode 100644 index 14623e3..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.neoforged.neoforge.registries.DeferredHolder; - -public class BlockEntry extends ItemProviderEntry { - - public BlockEntry(AbstractRegistrate owner, DeferredHolder delegate) { - super(owner, delegate); - } - - public BlockState getDefaultState() { - return get().defaultBlockState(); - } - - public boolean has(BlockState state) { - return is(state.getBlock()); - } - - public static BlockEntry cast(RegistryEntry entry) { - return RegistryEntry.cast(BlockEntry.class, entry); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.kt new file mode 100644 index 0000000..dcbaebd --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/BlockEntry.kt @@ -0,0 +1,19 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.block.state.BlockState +import net.neoforged.neoforge.registries.DeferredHolder + +open class BlockEntry(owner: AbstractRegistrate<*>, delegate: DeferredHolder) : ItemProviderEntry(owner, delegate) { + open fun getDefaultState(): BlockState = get().defaultBlockState() + + open fun has(state: BlockState): Boolean = `is`(state.block) + + companion object { + @JvmStatic + @Suppress("UNCHECKED_CAST") + fun cast(entry: RegistryEntry): BlockEntry = entry as BlockEntry + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java b/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java deleted file mode 100644 index 64cd3cb..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.level.Level; -import net.neoforged.neoforge.registries.DeferredHolder; - -import org.jspecify.annotations.Nullable; - -public class EntityEntry extends RegistryEntry, EntityType> { - - public EntityEntry(AbstractRegistrate owner, DeferredHolder, EntityType> delegate) { - super(owner, delegate); - } - - public @Nullable T create(Level world) { - return get().create(world); - } - - public boolean is(Entity t) { - return t != null && t.getType() == get(); - } - - public static EntityEntry cast(RegistryEntry, EntityType> entry) { - return RegistryEntry.cast(EntityEntry.class, entry); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.kt new file mode 100644 index 0000000..a13505b --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/EntityEntry.kt @@ -0,0 +1,20 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.world.entity.Entity +import net.minecraft.world.entity.EntityType +import net.minecraft.world.level.Level +import net.neoforged.neoforge.registries.DeferredHolder + +open class EntityEntry(owner: AbstractRegistrate<*>, delegate: DeferredHolder, EntityType>) : RegistryEntry, EntityType>(owner, delegate) { + open fun create(world: Level): T? = get().create(world) + + open fun `is`(entity: Entity?): Boolean = entity != null && entity.type === get() + + companion object { + @JvmStatic + @Suppress("UNCHECKED_CAST") + fun cast(entry: RegistryEntry, EntityType>): EntityEntry = entry as EntityEntry + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/EntryMetadata.kt b/src/main/java/com/modularmc/registrate/util/entry/EntryMetadata.kt new file mode 100644 index 0000000..ae7c0f6 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/EntryMetadata.kt @@ -0,0 +1,19 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.localization.EntryLocalization +import com.modularmc.registrate.providers.core.GeneratorType +import com.modularmc.registrate.util.nullness.NonNullConsumer + +import java.util.Collections + +/** The data generation and localization declarations associated with a registration. */ +class EntryMetadata(generators: Collection>, private val localization: EntryLocalization?) { + private val generators = Collections.unmodifiableCollection(generators) + + fun dataGenerators(): Collection> = generators + + fun localization(): EntryLocalization? = localization + + @JvmRecord + data class DataGenerator

(val type: GeneratorType, val callback: NonNullConsumer) +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java b/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java deleted file mode 100644 index 88111f7..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.material.Fluid; -import net.neoforged.neoforge.fluids.BaseFlowingFluid; -import net.neoforged.neoforge.fluids.FluidType; -import net.neoforged.neoforge.registries.DeferredHolder; - -import org.jspecify.annotations.Nullable; - -import java.util.Optional; - -public class FluidEntry extends RegistryEntry { - - private final @Nullable BlockEntry block; - - public FluidEntry(AbstractRegistrate owner, DeferredHolder delegate) { - super(owner, delegate); - this.block = getSiblingOptional(BuiltInRegistries.BLOCK) - .map(BlockEntry::cast) - .orElse(null); - } - - @Override - public boolean is(R entry) { - return get().isSame((Fluid) entry); - } - - @SuppressWarnings("unchecked") - public S getSource() { - return (S) get().getSource(); - } - - public FluidType getType() { - return get().getFluidType(); - } - - @SuppressWarnings({ "unchecked", "null" }) - public Optional getBlock() { - return (Optional) Optional.ofNullable(block).map(RegistryEntry::get); - } - - @SuppressWarnings({ "unchecked", "null" }) - public Optional getBucket() { - return Optional.of((I) get().getBucket()) - .filter(item -> item != Items.AIR); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.kt new file mode 100644 index 0000000..67f688e --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/FluidEntry.kt @@ -0,0 +1,31 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.core.registries.BuiltInRegistries +import net.minecraft.world.item.Item +import net.minecraft.world.item.Items +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.material.Fluid +import net.neoforged.neoforge.fluids.BaseFlowingFluid +import net.neoforged.neoforge.fluids.FluidType +import net.neoforged.neoforge.registries.DeferredHolder + +import java.util.Optional + +open class FluidEntry(owner: AbstractRegistrate<*>, delegate: DeferredHolder) : RegistryEntry(owner, delegate) { + private val block = getSiblingOptional(BuiltInRegistries.BLOCK).map { BlockEntry.cast(it) }.orElse(null) + + override fun `is`(entry: R): Boolean = get().isSame(entry as Fluid) + + @Suppress("UNCHECKED_CAST") + open fun getSource(): S = get().source as S + + open fun getType(): FluidType = get().fluidType + + @Suppress("UNCHECKED_CAST") + open fun getBlock(): Optional = Optional.ofNullable(block?.get() as B?) + + @Suppress("UNCHECKED_CAST") + open fun getBucket(): Optional = Optional.ofNullable(get().bucket.takeUnless { it === Items.AIR } as I?) +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java b/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java deleted file mode 100644 index 6aa577e..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.world.item.Item; -import net.neoforged.neoforge.registries.DeferredHolder; - -public class ItemEntry extends ItemProviderEntry { - - public ItemEntry(AbstractRegistrate owner, DeferredHolder delegate) { - super(owner, delegate); - } - - public static ItemEntry cast(RegistryEntry entry) { - return RegistryEntry.cast(ItemEntry.class, entry); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.kt new file mode 100644 index 0000000..b210a23 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/ItemEntry.kt @@ -0,0 +1,14 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.world.item.Item +import net.neoforged.neoforge.registries.DeferredHolder + +open class ItemEntry(owner: AbstractRegistrate<*>, delegate: DeferredHolder) : ItemProviderEntry(owner, delegate) { + companion object { + @JvmStatic + @Suppress("UNCHECKED_CAST") + fun cast(entry: RegistryEntry): ItemEntry = entry as ItemEntry + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java b/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java deleted file mode 100644 index c30816b..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.ItemLike; -import net.neoforged.neoforge.registries.DeferredHolder; - -public class ItemProviderEntry extends RegistryEntry implements ItemLike { - - public ItemProviderEntry(AbstractRegistrate owner, DeferredHolder delegate) { - super(owner, delegate); - } - - public ItemStack asStack() { - return new ItemStack(this); - } - - public ItemStack asStack(int count) { - return new ItemStack(this, count); - } - - public boolean isIn(ItemStack stack) { - return is(stack.getItem()); - } - - public boolean is(Item item) { - return asItem() == item; - } - - @Override - public Item asItem() { - return get().asItem(); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.kt new file mode 100644 index 0000000..d1d17f2 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/ItemProviderEntry.kt @@ -0,0 +1,22 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.world.item.Item +import net.minecraft.world.item.ItemStack +import net.minecraft.world.level.ItemLike +import net.neoforged.neoforge.registries.DeferredHolder + +open class ItemProviderEntry(owner: AbstractRegistrate<*>, delegate: DeferredHolder) : + RegistryEntry(owner, delegate), + ItemLike { + open fun asStack(): ItemStack = ItemStack(this) + + open fun asStack(count: Int): ItemStack = ItemStack(this, count) + + open fun isIn(stack: ItemStack): Boolean = `is`(stack.item) + + open fun `is`(item: Item): Boolean = asItem() === item + + override fun asItem(): Item = get().asItem() +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java b/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java deleted file mode 100644 index afce5e8..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import org.jspecify.annotations.Nullable; - -public class LazyRegistryEntry implements NonNullSupplier { - - private @Nullable NonNullSupplier> supplier; - private @Nullable RegistryEntry value; - - public LazyRegistryEntry(NonNullSupplier> supplier) { - this.supplier = supplier; - } - - @Override - public T get() { - NonNullSupplier> supplier = this.supplier; - if (supplier != null) { - this.value = supplier.get(); - this.supplier = null; - } - return this.value.get(); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.kt new file mode 100644 index 0000000..20f9400 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/LazyRegistryEntry.kt @@ -0,0 +1,9 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.util.nullness.NonNullSupplier + +open class LazyRegistryEntry(supplier: NonNullSupplier>) : NonNullSupplier { + private val holder by lazy(LazyThreadSafetyMode.NONE) { supplier.get() } + + override fun get(): T = holder.get() +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java b/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java deleted file mode 100644 index de3ec28..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; - -import net.minecraft.network.RegistryFriendlyByteBuf; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.SimpleMenuProvider; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuConstructor; -import net.minecraft.world.inventory.MenuType; -import net.neoforged.neoforge.registries.DeferredHolder; - -import java.util.function.Consumer; - -public class MenuEntry extends RegistryEntry, MenuType> { - - public MenuEntry(AbstractRegistrate owner, DeferredHolder, MenuType> delegate) { - super(owner, delegate); - } - - public T create(int windowId, Inventory playerInv) { - return get().create(windowId, playerInv); - } - - public MenuConstructor asProvider() { - return (window, playerinv, $) -> create(window, playerinv); - } - - public void open(ServerPlayer player, Component displayName) { - open(player, displayName, asProvider()); - } - - public void open(ServerPlayer player, Component displayName, Consumer extraData) { - open(player, displayName, asProvider(), extraData); - } - - public void open(ServerPlayer player, Component displayName, MenuConstructor provider) { - player.openMenu(new SimpleMenuProvider(provider, displayName)); - } - - public void open(ServerPlayer player, Component displayName, MenuConstructor provider, Consumer extraData) { - player.openMenu(new SimpleMenuProvider(provider, displayName), extraData); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.kt new file mode 100644 index 0000000..25ac8d9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/MenuEntry.kt @@ -0,0 +1,37 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate + +import net.minecraft.network.RegistryFriendlyByteBuf +import net.minecraft.network.chat.Component +import net.minecraft.server.level.ServerPlayer +import net.minecraft.world.SimpleMenuProvider +import net.minecraft.world.entity.player.Inventory +import net.minecraft.world.inventory.AbstractContainerMenu +import net.minecraft.world.inventory.MenuConstructor +import net.minecraft.world.inventory.MenuType +import net.neoforged.neoforge.registries.DeferredHolder + +import java.util.function.Consumer + +open class MenuEntry(owner: AbstractRegistrate<*>, delegate: DeferredHolder, MenuType>) : RegistryEntry, MenuType>(owner, delegate) { + open fun create(windowId: Int, inventory: Inventory): T = get().create(windowId, inventory) + + open fun asProvider(): MenuConstructor = MenuConstructor { windowId, inventory, _ -> create(windowId, inventory) } + + open fun open(player: ServerPlayer, displayName: Component) { + open(player, displayName, asProvider()) + } + + open fun open(player: ServerPlayer, displayName: Component, extraData: Consumer) { + open(player, displayName, asProvider(), extraData) + } + + open fun open(player: ServerPlayer, displayName: Component, provider: MenuConstructor) { + player.openMenu(SimpleMenuProvider(provider, displayName)) + } + + open fun open(player: ServerPlayer, displayName: Component, provider: MenuConstructor, extraData: Consumer) { + player.openMenu(SimpleMenuProvider(provider, displayName), extraData) + } +} diff --git a/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java b/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java deleted file mode 100644 index f9f44f3..0000000 --- a/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.modularmc.registrate.util.entry; - -import com.modularmc.registrate.AbstractRegistrate; -import com.modularmc.registrate.util.nullness.NonNullSupplier; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.neoforged.neoforge.registries.DeferredHolder; - -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; - -/** - * Wraps a {@link net.neoforged.neoforge.registries.DeferredHolder}, providing a cleaner API with null-safe access, and - * registrate-specific extensions such as {@link #getSibling(ResourceKey)} and - * {@link #getSiblingOptional(ResourceKey)}. - * - * @param - * The type of the entry - */ -public class RegistryEntry extends DeferredHolder implements NonNullSupplier { - - private final AbstractRegistrate owner; - - @SuppressWarnings("unused") - public RegistryEntry(AbstractRegistrate owner, DeferredHolder key) { - super(key.getKey()); - - if (owner == null) - throw new NullPointerException("Owner must not be null"); - this.owner = owner; - } - - public RegistryEntry getSibling(ResourceKey> registryType) { - return owner.get(getId().getPath(), registryType); - } - - public Optional> getSiblingOptional(ResourceKey> registryType) { - return owner.getOptional(getId().getPath(), registryType); - } - - public RegistryEntry getSibling(Registry registry) { - return getSibling(registry.key()); - } - - public Optional> getSiblingOptional(Registry registry) { - return getSiblingOptional(registry.key()); - } - - /** - * If an entry is present, and the entry matches the given predicate, return an {@link Optional} - * describing the value, otherwise return an empty {@link Optional}. - * - * @param predicate - * a {@link Predicate predicate} to apply to the entry, if present - * @return an {@link RegistryEntry} describing the value of this {@link RegistryEntry} if the entry is present and - * matches the given predicate, otherwise an empty {@link RegistryEntry} - * @throws NullPointerException - * if the predicate is null - */ - public Optional> filter(Predicate predicate) { - Objects.requireNonNull(predicate); - if (predicate.test(get())) { - return Optional.of(this); - } - return Optional.empty(); - } - - public boolean is(X entry) { - return get() == entry; - } - - @SuppressWarnings("unchecked") - protected static > E cast(Class clazz, RegistryEntry entry) { - if (clazz.isInstance(entry)) { - return (E) entry; - } - throw new IllegalArgumentException("Could not convert RegistryEntry: expecting " + clazz + ", found " + entry.getClass()); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.kt b/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.kt new file mode 100644 index 0000000..4cab73a --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/entry/RegistryEntry.kt @@ -0,0 +1,37 @@ +package com.modularmc.registrate.util.entry + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.Registry +import net.minecraft.resources.ResourceKey +import net.neoforged.neoforge.registries.DeferredHolder + +import java.util.Optional +import java.util.function.Predicate + +/** A deferred holder with access to its registration metadata and siblings of the same name. */ +open class RegistryEntry(private val owner: AbstractRegistrate<*>, holder: DeferredHolder) : + DeferredHolder(holder.key), + NonNullSupplier { + /** Returns the declarations associated with this entry, even before the holder binds. */ + open fun metadata(): EntryMetadata = owner.getEntryMetadata(key) + + open fun getSibling(registryType: ResourceKey>): RegistryEntry = owner.get(id.path, registryType) + + open fun getSiblingOptional(registryType: ResourceKey>): Optional> = owner.getOptional(id.path, registryType) + + open fun getSibling(registry: Registry): RegistryEntry = getSibling(registry.key()) + + open fun getSiblingOptional(registry: Registry): Optional> = getSiblingOptional(registry.key()) + + open fun filter(predicate: Predicate): Optional> = if (predicate.test(get())) Optional.of(this) else Optional.empty() + + open fun `is`(entry: X): Boolean = get() === entry + + companion object { + @JvmStatic + @Suppress("UNCHECKED_CAST") + protected fun > cast(type: Class, entry: RegistryEntry<*, *>): E = type.cast(entry) as E + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java b/src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java deleted file mode 100644 index cb23b90..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/FieldsAreNonnullByDefault.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.annotation.Nonnull; -import javax.annotation.meta.TypeQualifierDefault; - -/** - * This annotation can be applied to a package or class to indicate that the fields in that element are nonnull by - * default unless there is: - *

    - *
  • An explicit nullness annotation - *
  • there is a default parameter annotation applied to a more tightly nested element. - *
- */ -@Documented -@Nonnull -@TypeQualifierDefault(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.PACKAGE, ElementType.TYPE }) -public @interface FieldsAreNonnullByDefault {} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java deleted file mode 100644 index 033697e..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.util.function.BiConsumer; - -@FunctionalInterface -public interface NonNullBiConsumer extends BiConsumer { - - @Override - void accept(T t, U u); - - static NonNullBiConsumer noop() { - return (t, u) -> {}; - } -} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.kt b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.kt new file mode 100644 index 0000000..8e33abf --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiConsumer.kt @@ -0,0 +1,14 @@ +package com.modularmc.registrate.util.nullness + +import java.util.function.BiConsumer + +/** Consumes two non-null values synchronously in registration or DataGen callbacks. */ +fun interface NonNullBiConsumer : BiConsumer { + /** Consumes both values on the caller's thread and propagates callback failures. */ + override fun accept(first: T, second: U) + + companion object { + @JvmStatic + fun noop(): NonNullBiConsumer = NonNullBiConsumer { _, _ -> } + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java deleted file mode 100644 index eabc7d6..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.util.function.BiFunction; - -@FunctionalInterface -public interface NonNullBiFunction extends BiFunction { - - @Override - R apply(T t, U u); -} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.kt b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.kt new file mode 100644 index 0000000..4778995 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullBiFunction.kt @@ -0,0 +1,9 @@ +package com.modularmc.registrate.util.nullness + +import java.util.function.BiFunction + +/** Computes a non-null result from two non-null inputs on the caller's thread. */ +fun interface NonNullBiFunction : BiFunction { + /** Invokes the transform synchronously and propagates callback failures. */ + override fun apply(first: T, second: U): R +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java deleted file mode 100644 index 8e23abf..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.util.Objects; -import java.util.function.Consumer; - -@FunctionalInterface -public interface NonNullConsumer extends Consumer { - - @Override - void accept(T t); - - default NonNullConsumer andThen(NonNullConsumer after) { - Objects.requireNonNull(after); - return (T t) -> { - accept(t); - after.accept(t); - }; - } - - static NonNullConsumer noop() { - return t -> {}; - } -} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.kt b/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.kt new file mode 100644 index 0000000..eafc362 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullConsumer.kt @@ -0,0 +1,19 @@ +package com.modularmc.registrate.util.nullness + +import java.util.function.Consumer + +/** Consumes a value during the calling operation. Both callbacks run in order when composed. */ +fun interface NonNullConsumer : Consumer { + /** Runs on the caller's thread and propagates callback failures. */ + override fun accept(value: T) + + fun andThen(after: NonNullConsumer): NonNullConsumer = NonNullConsumer { value -> + accept(value) + after.accept(value) + } + + companion object { + @JvmStatic + fun noop(): NonNullConsumer = NonNullConsumer {} + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java deleted file mode 100644 index bfbcbe2..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.util.Objects; -import java.util.function.Function; - -@FunctionalInterface -public interface NonNullFunction extends Function { - - @Override - R apply(T t); - - default NonNullFunction andThen(NonNullFunction after) { - Objects.requireNonNull(after); - return t -> after.apply(apply(t)); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.kt b/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.kt new file mode 100644 index 0000000..4466721 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullFunction.kt @@ -0,0 +1,11 @@ +package com.modularmc.registrate.util.nullness + +import java.util.function.Function + +/** Transforms a non-null value while keeping a non-null result through composition. */ +fun interface NonNullFunction : Function { + /** Runs synchronously and propagates callback failures to the caller. */ + override fun apply(value: T): R + + fun andThen(after: NonNullFunction): NonNullFunction = NonNullFunction { after.apply(apply(it)) } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java deleted file mode 100644 index b6cad27..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import net.neoforged.neoforge.common.util.Lazy; - -import java.util.Objects; -import java.util.function.Supplier; - -@FunctionalInterface -public interface NonNullSupplier extends Supplier { - - @Override - T get(); - - static NonNullSupplier of(Supplier sup) { - return of(sup, () -> "Unexpected null value from supplier"); - } - - static NonNullSupplier of(Supplier sup, NonNullSupplier errorMsg) { - return () -> { - T res = sup.get(); - Objects.requireNonNull(res, errorMsg); - return res; - }; - } - - default NonNullSupplier lazy() { - return lazy(this); - } - - static NonNullSupplier lazy(Supplier sup) { - return Lazy.of(sup)::get; - } -} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.kt b/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.kt new file mode 100644 index 0000000..65a03e4 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullSupplier.kt @@ -0,0 +1,30 @@ +package com.modularmc.registrate.util.nullness + +import net.neoforged.neoforge.common.util.Lazy + +import java.util.Objects +import java.util.function.Supplier + +/** Supplies a non-null value when a registration or provider callback needs it. */ +fun interface NonNullSupplier : Supplier { + /** Computes the value on the caller's thread and propagates supplier failures. */ + override fun get(): T + + fun lazy(): NonNullSupplier = lazy(this) + + companion object { + /** Adapts a Java supplier and reports a null result when the adapter is used. */ + @JvmStatic + fun of(supplier: Supplier): NonNullSupplier = of(supplier) { "Unexpected null value from supplier" } + + @JvmStatic + fun of(supplier: Supplier, errorMessage: NonNullSupplier): NonNullSupplier = NonNullSupplier { Objects.requireNonNull(supplier.get(), errorMessage) } + + /** Defers computation until first use and memoizes the result through NeoForge's [Lazy]. */ + @JvmStatic + fun lazy(supplier: Supplier): NonNullSupplier { + val value = Lazy.of(supplier) + return NonNullSupplier { value.get() } + } + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java b/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java deleted file mode 100644 index b8cb544..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.util.Objects; - -@FunctionalInterface -public interface NonNullUnaryOperator extends NonNullFunction { - - static NonNullUnaryOperator identity() { - return t -> t; - } - - default NonNullUnaryOperator andThen(NonNullUnaryOperator after) { - Objects.requireNonNull(after); - return t -> after.apply(apply(t)); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.kt b/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.kt new file mode 100644 index 0000000..5e7a2e9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonNullUnaryOperator.kt @@ -0,0 +1,12 @@ +package com.modularmc.registrate.util.nullness + +/** Transforms a value without changing its type, as used by builder property callbacks. */ +fun interface NonNullUnaryOperator : NonNullFunction { + /** Composes transformations in call order and propagates failures from either. */ + fun andThen(after: NonNullUnaryOperator): NonNullUnaryOperator = NonNullUnaryOperator { after.apply(apply(it)) } + + companion object { + @JvmStatic + fun identity(): NonNullUnaryOperator = NonNullUnaryOperator { it } + } +} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java b/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java deleted file mode 100644 index a592b2c..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.annotation.Nonnull; - -/** - * An alternative to {@link javax.annotation.Nonnull} which works on type parameters (J8 feature). - */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_PARAMETER, ElementType.TYPE_USE }) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Nonnull -public @interface NonnullType {} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.kt b/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.kt new file mode 100644 index 0000000..d3775f8 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/util/nullness/NonnullType.kt @@ -0,0 +1,18 @@ +package com.modularmc.registrate.util.nullness + +import javax.annotation.Nonnull + +/** Non-null type-use annotation retained for Java consumers. */ +@MustBeDocumented +@Nonnull +@Retention(AnnotationRetention.RUNTIME) +@Target( + AnnotationTarget.FIELD, + AnnotationTarget.FUNCTION, + AnnotationTarget.PROPERTY_GETTER, + AnnotationTarget.PROPERTY_SETTER, + AnnotationTarget.VALUE_PARAMETER, + AnnotationTarget.TYPE_PARAMETER, + AnnotationTarget.TYPE, +) +annotation class NonnullType diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java b/src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java deleted file mode 100644 index 351c051..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NullableSupplier.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import org.jspecify.annotations.Nullable; - -import java.util.Objects; -import java.util.function.Supplier; - -@Deprecated -public interface NullableSupplier extends Supplier<@Nullable T> { - - @Override - @Nullable - T get(); - - default T getNonNull() { - return getNonNull(() -> "Unexpected null value from supplier"); - } - - default T getNonNull(NonNullSupplier errorMsg) { - T res = get(); - Objects.requireNonNull(res, errorMsg); - return res; - } - - default NonNullSupplier asNonNull() { - return () -> getNonNull(); - } - - default NonNullSupplier asNonNull(NonNullSupplier errorMsg) { - return () -> getNonNull(errorMsg); - } -} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/NullableType.java b/src/main/java/com/modularmc/registrate/util/nullness/NullableType.java deleted file mode 100644 index e01dfa7..0000000 --- a/src/main/java/com/modularmc/registrate/util/nullness/NullableType.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.modularmc.registrate.util.nullness; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.annotation.Nullable; - -/** - * An alternative to {@link javax.annotation.Nullable} which works on type parameters (J8 feature). - */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_PARAMETER, ElementType.TYPE_USE }) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Nullable -public @interface NullableType {} diff --git a/src/main/java/com/modularmc/registrate/util/nullness/package-info.java b/src/main/java/com/modularmc/registrate/util/nullness/package-info.java index dda48a4..57e8d30 100644 --- a/src/main/java/com/modularmc/registrate/util/nullness/package-info.java +++ b/src/main/java/com/modularmc/registrate/util/nullness/package-info.java @@ -5,5 +5,7 @@ * This package centralizes the functional interfaces and annotations used to * keep the fluent API ergonomic while remaining explicit about null contracts. */ -@org.jspecify.annotations.NullMarked +@NullMarked package com.modularmc.registrate.util.nullness; + +import org.jspecify.annotations.NullMarked; diff --git a/src/test/generated/resources/assets/testmod/lang/en_ud.json b/src/test/generated/resources/assets/testmod/lang/en_ud.json index a236878..781ae6f 100644 --- a/src/test/generated/resources/assets/testmod/lang/en_ud.json +++ b/src/test/generated/resources/assets/testmod/lang/en_ud.json @@ -9,6 +9,7 @@ "entity.testmod.testitem": "ɯǝʇıʇsǝ⟘", "fluid.testmod.testbucketfluid": "pınןɟʇǝʞɔnqʇsǝ⟘", "fluid.testmod.testfluid": "pınןɟʇsǝ⟘", + "gui.testmod.voltage": "Λ %1$s :ǝbɐʇןoΛ", "item.testmod.testbucketfluid_bucket": "ʇǝʞɔnᗺ pınןɟʇǝʞɔnqʇsǝ⟘", "item.testmod.testentity_spawn_egg": "bbƎ uʍɐdS ʎʇıʇuǝʇsǝ⟘", "item.testmod.testitem": "ɯǝʇıʇsǝ⟘", @@ -18,6 +19,6 @@ "testmod.custom.lang.brackets": "◁ϛ ʇǝʞɔɐɹᗺ▷ <ㄣ ʇǝʞɔɐɹᗺ> {Ɛ ʇǝʞɔɐɹᗺ} [ᄅ ʇǝʞɔɐɹᗺ] (Ɩ ʇǝʞɔɐɹᗺ)", "testmod.custom.lang.slashes": "/ ɥsɐןsʞɔɐq ɐ sı ǝɹǝɥ puɐ poob ʞooן spuɐɯɯɯoɔ\\", "testmod.custom.lang.with_placeholders1": "%2$s ᄅ ɹǝpןoɥǝɔɐןԀ %1$s Ɩ ɹǝpןoɥǝɔɐןԀ", - "testmod.custom.lang.with_placeholders2": "%3$s Ɛ ɹǝpןoɥǝɔɐןԀ %2$s ᄅ ɹǝpןoɥǝɔɐןԀ %1$s Ɩ ɹǝpןoɥǝɔɐןԀ", + "testmod.custom.lang.with_placeholders2": "%2$s Ɛ ɹǝpןoɥǝɔɐןԀ %2$s ᄅ ɹǝpןoɥǝɔɐןԀ %1$s Ɩ ɹǝpןoɥǝɔɐןԀ", "tooltip.testmod.testblock": "˙bbƎ" } \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/lang/en_us.json b/src/test/generated/resources/assets/testmod/lang/en_us.json index 58f56c5..53aeab1 100644 --- a/src/test/generated/resources/assets/testmod/lang/en_us.json +++ b/src/test/generated/resources/assets/testmod/lang/en_us.json @@ -9,6 +9,7 @@ "entity.testmod.testitem": "Testitem", "fluid.testmod.testbucketfluid": "Testbucketfluid", "fluid.testmod.testfluid": "Testfluid", + "gui.testmod.voltage": "Voltage: %s V", "item.testmod.testbucketfluid_bucket": "Testbucketfluid Bucket", "item.testmod.testentity_spawn_egg": "Testentity Spawn Egg", "item.testmod.testitem": "Testitem", diff --git a/src/test/generated/resources/assets/testmod/lang/zh_cn.json b/src/test/generated/resources/assets/testmod/lang/zh_cn.json new file mode 100644 index 0000000..b10973b --- /dev/null +++ b/src/test/generated/resources/assets/testmod/lang/zh_cn.json @@ -0,0 +1,4 @@ +{ + "gui.testmod.voltage": "电压:%1$s V", + "item.testmod.testitem": "测试物品" +} \ No newline at end of file diff --git a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java b/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java deleted file mode 100644 index d297010..0000000 --- a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.modularmc.registrate.test.gametests; - -import com.modularmc.registrate.test.mod.TestMod; - -import net.minecraft.gametest.framework.GameTest; -import net.neoforged.testframework.DynamicTest; -import net.neoforged.testframework.annotation.ForEachTest; -import net.neoforged.testframework.annotation.TestHolder; -import net.neoforged.testframework.gametest.EmptyTemplate; - -@ForEachTest(groups = "custom-item") -@SuppressWarnings("unused") -public class CustomItemTests { - - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = "Ensure custom item is registered and has the expected properties") - public static void ensureItemContent(final DynamicTest test) { - test.onGameTest(helper -> helper.startSequence(() -> TestMod.instance().testitem.asStack()) - .thenMap(stack -> stack.getItem().getDescriptionId()) - .thenExecute(descriptionId -> helper.assertValueEqual("item.testmod.testitem", descriptionId, "Test Item translation key")) - .thenSucceed()); - } -} diff --git a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.kt b/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.kt new file mode 100644 index 0000000..634677d --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.kt @@ -0,0 +1,24 @@ +package com.modularmc.registrate.test.gametests + +import com.modularmc.registrate.test.mod.TestMod + +import net.minecraft.gametest.framework.GameTest +import net.neoforged.testframework.DynamicTest +import net.neoforged.testframework.annotation.ForEachTest +import net.neoforged.testframework.annotation.TestHolder +import net.neoforged.testframework.gametest.EmptyTemplate + +@ForEachTest(groups = ["custom-item"]) +object CustomItemTests { + @JvmStatic + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = ["Ensure custom item is registered and has the expected properties"]) + fun ensureItemContent(test: DynamicTest) { + test.onGameTest { helper -> + val stack = TestMod.instance().testitem.asStack() + helper.assertValueEqual("item.testmod.testitem", stack.item.descriptionId, "Test Item translation key") + helper.succeed() + } + } +} diff --git a/src/test/java/com/modularmc/registrate/test/gametests/LocalizationTests.kt b/src/test/java/com/modularmc/registrate/test/gametests/LocalizationTests.kt new file mode 100644 index 0000000..7e42a0f --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/gametests/LocalizationTests.kt @@ -0,0 +1,145 @@ +package com.modularmc.registrate.test.gametests + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.LocalizationDeclaration.Companion.sourceText +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.MinecraftLocale.EN_UD +import com.modularmc.registrate.localization.MinecraftLocale.EN_US +import com.modularmc.registrate.localization.MinecraftLocale.ZH_CN +import com.modularmc.registrate.localization.TextType +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.TranslationSource.Kind +import com.modularmc.registrate.localization.index.IndexedTranslations +import com.modularmc.registrate.localization.resolution.TranslationRegistry +import com.modularmc.registrate.localization.resolution.TranslationRegistry.LanguageFile +import com.modularmc.registrate.localization.terminology.Domain +import com.modularmc.registrate.providers.core.LanguageOutput +import com.modularmc.registrate.test.mod.TestMod +import com.modularmc.registrate.test.mod.localization.ChineseLocaleTestMod +import com.modularmc.registrate.test.mod.localization.EnglishLabels + +import net.minecraft.data.PackOutput +import net.minecraft.gametest.framework.GameTest +import net.neoforged.testframework.DynamicTest +import net.neoforged.testframework.annotation.ForEachTest +import net.neoforged.testframework.annotation.TestHolder +import net.neoforged.testframework.gametest.EmptyTemplate + +import java.nio.file.Path + +@ForEachTest(groups = ["registrate-localization"]) +object LocalizationTests { + private val inventory = TranslationKey(TestMod.MOD_ID, "gui.testmod.inventory") + private val builder = TranslationSource(Kind.DECLARED, "Builder testmod:inventory") + private val manual = TranslationSource(Kind.DECLARED, "Manual inventory label") + + @JvmStatic + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = ["Use explicit translations and preserve reordered Minecraft placeholders"]) + fun resolveDeclaredTextAndMinecraftPlaceholders(test: DynamicTest) { + test.onGameTest { helper -> + val registry = TranslationRegistry() + registry.add(inventory, EN_US, sourceText("Automatic Name"), TranslationSource(Kind.AUTOMATIC, "Default inventory label")) + registry.add(inventory, EN_US, sourceText("Other Automatic Name"), TranslationSource(Kind.AUTOMATIC, "Other default inventory label")) + val label = LocalizationDeclaration.Builder() + .source($$"%s at %2$s (%s%%)") + .translation(ZH_CN, $$"%2$s 上的 %1$s(%2$s%%)") + .build() + registry.add(inventory, EN_US, label, builder) + registry.add(inventory, EN_US, sourceText(label.source), manual) + + val languages = registry.resolve() + helper.assertValueEqual(label.source, languages.text(EN_US, inventory.value), "Declared source") + helper.assertValueEqual(label.translations.getValue(ZH_CN), languages.text(ZH_CN, inventory.value), "Reordered indexed arguments") + helper.assertTrue($$"%%%2$s" in languages.text(EN_UD, inventory.value), "Variant reverses the percent and argument tokens as units") + + val explicitVariant = $$"%1$s / %2$s / %2$s %%" + registry.add( + inventory, + EN_US, + LocalizationDeclaration.Builder().source(label.source).translation(EN_UD, explicitVariant).build(), + manual, + ) + helper.assertValueEqual(explicitVariant, registry.resolve().text(EN_UD, inventory.value), "Explicit variant takes priority") + + val mod = TestMod.instance() + val metadata = mod.testitem.metadata().localization()!!.declaration.get() + val catalog = mod.registrate().localizationCatalog() + helper.assertValueEqual(listOf(Domain.PHYSICS), metadata.domains, "Object-level domain overrides the profile") + helper.assertTrue(metadata.type == TextType.ITEM, "Text type from profile") + helper.assertValueEqual(catalog.glossary("electric_potential").orElseThrow(), metadata.glossary.first(), "Glossary from profile") + helper.assertValueEqual("V", catalog.unit("volt").orElseThrow().symbol, "Unit symbol") + helper.succeed() + } + } + + @JvmStatic + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = ["Report both conflicting declarations, mismatched placeholders and missing source locale"]) + fun locateInvalidLocalizationDeclarations(test: DynamicTest) { + test.onGameTest { helper -> + val conflict = TranslationRegistry() + conflict.add(inventory, EN_US, sourceText("First"), builder) + conflict.add(inventory, EN_US, sourceText("Second"), manual) + val conflictingDeclarations = failure(conflict::resolve) + helper.assertTrue(builder.location in conflictingDeclarations && manual.location in conflictingDeclarations, "Both conflicting sources") + + val wrongFormat = TranslationRegistry() + wrongFormat.add( + inventory, + EN_US, + LocalizationDeclaration.Builder().source("Inventory: %s").translation(ZH_CN, $$"物品栏:%2$s").build(), + manual, + ) + val mismatch = failure(wrongFormat::resolve) + helper.assertTrue("placeholder mismatch" in mismatch && manual.location in mismatch, "Translation that changed its source argument") + helper.assertTrue("[missing_locale]" in failure(UnconfiguredRegistrate()::requireSourceLocale), "Mod with missing source locale") + helper.succeed() + } + } + + @JvmStatic + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = ["Read Java and Kotlin indexes and fail before writing when a manual declaration conflicts with an annotation"]) + fun collectCompiledAnnotationsBeforeWriting(test: DynamicTest) { + test.onGameTest { helper -> + val registry = TranslationRegistry() + IndexedTranslations.collect(TestMod.MOD_ID, EN_US, registry) + IndexedTranslations.collect(ChineseLocaleTestMod.MOD_ID, ZH_CN, registry) + val languages = registry.resolve() + helper.assertValueEqual("Test", languages.text(EN_US, TestMod.CUSTOM_LANG), "Java annotation") + helper.assertValueEqual("Test Container", languages.text(EN_US, EnglishLabels.MENU_TITLE), "Kotlin field annotation") + helper.assertValueEqual("Low power", languages.text(EN_US, "gui.testmod.power.low"), "First variant") + helper.assertValueEqual("高功率", languages.text(ZH_CN, "gui.testmod.power.high"), "Second variant's target text") + helper.assertValueEqual($$"频率:%1$s Hz", languages.text(ZH_CN, "gui.localetest.frequency"), "Chinese source in shared namespace") + + registry.add(TranslationKey(TestMod.MOD_ID, EnglishLabels.MENU_TITLE), EN_US, sourceText("Conflicting name"), manual) + val diagnostic = failure { + LanguageOutput.write({ _, _, _ -> + throw AssertionError("Conflicting declarations caused a language write") + }, PackOutput(Path.of("unused-language-output")), registry) + } + helper.assertTrue("@Trans ${EnglishLabels::class.java.name}#MENU_TITLE" in diagnostic, "Annotated field in conflict diagnostic") + helper.assertTrue(manual.location in diagnostic, "Manual declaration in conflict diagnostic") + helper.succeed() + } + } + + private fun Map>.text(locale: MinecraftLocale, key: String): String = getValue(LanguageFile(TestMod.MOD_ID, locale)).getValue(key) + + private fun failure(operation: () -> Unit): String { + try { + operation() + } catch (error: IllegalArgumentException) { + return error.message!! + } + throw AssertionError("Localization operation should have failed") + } + + private class UnconfiguredRegistrate : AbstractRegistrate("missing_locale") +} diff --git a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java b/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java deleted file mode 100644 index 7481b16..0000000 --- a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.modularmc.registrate.test.gametests; - -import com.modularmc.registrate.test.mod.TestMod; - -import net.minecraft.gametest.framework.GameTest; -import net.neoforged.testframework.DynamicTest; -import net.neoforged.testframework.annotation.ForEachTest; -import net.neoforged.testframework.annotation.TestHolder; -import net.neoforged.testframework.gametest.EmptyTemplate; - -@ForEachTest(groups = "registrate-runtime") -@SuppressWarnings("unused") -public class RegistrationRuntimeTests { - - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = "Ensure block item lang reuse and fluid optional helpers behave as expected") - public static void ensureItemAndFluidHelpers(final DynamicTest test) { - test.onGameTest(helper -> helper.startSequence(() -> TestMod.instance().testblockitem.asStack().getItem().getDescriptionId()) - .thenExecute(blockItemDescriptionId -> { - helper.assertValueEqual(TestMod.instance().testblock.get().getDescriptionId(), blockItemDescriptionId, "Block item should reuse the block description key"); - helper.assertValueEqual(true, TestMod.instance().testfluid.getBlock().isEmpty(), "Fluid entry should return an empty block optional when no sibling exists"); - helper.assertValueEqual(true, TestMod.instance().testfluid.getBucket().isEmpty(), "Fluid entry should hide buckets when noBucket() is used"); - }) - .thenSucceed()); - } - - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = "Ensure auxiliary registrations remain available at runtime") - public static void ensureAuxiliaryRegistrations(final DynamicTest test) { - test.onGameTest(helper -> helper.startSequence(() -> TestMod.instance().testmenu.getId().getPath()) - .thenExecute(menuId -> { - helper.assertValueEqual("testmenu", menuId, "Menu registration path"); - helper.assertValueEqual("entity.testmod.testentity", TestMod.instance().testentity.get().getDescriptionId(), "Entity translation key"); - helper.assertValueEqual(TestMod.instance().testentity.get(), TestMod.instance().testentitySpawnEgg.get().getType(TestMod.instance().testentitySpawnEgg.asStack()), "Spawn egg should resolve to the registered entity type"); - helper.assertValueEqual("testitem", TestMod.instance().testduplicatename.getId().getPath(), "Duplicate-name entity registration path"); - helper.assertValueEqual("testblockentity", TestMod.instance().testblockentity.getId().getPath(), "Standalone block entity registration path"); - helper.assertValueEqual("testcustom", TestMod.instance().testcustom.getId().getPath(), "Custom registry entry path"); - helper.assertValueEqual("block.testmod.magic_item_model", TestMod.instance().magicItemModelTest.asStack().getItem().getDescriptionId(), "Magic item-model block description key"); - }) - .thenSucceed()); - } -} diff --git a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.kt b/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.kt new file mode 100644 index 0000000..bc7a968 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.kt @@ -0,0 +1,96 @@ +package com.modularmc.registrate.test.gametests + +import com.modularmc.registrate.providers.core.ProviderType +import com.modularmc.registrate.test.mod.TestMod + +import net.minecraft.core.registries.Registries +import net.minecraft.gametest.framework.GameTest +import net.minecraft.world.item.Item +import net.minecraft.world.level.block.Block +import net.neoforged.neoforge.fluids.FluidType +import net.neoforged.neoforge.registries.NeoForgeRegistries +import net.neoforged.testframework.DynamicTest +import net.neoforged.testframework.annotation.ForEachTest +import net.neoforged.testframework.annotation.TestHolder +import net.neoforged.testframework.gametest.EmptyTemplate + +@ForEachTest(groups = ["registrate-runtime"]) +object RegistrationRuntimeTests { + @JvmStatic + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = ["Ensure block item lang reuse and fluid optional helpers behave as expected"]) + fun ensureItemAndFluidHelpers(test: DynamicTest) { + test.onGameTest { helper -> + val mod = TestMod.instance() + helper.assertValueEqual( + mod.testblock.get().descriptionId, + mod.testblockitem.asStack().item.descriptionId, + "Block item should reuse the block description key", + ) + helper.assertTrue(mod.testfluid.getBlock().isEmpty, "No block entry for the test fluid") + helper.assertTrue(mod.testfluid.getBucket().isEmpty, "No bucket for noBucket()") + val supplierFluid = mod.kotlinEntries.supplierFluid + helper.assertTrue( + mod.registrate().get("test_supplier_fluid", NeoForgeRegistries.Keys.FLUID_TYPES).get() === supplierFluid.getType(), + "Fluid type supplied through the short overload is registered", + ) + helper.succeed() + } + } + + @JvmStatic + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = ["Ensure Java and Kotlin registrations share the test mod's Registrate instance"]) + fun ensureAuxiliaryRegistrations(test: DynamicTest) { + test.onGameTest { helper -> + val mod = TestMod.instance() + val kotlinEntries = mod.kotlinEntries + helper.assertValueEqual("testmenu", mod.testmenu.id.path, "Menu registration path") + helper.assertValueEqual("entity.testmod.testentity", mod.testentity.get().descriptionId, "Entity translation key") + helper.assertValueEqual( + mod.testentity.get(), + mod.testentitySpawnEgg.get().getType(mod.testentitySpawnEgg.asStack()), + "Spawn egg should resolve to the registered entity type", + ) + helper.assertValueEqual("testitem", mod.testduplicatename.id.path, "Duplicate-name entity registration path") + helper.assertValueEqual("testblockentity", kotlinEntries.standaloneBlockEntity.id.path, "Standalone block entity registration path") + helper.assertValueEqual("testcustom", mod.testcustom.id.path, "Custom registry entry path") + helper.assertValueEqual( + "block.testmod.magic_item_model", + kotlinEntries.magicItemModelTest.asStack().item.descriptionId, + "Magic item-model block description key", + ) + helper.assertTrue( + mod.registrate().get("magic_item_model", Registries.BLOCK) === kotlinEntries.magicItemModelTest, + "Kotlin block accessible through the Java entry point's Registrate", + ) + helper.succeed() + } + } + + @JvmStatic + @GameTest + @EmptyTemplate(floor = true) + @TestHolder(description = ["Reject duplicate registrations before replacing the original holder and its declarations"]) + fun rejectDuplicateItemWithoutReplacingMetadata(test: DynamicTest) { + test.onGameTest { helper -> + val mod = TestMod.instance() + val metadata = mod.testitem.metadata() + try { + mod.registrate().item("testitem", ::Item).lang("Duplicate").register() + throw AssertionError("Duplicate registration succeeded") + } catch (error: IllegalArgumentException) { + val message = error.message!! + helper.assertTrue("testmod:testitem" in message && "minecraft:item" in message, "Duplicate diagnostic: $message") + } + + helper.assertTrue(mod.registrate().get("testitem", Registries.ITEM) === mod.testitem, "Original holder") + helper.assertTrue(mod.testitem.metadata() === metadata, "Original entry metadata") + helper.assertTrue(metadata.dataGenerators().any { it.type === ProviderType.ITEM_MODEL }, "Item model declaration") + helper.assertTrue(mod.testcustom.metadata().dataGenerators().isEmpty(), "Custom registry metadata") + helper.succeed() + } + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java b/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java deleted file mode 100644 index 8d73b9b..0000000 --- a/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.modularmc.registrate.test.meta; - -import com.modularmc.registrate.test.meta.ProtectedMethodScraper.Header; - -import com.google.common.collect.ImmutableList; -import lombok.RequiredArgsConstructor; -import lombok.Value; -import org.apache.commons.lang3.tuple.Pair; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -@RequiredArgsConstructor -public class MethodGenerator { - - @Value - private class Exclusion { - - String name; - String[] params; - - public boolean matches(Header header) { - if (!header.getName().equals(this.name)) { - return false; - } - return this.params == null ? true : Arrays.equals(header.getParamTypes(), this.params); - } - } - - private static final String START_KEY = "// GENERATED START"; - private static final String END_KEY = "// GENERATED END"; - - private final List> typeReplacements; - private final Set excludes = new HashSet<>(); - - private final Class mainClass; - - public MethodGenerator(Class mainClass) { - this(ImmutableList.of(), mainClass); - } - - public MethodGenerator exclude(String name) { - excludes.add(new Exclusion(name, null)); - return this; - } - - public MethodGenerator exclude(String name, String... paramTypes) { - excludes.add(new Exclusion(name, paramTypes)); - return this; - } - - public void generate(Path output) throws IOException { - List currentSource = Files.readAllLines(output, StandardCharsets.UTF_8); - List
newHeaders = ProtectedMethodScraper.scrapeInput(); - ListIterator
headerItr = newHeaders.listIterator(); - while (headerItr.hasNext()) { - Header header = headerItr.next(); - for (Pair repl : typeReplacements) { - header = header.applyTypeReplacement(repl); - } - headerItr.set(header); - } - ListIterator itr = currentSource.listIterator(); - while (itr.hasNext()) { - int index = itr.nextIndex(); - String line = itr.next(); - if (line.contains(START_KEY)) { - itr.remove(); - while (itr.hasNext()) { - if (!itr.next().contains(END_KEY)) { - itr.remove(); - } else { - itr.remove(); - itr = currentSource.listIterator(index); - break; - } - } - itr.add(line); - for (Header header : newHeaders) { - if (excludes.stream().anyMatch(e -> e.matches(header))) continue; - itr.add(""); - for (String s : header.printStubMethod(mainClass).split("\n")) { - itr.add(" " + s); - } - } - itr.add(""); - itr.add(" " + END_KEY); - break; - } - } - Files.write(output, currentSource); - System.out.print("Updated source code: " + Paths.get("src/main/java").relativize(output).toString().replace(File.separator, ".").replace(".java", "")); - } -} diff --git a/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.kt b/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.kt new file mode 100644 index 0000000..f251103 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.kt @@ -0,0 +1,122 @@ +package com.modularmc.registrate.test.meta + +import com.modularmc.registrate.test.meta.ProtectedMethodScraper.isNullable +import com.modularmc.registrate.test.meta.ProtectedMethodScraper.kotlinType + +import com.sun.source.tree.AnnotatedTypeTree +import com.sun.source.tree.ArrayTypeTree +import com.sun.source.tree.IdentifierTree +import com.sun.source.tree.MethodTree +import com.sun.source.util.TreeScanner + +import java.nio.file.Files +import java.nio.file.Path +import javax.lang.model.element.Modifier + +/** Updates the public overrides and companion methods in a Kotlin DataGen provider. */ +internal class MethodGenerator(private val owner: String, private val updater: Class<*>) { + private data class Exclusion(val name: String, val parameterTypes: List?) + + private enum class Section { + OVERRIDE, + STATIC, + } + + private val exclusions = HashSet() + + fun exclude(name: String, vararg parameterTypes: String) = apply { + exclusions.add(Exclusion(name, parameterTypes.asList().ifEmpty { null })) + } + + fun generate(output: Path) { + val source = Files.readAllLines(output) + val declarations = ProtectedMethodScraper.scrapeInput(owner) + val methods = declarations.methods.filterNot { method -> + val methodName = method.name.toString() + Exclusion(methodName, null) in exclusions || + Exclusion(methodName, method.parameters.map { it.type.toString() }) in exclusions + } + val (staticMethods, overrides) = methods.partition { Modifier.STATIC in it.modifiers.flags } + replaceMethods(source, Section.OVERRIDE, overrides) + replaceMethods(source, Section.STATIC, staticMethods) + addImports(source, declarations.imports, methods) + Files.write(output, source) + println("Updated $output with ${methods.size} methods") + } + + private fun addImports(source: MutableList, imports: List, methods: List) { + val types = HashSet() + val scanTypes = object : TreeScanner() { + override fun visitIdentifier(node: IdentifierTree, data: Unit) { + types.add(kotlinType(node)) + } + + override fun visitAnnotatedType(node: AnnotatedTypeTree, data: Unit) { + scan(node.underlyingType, data) + } + } + for (method in methods) { + scanTypes.scan(method.returnType, Unit) + for (parameter in method.parameters) scanTypes.scan(parameter.type, Unit) + for (parameter in method.typeParameters) scanTypes.scan(parameter.bounds, Unit) + } + val existing = source.filterTo(HashSet()) { it.startsWith("import ") } + val needed = imports.filter { it.substringAfterLast('.') in types }.map { "import $it" }.filterNot(existing::contains) + source.addAll(source.indexOfLast { it.startsWith("import ") } + 1, needed) + } + + private fun replaceMethods(source: MutableList, region: Section, methods: List) { + val start = source.indexOfFirst { it.trim() == "// GENERATED $region START" } + val end = source.indexOfFirst { it.trim() == "// GENERATED $region END" } + val indent = source[start].takeWhile(Char::isWhitespace) + val lines = source.subList(start + 1, end) + lines.clear() + for (method in methods) { + lines.add("") + lines.addAll(stub(method, region).lineSequence().map { indent + it }) + } + lines.add("") + } + + private fun stub(method: MethodTree, section: Section): String = buildString { + val isStatic = section == Section.STATIC + val receiver = if (isStatic) owner else "super" + val name = method.name.toString() + appendLine("/** Exposes [$owner.$name]. */") + appendLine("@Generated(value = [\"${updater.name}\"])") + if (isStatic) appendLine("@JvmStatic") + append(if (isStatic) "fun " else "public override fun ") + val typeParameters = method.typeParameters + if (typeParameters.isNotEmpty()) { + append(typeParameters.joinToString(", ", "<", "> ") { it.name.toString() }) + } + append(name) + val arguments = ArrayList(method.parameters.size) + append( + method.parameters.joinToString(", ", "(", ")") { parameter -> + val paramName = parameter.name.toString() + val vararg = parameter.toString().substringBeforeLast(' ').endsWith("...") + arguments.add(if (vararg) "*$paramName" else paramName) + val type = if (vararg) (parameter.type as ArrayTypeTree).type else parameter.type + val renderedType = kotlinType(type) + val nullable = parameter.modifiers.annotations.any { isNullable(it.annotationType) } + val prefix = if (vararg) "vararg " else "" + val suffix = if (nullable && !renderedType.endsWith('?')) "?" else "" + "$prefix$paramName: $renderedType$suffix" + }, + ) + val returnType = kotlinType(method.returnType) + if (returnType != "Unit") { + val nullable = method.modifiers.annotations.any { isNullable(it.annotationType) } + append(": ").append(returnType) + if (nullable && !returnType.endsWith("?")) append('?') + } + val bounds = typeParameters.flatMap { parameter -> + parameter.bounds.map { "${parameter.name} : ${kotlinType(it)}" } + } + if (bounds.isNotEmpty()) append(bounds.joinToString(", ", " where ")) + append(" = ").append(receiver).append('.').append(name) + if (typeParameters.isNotEmpty()) append(typeParameters.joinToString(", ", "<", ">") { it.name.toString() }) + append(arguments.joinToString(", ", "(", ")")) + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java b/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java deleted file mode 100644 index 739833a..0000000 --- a/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.modularmc.registrate.test.meta; - -import lombok.AccessLevel; -import lombok.RequiredArgsConstructor; -import lombok.Value; -import org.apache.commons.lang3.tuple.Pair; - -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.Scanner; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -/** - * Scrapes all protected methods from pasted source, and emits them as public super-calling stubs. Used to create the - * bouncer classes such as BuilderModelProvider. - */ -public class ProtectedMethodScraper { - - @Value - @RequiredArgsConstructor(access = AccessLevel.PRIVATE) - public static class Header { - - String className; - boolean isStatic; - String generics; - String type; - String name; - String[] paramTypes; - String[] paramNames; - - public Header applyTypeReplacement(Pair repl) { - String[] newParamTypes = Arrays.copyOf(paramTypes, paramTypes.length); - for (int i = 0; i < newParamTypes.length; i++) { - if (newParamTypes[i].equals(repl.getKey())) { - newParamTypes[i] = repl.getValue(); - } - } - String type = this.type.equals(repl.getKey()) ? repl.getValue() : this.type; - return new Header(this.className, this.isStatic, this.generics, type, this.name, newParamTypes, this.paramNames); - } - - public String printStubMethod(Class source) { - StringBuilder base = new StringBuilder(); - base.append("/** Generated override to expose protected method: {@link ").append(className).append("#").append(name).append("} */\n"); - if (!isStatic) { - base.append("@Override\n"); - } - base.append("@Generated(value = \"").append(source.getName()).append("\", date = \"") - .append(DateTimeFormatter.RFC_1123_DATE_TIME.format(Instant.now().atZone(ZoneOffset.UTC))).append("\")\n"); - base.append("public ").append(isStatic ? "static " : ""); - if (generics != null) { - base.append(generics).append(" "); - } - base.append(type).append(" ").append(name).append("("); - for (int i = 0; i < paramTypes.length; i++) { - if (i > 0) { - base.append(", "); - } - base.append(paramTypes[i]).append(" ").append(paramNames[i]); - } - base.append(") { ").append(type.equals("void") ? "" : "return "); - if (isStatic) { - base.append(className).append("."); - } else { - base.append("super."); - } - base.append(name).append("(").append(Arrays.stream(paramNames).collect(Collectors.joining(", "))).append("); }"); - return base.toString(); - } - - // Match generics up to three levels deep -- java does not support recursive patterns - private static final Pattern HEADER_PATTERN = Pattern.compile("^\\s*protected\\s+(?:(static)\\s)?\\s*(<[^<>]+(?:<[^<>]+(?:<[^<>]+>[^<>]*)*>[^<>]*)*>)?\\s*(\\S+)\\s+(\\S+)\\((.+)\\)\\s\\{$"); - private static final Pattern PARAM_PATTERN = Pattern.compile("([a-zA-Z_][\\w.$]+(?:<.+>)?)\\s+(\\S+)"); - - public static Optional
parse(String className, String code) { - Matcher h = HEADER_PATTERN.matcher(code); - if (h.matches()) { - boolean isStatic = h.group(1) != null; - String generics = h.group(2); - String type = h.group(3); - String name = h.group(4); - String params = h.group(5); - String[] paramList = params.split(","); - String[] paramTypes = new String[paramList.length]; - String[] paramNames = new String[paramList.length]; - for (int i = 0; i < paramList.length; i++) { - String param = paramList[i].trim(); - Matcher p = PARAM_PATTERN.matcher(param); - if (p.matches()) { - paramTypes[i] = p.group(1); - paramNames[i] = p.group(2); - } else { - return Optional.empty(); - } - } - return Optional.of(new Header(className, isStatic, generics, type, name, paramTypes, paramNames)); - } - return Optional.empty(); - } - } - - public static List
scrapeInput() { - @SuppressWarnings("resource") - Scanner scanner = new Scanner(System.in); - System.out.println("Paste class source:"); - String line = scanner.nextLine(); - List
headers = new ArrayList<>(); - String className = null; - do { - if (className != null) { - Header.parse(className, line).ifPresent(headers::add); - } else if (line.startsWith("public class ") || line.startsWith("public abstract class")) { - className = line.replaceAll("public (abstract )?class ", "").split("\\s+")[0]; - } - line = scanner.nextLine(); - } while (!"done".equals(line) && !"}".equals(line)); - System.out.println("Text processed! Found " + headers.size() + " methods to generate."); - return headers; - } -} diff --git a/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.kt b/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.kt new file mode 100644 index 0000000..65096e8 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.kt @@ -0,0 +1,89 @@ +package com.modularmc.registrate.test.meta + +import com.sun.source.tree.AnnotatedTypeTree +import com.sun.source.tree.ArrayTypeTree +import com.sun.source.tree.ClassTree +import com.sun.source.tree.MethodTree +import com.sun.source.tree.ParameterizedTypeTree +import com.sun.source.tree.PrimitiveTypeTree +import com.sun.source.tree.Tree +import com.sun.source.tree.WildcardTree +import com.sun.source.util.JavacTask + +import java.net.URI +import javax.lang.model.element.Modifier +import javax.tools.Diagnostic +import javax.tools.JavaFileObject +import javax.tools.SimpleJavaFileObject +import javax.tools.ToolProvider + +/** Reads protected method signatures from a pasted Java class using the JDK parser. */ +internal object ProtectedMethodScraper { + data class Declarations(val imports: List, val methods: List) + + fun scrapeInput(owner: String): Declarations { + println("Paste the $owner Java source, followed by 'done' or EOF:") + val source = buildString { + while (true) { + val line = readlnOrNull() ?: break + if (line == "done") break + appendLine(line) + if (line == "}") break + } + } + val file = object : SimpleJavaFileObject(URI.create("string:///$owner.java"), JavaFileObject.Kind.SOURCE) { + override fun getCharContent(ignoreEncodingErrors: Boolean): String = source + } + val task = ToolProvider.getSystemJavaCompiler().getTask(null, null, { diagnostic -> + if (diagnostic.kind == Diagnostic.Kind.ERROR) error(diagnostic.toString()) + }, listOf("-proc:none"), null, listOf(file)) as JavacTask + val sourceFile = task.parse().single() + val imports = sourceFile.imports.filterNot { it.isStatic }.map { it.qualifiedIdentifier.toString() } + val parent = sourceFile.typeDecls.filterIsInstance().single { it.simpleName.contentEquals(owner) } + val methods = parent.members.filterIsInstance().filter { + val flags = it.modifiers.flags + it.returnType != null && Modifier.PROTECTED in flags && Modifier.FINAL !in flags && Modifier.ABSTRACT !in flags + } + return Declarations(imports, methods) + } + + private val typeNames = mapOf( + "void" to "Unit", + "boolean" to "Boolean", + "byte" to "Byte", + "char" to "Char", + "short" to "Short", + "int" to "Int", + "long" to "Long", + "float" to "Float", + "double" to "Double", + "Object" to "Any", + "Integer" to "Int", + "Character" to "Char", + "List" to "MutableList", + "Set" to "MutableSet", + "Map" to "MutableMap", + "Collection" to "MutableCollection", + ) + + fun kotlinType(type: Tree): String = when (type) { + is ParameterizedTypeTree -> type.typeArguments.joinToString(", ", "${kotlinType(type.type)}<", ">") { kotlinType(it) } + + is ArrayTypeTree -> { + val element = kotlinType(type.type) + if (type.type is PrimitiveTypeTree) "${element}Array" else "Array<$element>" + } + + is WildcardTree -> when (type.kind) { + Tree.Kind.EXTENDS_WILDCARD -> "out ${kotlinType(type.bound)}" + Tree.Kind.SUPER_WILDCARD -> "in ${kotlinType(type.bound)}" + else -> "*" + } + + is AnnotatedTypeTree -> kotlinType(type.underlyingType) + if (type.annotations.any { isNullable(it.annotationType) }) "?" else "" + + else -> type.toString().let { typeNames[it] ?: it } + } + + fun isNullable(annotationType: Tree): Boolean = annotationType.toString().substringAfterLast('.') == "Nullable" +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java b/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java deleted file mode 100644 index 83e9cdf..0000000 --- a/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.modularmc.registrate.test.meta; - -import java.io.IOException; -import java.nio.file.Paths; - -public class UpdateBlockLootTables { - - public static void main(String[] args) throws IOException { - new MethodGenerator(UpdateBlockLootTables.class) - .generate(Paths.get("src", "main", "java", "com", "tterrag", "registrate", "providers", "loot", "RegistrateBlockLootTables.java")); - } -} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.kt b/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.kt new file mode 100644 index 0000000..8cc136f --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.kt @@ -0,0 +1,13 @@ +package com.modularmc.registrate.test.meta + +import java.nio.file.Path + +object UpdateBlockLootTables { + @JvmStatic + fun main(args: Array) { + MethodGenerator("BlockLootSubProvider", UpdateBlockLootTables::class.java) + .exclude("generate") + .exclude("getKnownBlocks") + .generate(Path.of("src/main/java/com/modularmc/registrate/providers/loot/RegistrateBlockLootTables.kt")) + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java b/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java deleted file mode 100644 index b441f03..0000000 --- a/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.modularmc.registrate.test.meta; - -import java.io.IOException; -import java.nio.file.Paths; - -public class UpdateEntityLootTables { - - public static void main(String[] args) throws IOException { - new MethodGenerator(UpdateEntityLootTables.class) - .exclude("isNonLiving").exclude("getKnownEntities") - .generate(Paths.get("src", "main", "java", "com", "tterrag", "registrate", "providers", "loot", "RegistrateEntityLootTables.java")); - } -} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.kt b/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.kt new file mode 100644 index 0000000..ff785ee --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.kt @@ -0,0 +1,14 @@ +package com.modularmc.registrate.test.meta + +import java.nio.file.Path + +object UpdateEntityLootTables { + @JvmStatic + fun main(args: Array) { + MethodGenerator("EntityLootSubProvider", UpdateEntityLootTables::class.java) + .exclude("generate") + .exclude("isNonLiving") + .exclude("getKnownEntityTypes") + .generate(Path.of("src/main/java/com/modularmc/registrate/providers/loot/RegistrateEntityLootTables.kt")) + } +} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java b/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java deleted file mode 100644 index 105799f..0000000 --- a/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.modularmc.registrate.test.meta; - -import java.io.IOException; -import java.nio.file.Paths; - -public class UpdateRecipeProvider { - - public static void main(String[] args) throws IOException { - new MethodGenerator(UpdateRecipeProvider.class) - .exclude("buildCraftingRecipes") - .generate(Paths.get("src", "main", "java", "com", "tterrag", "registrate", "providers", "generators", "RegistrateRecipeProvider.java")); - } -} diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.kt b/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.kt new file mode 100644 index 0000000..23b8614 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.kt @@ -0,0 +1,12 @@ +package com.modularmc.registrate.test.meta + +import java.nio.file.Path + +object UpdateRecipeProvider { + @JvmStatic + fun main(args: Array) { + MethodGenerator("RecipeProvider", UpdateRecipeProvider::class.java) + .exclude("buildRecipes", "RecipeOutput") + .generate(Path.of("src/main/java/com/modularmc/registrate/providers/generators/RegistrateRecipeProvider.kt")) + } +} diff --git a/src/test/java/com/modularmc/registrate/test/mod/KotlinRegistrations.kt b/src/test/java/com/modularmc/registrate/test/mod/KotlinRegistrations.kt new file mode 100644 index 0000000..71fb4da --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/mod/KotlinRegistrations.kt @@ -0,0 +1,37 @@ +package com.modularmc.registrate.test.mod + +import com.modularmc.registrate.Registrate +import com.modularmc.registrate.util.nullness.NonNullBiConsumer +import com.modularmc.registrate.util.nullness.NonNullSupplier + +import net.minecraft.core.BlockPos +import net.minecraft.world.level.block.Block +import net.minecraft.world.level.block.Blocks +import net.minecraft.world.level.block.entity.BlockEntity +import net.minecraft.world.level.block.entity.BlockEntityType +import net.minecraft.world.level.block.state.BlockState +import net.neoforged.neoforge.fluids.FluidType + +/** Kotlin registration examples using the test mod's Registrate instance. */ +class KotlinRegistrations(registrate: Registrate) { + val magicItemModelTest = registrate.block("magic_item_model", ::Block) + .blockstate { + NonNullBiConsumer { context, models -> + val model = models.models().cubeAll("block/subfolder/" + context.name, models.mcBlockTexture("gold_block")) + models.create(context.entry, model.location) + } + } + .simpleItem() + .register() + + val standaloneBlockEntity = registrate.blockEntity("testblockentity", ::TestDummyBlockEntity) + .validBlock { Blocks.DIRT } + .register() + + val supplierFluid = registrate.fluid("test_supplier_fluid", NonNullSupplier { FluidType(FluidType.Properties.create()) }) + .noBlock() + .noBucket() + .register() + + class TestDummyBlockEntity(type: BlockEntityType, pos: BlockPos, state: BlockState) : BlockEntity(type, pos, state) +} diff --git a/src/test/java/com/modularmc/registrate/test/mod/TestMod.java b/src/test/java/com/modularmc/registrate/test/mod/TestMod.java index 3cb66e8..0ef0e67 100644 --- a/src/test/java/com/modularmc/registrate/test/mod/TestMod.java +++ b/src/test/java/com/modularmc/registrate/test/mod/TestMod.java @@ -2,7 +2,17 @@ import com.modularmc.registrate.Registrate; import com.modularmc.registrate.builders.BlockBuilder; +import com.modularmc.registrate.localization.LocalizationProfile; +import com.modularmc.registrate.localization.MinecraftLocale; +import com.modularmc.registrate.localization.TextType; +import com.modularmc.registrate.localization.TranslationKey; +import com.modularmc.registrate.localization.annotation.Trans; +import com.modularmc.registrate.localization.terminology.Domain; +import com.modularmc.registrate.localization.terminology.LocalizationCatalog.GlossaryTerm; +import com.modularmc.registrate.localization.terminology.LocalizationCatalog.Unit; import com.modularmc.registrate.providers.core.ProviderType; +import com.modularmc.registrate.providers.generators.RegistrateRecipeProvider; +import com.modularmc.registrate.test.mod.localization.EnglishLabels; import com.modularmc.registrate.util.DataIngredient; import com.modularmc.registrate.util.entry.*; @@ -92,18 +102,23 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import org.lwjgl.glfw.GLFW; -import java.util.Objects; +import java.util.List; +import java.util.Map; import java.util.OptionalLong; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import javax.annotation.Nullable; - @Mod(TestMod.MOD_ID) public class TestMod { public static final String MOD_ID = "testmod"; + @Trans(modId = MOD_ID, key = TestMod.CUSTOM_LANG, source = "Test") + public static final String CUSTOM_LANG = "testmod.custom.lang"; + + private static final GlossaryTerm POTENTIAL = new GlossaryTerm("electric_potential", "electric potential", List.of(Domain.PHYSICS), Map.of(MinecraftLocale.ZH_CN, "电势")); + private static final LocalizationProfile TECHNOLOGY = new LocalizationProfile(List.of(Domain.ENGINEERING), TextType.ITEM, List.of(POTENTIAL)); + public static final class TestBlock extends Block implements EntityBlock { public TestBlock(Properties properties) { @@ -128,7 +143,7 @@ public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player play @Override public Component getDisplayName() { - return Component.literal("Test"); + return Component.translatable(EnglishLabels.MENU_TITLE); } }); } @@ -166,13 +181,6 @@ public void render(TestBlockEntity blockEntity, float partialTicks, PoseStack po } } - public static final class TestDummyBlockEntity extends BlockEntity { - - public TestDummyBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { - super(type, pos, state); - } - } - public static final class TestEntity extends Pig { public TestEntity(EntityType p_i50250_1_, Level p_i50250_2_) { @@ -182,7 +190,7 @@ public TestEntity(EntityType p_i50250_1_, Level p_i50250_2_) { public static final class TestCustomRegistryEntry {} - private final Registrate registrate = Registrate.create("testmod"); + private final Registrate registrate = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); @VisibleForTesting public final RegistryEntry testcreativetab = registrate.object("test_creative_mode_tab") @@ -194,7 +202,8 @@ public static final class TestCustomRegistryEntry {} @VisibleForTesting public final ItemEntry testitem = registrate.object("testitem") .item(Item::new) - .onRegister(ignored -> sawCallback.set(true)) + .localization(text -> text.profile(TECHNOLOGY).domain(Domain.PHYSICS).source("Testitem").translation(MinecraftLocale.ZH_CN, "测试物品")) + .onRegister(item -> sawCallback.set(registrate.get("testitem", Registries.ITEM).get() == item)) .properties(p -> p.food(new FoodProperties.Builder().nutrition(1).saturationModifier(0.2f).build())) .tag(ItemTags.BEDS) .model(() -> (ctx, prov) -> prov.createWithExistingModel(ctx.getEntry(), prov.mcLoc("block/stone"))) @@ -220,7 +229,7 @@ public static final class TestCustomRegistryEntry {} .pattern("DDD").pattern("DED").pattern("DDD") .define('D', Items.DIAMOND) .define('E', Items.EGG) - .unlockedBy("has_egg", prov.has(Items.EGG)) + .unlockedBy("has_egg", RegistrateRecipeProvider.has(Items.EGG)) .save(prov); prov.food(DataIngredient.items(ctx), RecipeCategory.MISC, () -> Blocks.DIAMOND_BLOCK, 1f); @@ -238,16 +247,10 @@ public static final class TestCustomRegistryEntry {} .register(); @VisibleForTesting - public final BlockEntry magicItemModelTest = registrate.object("magic_item_model") - .block(Block::new) - .blockstate(() -> (ctx, prov) -> prov.create( - ctx.getEntry(), - prov.models().cubeAll("block/subfolder/" + ctx.getName(), prov.mcBlockTexture("gold_block")).getLocation())) - .simpleItem() - .register(); + public final KotlinRegistrations kotlinEntries = new KotlinRegistrations(registrate); @VisibleForTesting - public final ItemEntry testblockitem = (ItemEntry) testblock.getSibling(Registries.ITEM); + public final ItemEntry testblockitem = ItemEntry.cast(testblock.getSibling(Registries.ITEM)); @VisibleForTesting public final BlockEntityEntry testblockbe = BlockEntityEntry.cast(testblock.getSibling(Registries.BLOCK_ENTITY_TYPE)); @@ -269,12 +272,6 @@ public static final class TestCustomRegistryEntry {} @VisibleForTesting public final ItemEntry testentitySpawnEgg = ItemEntry.cast(registrate.get("testentity_spawn_egg", Registries.ITEM)); - @VisibleForTesting - public final BlockEntityEntry testblockentity = registrate.object("testblockentity") - .blockEntity(TestDummyBlockEntity::new) - .validBlock(() -> Blocks.DIRT) - .register(); - @VisibleForTesting public final FluidEntry testfluid = registrate.object("testfluid") .fluid( @@ -309,24 +306,33 @@ private static BlockBuilder applyDiamondDrop(BlockBui return builder.loot((prov, block) -> prov.dropOther(block, Items.DIAMOND)); } - private static @Nullable TestMod INSTANCE = null; + private static TestMod INSTANCE; public TestMod(IEventBus eventBus, ModContainer container) { INSTANCE = this; - registrate.addRawLang("testmod.custom.lang", "Test"); + var catalog = registrate.localizationCatalog(); + catalog.register(Domain.PHYSICS); + catalog.register(POTENTIAL); + catalog.register(new Unit("volt", "V", Map.of(MinecraftLocale.EN_US, "volt", MinecraftLocale.ZH_CN, "伏特"))); + registrate.addLocalization(new TranslationKey(MOD_ID, "gui.testmod.voltage"), + text -> text.profile(TECHNOLOGY).type(TextType.GUI_LABEL) + .source("Voltage: %s V").translation(MinecraftLocale.ZH_CN, "电压:%1$s V")); registrate.addRawLang("testmod.custom.lang.with_placeholders1", "Placeholder 1 %s Placeholder 2 %s"); registrate.addRawLang("testmod.custom.lang.with_placeholders2", "Placeholder 1 %s Placeholder 2 %2$s Placeholder 3 %s"); registrate.addRawLang("testmod.custom.lang.brackets", "(Bracket 1) [Bracket 2] {Bracket 3} ◁Bracket 5▷"); registrate.addRawLang("testmod.custom.lang.slashes", "/commmands look good and here is a backslash \\"); registrate.addLang("tooltip", testblock.getId(), "Egg."); registrate.addLang("item", testitem.getId(), "testextra", "Magic!"); + var rootAdvancement = ResourceLocation.fromNamespaceAndPath(MOD_ID, "root"); + var advancementTitle = registrate.addLang("advancements", rootAdvancement, "title", "Test Advancement"); + var advancementDescription = registrate.addLang("advancements", rootAdvancement, "description", "Get an egg."); registrate.addDataGenerator(ProviderType.ADVANCEMENT, adv -> Advancement.Builder.advancement() .addCriterion("has_egg", InventoryChangeTrigger.TriggerInstance.hasItems(Items.EGG)) .display(Items.EGG, - adv.title(registrate.getModid(), "root", "Test Advancement"), adv.desc(registrate.getModid(), "root", "Get an egg."), + advancementTitle, advancementDescription, ResourceLocation.withDefaultNamespace("textures/gui/advancements/backgrounds/stone.png"), AdvancementType.TASK, true, true, false) - .save(adv, registrate.getModid() + ":root")); + .save(adv, rootAdvancement.toString())); registrate.addDataGenerator(ProviderType.GENERIC_SERVER, provider -> provider.add(data -> { // generic server side provider to generate custom dimension // to teleport to this dimension use the following command @@ -404,7 +410,11 @@ private void onCommonSetup(FMLCommonSetupEvent event) { } public static TestMod instance() { - Objects.requireNonNull(INSTANCE, "Attempting to get mod instance before mod construction"); return INSTANCE; } + + @VisibleForTesting + public Registrate registrate() { + return registrate; + } } diff --git a/src/test/java/com/modularmc/registrate/test/mod/localization/ChineseLocaleTestMod.kt b/src/test/java/com/modularmc/registrate/test/mod/localization/ChineseLocaleTestMod.kt new file mode 100644 index 0000000..85480b7 --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/mod/localization/ChineseLocaleTestMod.kt @@ -0,0 +1,37 @@ +package com.modularmc.registrate.test.mod.localization + +import com.modularmc.registrate.Registrate +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.annotation.Trans +import com.modularmc.registrate.localization.annotation.Translation +import com.modularmc.registrate.test.mod.TestMod +import com.modularmc.registrate.util.nullness.NonNullBiConsumer + +import net.minecraft.world.item.Item +import net.neoforged.fml.common.Mod + +@Mod(ChineseLocaleTestMod.MOD_ID) +@Trans( + modId = ChineseLocaleTestMod.MOD_ID, + namespace = TestMod.MOD_ID, + key = "gui.localetest.frequency", + source = $$"频率:%1$s Hz", + translations = [Translation(MinecraftLocale.EN_US, "Frequency: %s Hz")], +) +class ChineseLocaleTestMod { + init { + Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.ZH_CN) + .item("celestial_dust", ::Item) + .localization { it.source("星尘").translation(MinecraftLocale.EN_US, "Celestial Dust") } + .model { + NonNullBiConsumer { context, generator -> + generator.createWithExistingModel(context.entry, generator.mcLoc("item/glowstone_dust")) + } + } + .register() + } + + companion object { + const val MOD_ID = "localetest" + } +} diff --git a/src/test/java/com/modularmc/registrate/test/mod/localization/EnglishLabels.kt b/src/test/java/com/modularmc/registrate/test/mod/localization/EnglishLabels.kt new file mode 100644 index 0000000..c33e3de --- /dev/null +++ b/src/test/java/com/modularmc/registrate/test/mod/localization/EnglishLabels.kt @@ -0,0 +1,26 @@ +package com.modularmc.registrate.test.mod.localization + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.annotation.Trans +import com.modularmc.registrate.localization.annotation.TransVariants +import com.modularmc.registrate.localization.annotation.Translation +import com.modularmc.registrate.localization.annotation.Variant +import com.modularmc.registrate.test.mod.TestMod + +@TransVariants( + modId = TestMod.MOD_ID, + keyPrefix = "gui.testmod.power.", + value = [ + Variant(id = "low", source = "Low power", translations = [Translation(MinecraftLocale.ZH_CN, "低功率")]), + Variant(id = "high", source = "High power", translations = [Translation(MinecraftLocale.ZH_CN, "高功率")]), + ], +) +object EnglishLabels { + @field:Trans( + modId = TestMod.MOD_ID, + key = "gui.testmod.container", + source = "Test Container", + translations = [Translation(MinecraftLocale.ZH_CN, "测试容器")], + ) + const val MENU_TITLE = "gui.testmod.container" +} diff --git a/src/test/resources/META-INF/neoforge.mods.toml b/src/test/resources/META-INF/neoforge.mods.toml index ea4e5ea..c3298e0 100644 --- a/src/test/resources/META-INF/neoforge.mods.toml +++ b/src/test/resources/META-INF/neoforge.mods.toml @@ -43,3 +43,16 @@ type="required" versionRange="[2.0.0,)" ordering="AFTER" side="BOTH" + +[[mods]] +modId="localetest" +version="${file.jarVersion}" +displayName="Localization Test Mod" +description="Exercises a second source locale in Registrate DataGen." + +[[dependencies.localetest]] +modId="registratelib" +type="required" +versionRange="[2.0.0,)" +ordering="AFTER" +side="BOTH" From 5c1e989c45ffe393074e0fe6c427adf556d74ef7 Mon Sep 17 00:00:00 2001 From: QiuYe Date: Sat, 21 Nov 2026 15:31:42 +0800 Subject: [PATCH 7/7] =?UTF-8?q?=E4=BB=8E=20Maven=20Central=20=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=20KSP=20=E6=8F=92=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- settings.gradle | 3 +++ 1 file changed, 3 insertions(+) diff --git a/settings.gradle b/settings.gradle index 89aae22..2e5a23a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,6 +1,9 @@ pluginManagement { repositories { mavenLocal() + mavenCentral { + content { includeGroup("com.google.devtools.ksp") } + } gradlePluginPortal() maven { url = 'https://maven.neoforged.net/releases' } maven { url = "https://maven.quiltmc.org/repository/release" }