diff --git a/README.md b/README.md index 629d4dd..4c53262 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,30 @@ that don't want to install mods on the client. This mod was heavily inspired by [Aurora's Decorations](https://modrinth.com/mod/aurorasdecorations) mod, which you should try out/use instead if you aren't looking for server side mod! +## Configuration +Features can be configured in `config/polydecorations.json` (created on first start, with everything enabled). +Every feature can be set to one of these values: +- `true` - enabled (default). +- `false` - its recipes are removed, but its blocks and items still exist, so nothing gets removed from existing worlds. + Features without recipes (`wall_lanterns`, `fence_leads`) stop working instead. +- `"hard"` - removed completely. Its blocks, items and entities aren't registered, it doesn't use + any Polymer block states and its assets aren't added to the resource pack. + Blocks and items of this feature are removed from existing worlds! + +```json +{ + "features": { + "bench": false, + "statues": "hard" + } +} +``` + +Features: `canvas`, `mailbox`, `sign_post`, `rope`, `hammer`, `trowel`, `wall_lanterns` (placing lanterns on walls), +`fence_leads` (tying a lead to a fence without a leashed mob), `shelf`, `bench`, `table`, `tool_rack`, `stump`, `sleeping_bag`, +`brazier`, `copper_campfire`, `globe`, `display_case`, `flower_pots`, `ghost_lights`, `trashcan`, `basket`, `cardboard_box`, +`wind_chime`, `statues` and `tied_containers` (tying containers with string to hide their contents). + ## Extra mods you might want to use! ### Polymer AutoHost diff --git a/src/main/java/eu/pb4/polydecorations/DecorationsConfig.java b/src/main/java/eu/pb4/polydecorations/DecorationsConfig.java new file mode 100644 index 0000000..400ef39 --- /dev/null +++ b/src/main/java/eu/pb4/polydecorations/DecorationsConfig.java @@ -0,0 +1,109 @@ +package eu.pb4.polydecorations; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import net.fabricmc.loader.api.FabricLoader; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.file.Files; +import java.util.EnumMap; +import java.util.Map; + +// Loaded from the mixin plugin, so it can't touch any Minecraft classes +public final class DecorationsConfig { + private static final Logger LOGGER = LoggerFactory.getLogger("PolyDecorations"); + private static final Map MODES = load(); + + public static Mode mode(DecorationsFeature feature) { + return MODES.getOrDefault(feature, Mode.ENABLED); + } + + private static Map load() { + var modes = new EnumMap(DecorationsFeature.class); + if (System.getProperty("fabric-api.datagen") != null) { + return modes; + } + + var path = FabricLoader.getInstance().getConfigDir().resolve("polydecorations.json"); + var features = new JsonObject(); + var write = true; + try { + if (Files.exists(path)) { + var json = JsonParser.parseString(Files.readString(path)).getAsJsonObject(); + if (json.has("features")) { + features = json.getAsJsonObject("features"); + } + write = false; + } + + for (var key : features.keySet()) { + if (DecorationsFeature.byKey(key) == null) { + LOGGER.warn("Unknown feature '{}' in config/polydecorations.json", key); + } + } + + for (var feature : DecorationsFeature.values()) { + if (!features.has(feature.key())) { + features.addProperty(feature.key(), true); + write = true; + continue; + } + + var mode = Mode.of(features.get(feature.key())); + if (mode == null) { + LOGGER.warn("Invalid value for '{}' in config/polydecorations.json, expected true, false or \"hard\"", feature.key()); + } else if (mode != Mode.ENABLED) { + modes.put(feature, mode); + } + } + } catch (Throwable e) { + LOGGER.error("Failed to read config/polydecorations.json, all features will be enabled!", e); + return new EnumMap<>(DecorationsFeature.class); + } + + if (write) { + try { + var json = new JsonObject(); + json.add("features", features); + Files.createDirectories(path.getParent()); + Files.writeString(path, new GsonBuilder().setPrettyPrinting().create().toJson(json)); + } catch (Throwable e) { + LOGGER.warn("Failed to write config/polydecorations.json", e); + } + } + + if (!modes.isEmpty()) { + LOGGER.info("Disabled features: {}", modes); + } + return modes; + } + + public enum Mode { + ENABLED, + // Content stays registered, but can't be crafted or obtained in survival + DISABLED, + // Content isn't registered at all + HARD; + + @Nullable + private static Mode of(JsonElement element) { + if (!(element instanceof JsonPrimitive primitive)) { + return null; + } + if (primitive.isBoolean()) { + return primitive.getAsBoolean() ? ENABLED : DISABLED; + } + return switch (primitive.getAsString()) { + case "true" -> ENABLED; + case "false" -> DISABLED; + case "hard" -> HARD; + default -> null; + }; + } + } +} diff --git a/src/main/java/eu/pb4/polydecorations/DecorationsFeature.java b/src/main/java/eu/pb4/polydecorations/DecorationsFeature.java new file mode 100644 index 0000000..9bcd206 --- /dev/null +++ b/src/main/java/eu/pb4/polydecorations/DecorationsFeature.java @@ -0,0 +1,116 @@ +package eu.pb4.polydecorations; + +import org.jetbrains.annotations.Nullable; + +import java.util.EnumSet; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Pattern; + +// Patterns match names of assets (without type folder and extension, like "oak_bench_left" or "statue/oak/head"), +// recipes, loot tables and translation keys. Names not matching any feature are shared. +// Loaded from the mixin plugin, so it can't touch any Minecraft classes +public enum DecorationsFeature { + CANVAS("canvas", "canvas_*", "font/canvas", "sgui/pixel"), + MAILBOX("*_mailbox", "base_mailbox", "mailbox_*", "sgui/mailbox_select", "sgui/shelf_2", "palettes/wood/*"), + SIGN_POST("*_sign_post", "base_sign_post", "sign_post", "sign_post_*", "palettes/wood/*"), + ROPE("rope", "rope_*", "rope/*"), + HAMMER("hammer"), + TROWEL("trowel"), + WALL_LANTERNS("*wall_lantern", "lantern_support", "lantern_support/*"), + FENCE_LEADS("first_leash_fence_knot"), + SHELF("*_shelf", "*_shelf_top", "*_shelf_double", "base_shelf*", "sgui/shelf", "sgui/shelf_2"), + BENCH("*_bench", "*_bench_*", "base_bench*", "seat"), + TABLE("*_table", "*_table_*", "base_table*"), + TOOL_RACK("*_tool_rack", "base_tool_rack"), + STUMP("*_stump", "*_stump_tall", "*_stump_top", "base_stump*", "seat"), + SLEEPING_BAG("*sleeping_bag*", "palettes/bed_color/*"), + BRAZIER("*brazier*", "empty2", "copper_campfire_fire", "copper_campfire_log_lit", "palette/copper_bars/*"), + COPPER_CAMPFIRE("copper_campfire*"), + GLOBE("globe*", "tiny_potato"), + DISPLAY_CASE("display_case*"), + FLOWER_POTS("large_flower_pot", "long_flower_pot", "long_flower_pot/*", "empty"), + GHOST_LIGHTS("*ghost_light"), + TRASHCAN("trashcan*", "trashcan/*", "sgui/trashcan"), + BASKET("basket*"), + CARDBOARD_BOX("cardboard_box*"), + WIND_CHIME("wind_chime*", "wind_chime/*"), + STATUES("statue", "*_statue", "statue/*"), + TIED_CONTAINERS("tied", "tie_container"); + + private final String key; + private final Pattern assets; + + DecorationsFeature(String... assetPatterns) { + this.key = this.name().toLowerCase(Locale.ROOT); + var regex = new StringBuilder(); + for (var pattern : assetPatterns) { + if (!regex.isEmpty()) { + regex.append('|'); + } + regex.append(Pattern.quote(pattern).replace("*", "\\E.*\\Q")); + } + this.assets = Pattern.compile(regex.toString()); + } + + public String key() { + return this.key; + } + + public DecorationsConfig.Mode mode() { + return DecorationsConfig.mode(this); + } + + // Can be crafted and obtained in survival + public boolean isEnabled() { + return this.mode() == DecorationsConfig.Mode.ENABLED; + } + + // Has its blocks, items and entities registered + public boolean isRegistered() { + return this.mode() != DecorationsConfig.Mode.HARD; + } + + public static boolean anyRegistered(DecorationsFeature... features) { + for (var feature : features) { + if (feature.isRegistered()) { + return true; + } + } + return false; + } + + public static boolean anyHardDisabled() { + for (var feature : values()) { + if (!feature.isRegistered()) { + return true; + } + } + return false; + } + + public static Set owners(String name) { + var set = EnumSet.noneOf(DecorationsFeature.class); + for (var feature : values()) { + if (feature.assets.matcher(name).matches()) { + set.add(feature); + } + } + return set; + } + + public static boolean isUsed(String name) { + var owners = owners(name); + return owners.isEmpty() || owners.stream().anyMatch(DecorationsFeature::isRegistered); + } + + @Nullable + public static DecorationsFeature byKey(String key) { + for (var feature : values()) { + if (feature.key.equals(key)) { + return feature; + } + } + return null; + } +} diff --git a/src/main/java/eu/pb4/polydecorations/DecorationsMixinPlugin.java b/src/main/java/eu/pb4/polydecorations/DecorationsMixinPlugin.java new file mode 100644 index 0000000..b89d491 --- /dev/null +++ b/src/main/java/eu/pb4/polydecorations/DecorationsMixinPlugin.java @@ -0,0 +1,58 @@ +package eu.pb4.polydecorations; + +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static eu.pb4.polydecorations.DecorationsFeature.*; + +public class DecorationsMixinPlugin implements IMixinConfigPlugin { + private static final String PACKAGE = "eu.pb4.polydecorations.mixin."; + // Mixins only needed by some features, skipped if all of them are hard disabled + private static final Map FEATURE_MIXINS = Map.ofEntries( + Map.entry("BlockItemMixin", new DecorationsFeature[]{ WALL_LANTERNS }), + Map.entry("LanternBlockMixin", new DecorationsFeature[]{ WALL_LANTERNS, ROPE }), + Map.entry("CeilingHangingSignBlockMixin", new DecorationsFeature[]{ ROPE }), + Map.entry("LeadItemMixin", new DecorationsFeature[]{ FENCE_LEADS }), + Map.entry("FaceAttachedHorizontalDirectionalBlockMixin", new DecorationsFeature[]{ STUMP }), + Map.entry("ShulkerBoxBlockEntityMixin", new DecorationsFeature[]{ BASKET, TIED_CONTAINERS }), + Map.entry("ItemContainerContentsMixin", new DecorationsFeature[]{ TIED_CONTAINERS }), + Map.entry("LivingEntityMixin", new DecorationsFeature[]{ SLEEPING_BAG }), + Map.entry("ServerPlayerMixin", new DecorationsFeature[]{ SLEEPING_BAG }), + Map.entry("SignBlockEntityMixin", new DecorationsFeature[]{ SIGN_POST }), + Map.entry("flowerpot.PlantBlockMixin", new DecorationsFeature[]{ FLOWER_POTS }), + Map.entry("flowerpot.SaplingBlockMixin", new DecorationsFeature[]{ FLOWER_POTS }) + ); + + @Override + public void onLoad(String mixinPackage) {} + + @Override + public String getRefMapperConfig() { + return null; + } + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + var features = FEATURE_MIXINS.get(mixinClassName.startsWith(PACKAGE) ? mixinClassName.substring(PACKAGE.length()) : mixinClassName); + return features == null || DecorationsFeature.anyRegistered(features); + } + + @Override + public void acceptTargets(Set myTargets, Set otherTargets) {} + + @Override + public List getMixins() { + return null; + } + + @Override + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {} + + @Override + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) {} +} diff --git a/src/main/java/eu/pb4/polydecorations/ModInit.java b/src/main/java/eu/pb4/polydecorations/ModInit.java index 00b7175..d1013a8 100644 --- a/src/main/java/eu/pb4/polydecorations/ModInit.java +++ b/src/main/java/eu/pb4/polydecorations/ModInit.java @@ -52,6 +52,7 @@ public void onInitialize() { LOGGER.warn("====================================================="); } + FeatureResourceCondition.register(); DecorationsBlocks.register(); DecorationsBlockEntities.register(); DecorationsModels.register(); @@ -70,6 +71,7 @@ public void onInitialize() { GuiTextures.register(); PolydexCompat.register(); PolymerResourcePackUtils.addModAssets(ID); + FeatureAssetFilter.register(); PolymerResourcePackUtils.markAsRequired(); ResourcePackExtras.forDefault().addBridgedModelsFolder(id("block"), id("sgui")); } diff --git a/src/main/java/eu/pb4/polydecorations/block/DecorationsBlockEntities.java b/src/main/java/eu/pb4/polydecorations/block/DecorationsBlockEntities.java index 5c7fcbe..5f08b74 100644 --- a/src/main/java/eu/pb4/polydecorations/block/DecorationsBlockEntities.java +++ b/src/main/java/eu/pb4/polydecorations/block/DecorationsBlockEntities.java @@ -1,5 +1,6 @@ package eu.pb4.polydecorations.block; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.ModInit; import eu.pb4.polydecorations.block.furniture.WindChimeBlockEntity; import eu.pb4.polydecorations.block.item.*; @@ -16,31 +17,33 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Objects; import static eu.pb4.polydecorations.ModInit.id; public class DecorationsBlockEntities { - public static final BlockEntityType SHELF = register("shelf", ShelfBlockEntity::new); - public static final BlockEntityType SIGN_POST = register("sign_post", SignPostBlockEntity::new); + public static final BlockEntityType SHELF = DecorationsFeature.SHELF.isRegistered() ? register("shelf", ShelfBlockEntity::new) : null; + public static final BlockEntityType SIGN_POST = DecorationsFeature.SIGN_POST.isRegistered() ? register("sign_post", SignPostBlockEntity::new) : null; - public static final BlockEntityType MAILBOX = register("mailbox", MailboxBlockEntity::new); - public static final BlockEntityType GLOBE = register("globe", GenericSingleItemBlockEntity::globe, DecorationsBlocks.GLOBE); - public static final BlockEntityType TRASHCAN = register("trashcan", TrashCanBlockEntity::new, DecorationsBlocks.TRASHCAN); - public static final BlockEntityType GENERIC_PICKABLE_STORAGE = register("generic_pickable_storage", PickableItemContainerBlockEntity::new, - DecorationsBlocks.BASKET, DecorationsBlocks.CARDBOARD_BOX); - public static final BlockEntityType WIND_CHIME = register("wind_chime", WindChimeBlockEntity::new, DecorationsBlocks.WIND_CHIME); + public static final BlockEntityType MAILBOX = DecorationsFeature.MAILBOX.isRegistered() ? register("mailbox", MailboxBlockEntity::new) : null; + public static final BlockEntityType GLOBE = DecorationsFeature.GLOBE.isRegistered() ? register("globe", GenericSingleItemBlockEntity::globe, DecorationsBlocks.GLOBE) : null; + public static final BlockEntityType TRASHCAN = DecorationsFeature.TRASHCAN.isRegistered() ? register("trashcan", TrashCanBlockEntity::new, DecorationsBlocks.TRASHCAN) : null; + public static final BlockEntityType GENERIC_PICKABLE_STORAGE = DecorationsFeature.anyRegistered(DecorationsFeature.BASKET, DecorationsFeature.CARDBOARD_BOX) + ? register("generic_pickable_storage", PickableItemContainerBlockEntity::new, DecorationsBlocks.BASKET, DecorationsBlocks.CARDBOARD_BOX) : null; + public static final BlockEntityType WIND_CHIME = DecorationsFeature.WIND_CHIME.isRegistered() ? register("wind_chime", WindChimeBlockEntity::new, DecorationsBlocks.WIND_CHIME) : null; - public static final BlockEntityType DISPLAY_CASE = register("display_case", + public static final BlockEntityType DISPLAY_CASE = DecorationsFeature.DISPLAY_CASE.isRegistered() ? register("display_case", GenericSingleItemBlockEntity::displayCase, DecorationsBlocks.DISPLAY_CASE - ); + ) : null; - public static final BlockEntityType LONG_FLOWER_POT = register("long_flower_pot", + public static final BlockEntityType LONG_FLOWER_POT = DecorationsFeature.FLOWER_POTS.isRegistered() ? register("long_flower_pot", LongFlowerPotBlockEntity::new, DecorationsBlocks.LONG_FLOWER_POT - ); + ) : null; - public static final BlockEntityType TOOL_RACK = register("tool_rack", ToolRackBlockEntity::new); + public static final BlockEntityType TOOL_RACK = DecorationsFeature.TOOL_RACK.isRegistered() ? register("tool_rack", ToolRackBlockEntity::new) : null; //public static final BlockEntityType BANNER_BED = register("banner_bed", // FabricBlockEntityTypeBuilder.create(BedWithBannerBlockEntity::new) @@ -48,7 +51,7 @@ public class DecorationsBlockEntities { ; public static BlockEntityType register(String path, FabricBlockEntityTypeBuilder.Factory factory, Block... blocks) { - return register(path, FabricBlockEntityTypeBuilder.create(factory, blocks)); + return register(path, FabricBlockEntityTypeBuilder.create(factory, Arrays.stream(blocks).filter(Objects::nonNull).toArray(Block[]::new))); } public static BlockEntityType register(String path, FabricBlockEntityTypeBuilder item) { var x = Registry.register(BuiltInRegistries.BLOCK_ENTITY_TYPE, Identifier.fromNamespaceAndPath(ModInit.ID, path), item.build()); @@ -57,6 +60,8 @@ public static BlockEntityType register(String path, F } public static void register() { - BuiltInRegistries.BLOCK_ENTITY_TYPE.addAlias(id("basket"), id("generic_pickable_storage")); + if (GENERIC_PICKABLE_STORAGE != null) { + BuiltInRegistries.BLOCK_ENTITY_TYPE.addAlias(id("basket"), id("generic_pickable_storage")); + } } } diff --git a/src/main/java/eu/pb4/polydecorations/block/DecorationsBlocks.java b/src/main/java/eu/pb4/polydecorations/block/DecorationsBlocks.java index 30e79b3..baedf0c 100644 --- a/src/main/java/eu/pb4/polydecorations/block/DecorationsBlocks.java +++ b/src/main/java/eu/pb4/polydecorations/block/DecorationsBlocks.java @@ -1,5 +1,6 @@ package eu.pb4.polydecorations.block; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.ModInit; import eu.pb4.polydecorations.block.extension.AttachedSignPostBlock; import eu.pb4.polydecorations.block.extension.WallAttachedLanternBlock; @@ -44,66 +45,66 @@ public class DecorationsBlocks { private static final List BLOCKS = new ArrayList<>(); - public static final WallAttachedLanternBlock WALL_LANTERN = register("wall_lantern", (LanternBlock) Blocks.LANTERN, WallAttachedLanternBlock::new); - public static final WallAttachedLanternBlock WALL_SOUL_LANTERN = register("wall_soul_lantern", (LanternBlock) Blocks.SOUL_LANTERN, WallAttachedLanternBlock::new); + public static final WallAttachedLanternBlock WALL_LANTERN = DecorationsFeature.WALL_LANTERNS.isRegistered() ? register("wall_lantern", (LanternBlock) Blocks.LANTERN, WallAttachedLanternBlock::new) : null; + public static final WallAttachedLanternBlock WALL_SOUL_LANTERN = DecorationsFeature.WALL_LANTERNS.isRegistered() ? register("wall_soul_lantern", (LanternBlock) Blocks.SOUL_LANTERN, WallAttachedLanternBlock::new) : null; - public static WeatheringCopperCollection WALL_COPPER_LANTERNS = registerRelativeCopper("copper_wall_lantern", Blocks.COPPER_LANTERN, + public static WeatheringCopperCollection WALL_COPPER_LANTERNS = DecorationsFeature.WALL_LANTERNS.isRegistered() ? registerRelativeCopper("copper_wall_lantern", Blocks.COPPER_LANTERN, (settings, block) -> new WallAttachedLanternBlock(settings, (LanternBlock) block), (level, settings, block) -> new WallAttachedOxidizableLanternBlock(settings, (WeatheringLanternBlock) block), (level, block) -> BlockBehaviour.Properties.ofFullCopy(block) - ); + ) : null; - public static final BrazierBlock BRAZIER = register("brazier", Blocks.LANTERN, (settings, ignored) -> new BrazierBlock(settings.noOcclusion().lightLevel(x -> { + public static final BrazierBlock BRAZIER = DecorationsFeature.BRAZIER.isRegistered() ? register("brazier", Blocks.LANTERN, (settings, ignored) -> new BrazierBlock(settings.noOcclusion().lightLevel(x -> { return x.getValue(BrazierBlock.LIT) ? Blocks.CAMPFIRE.defaultBlockState().getLightEmission() : 0; })) - ); - public static final BrazierBlock SOUL_BRAZIER = register("soul_brazier", Blocks.SOUL_LANTERN, (settings, ignored) -> new BrazierBlock(settings.noOcclusion().lightLevel(x -> { + ) : null; + public static final BrazierBlock SOUL_BRAZIER = DecorationsFeature.BRAZIER.isRegistered() ? register("soul_brazier", Blocks.SOUL_LANTERN, (settings, ignored) -> new BrazierBlock(settings.noOcclusion().lightLevel(x -> { return x.getValue(BrazierBlock.LIT) ? Blocks.SOUL_CAMPFIRE.defaultBlockState().getLightEmission() : 0; })) - ); + ) : null; - public static final BrazierBlock COPPER_BRAZIER = register("copper_brazier", Blocks.COPPER_LANTERN.weathering().unaffected(), (settings, ignored) -> new BrazierBlock(settings.noOcclusion().lightLevel(x -> { + public static final BrazierBlock COPPER_BRAZIER = DecorationsFeature.BRAZIER.isRegistered() ? register("copper_brazier", Blocks.COPPER_LANTERN.weathering().unaffected(), (settings, ignored) -> new BrazierBlock(settings.noOcclusion().lightLevel(x -> { return x.getValue(BrazierBlock.LIT) ? Blocks.CAMPFIRE.defaultBlockState().getLightEmission() : 0; })) - ); + ) : null; - public static final PolymerCampfireBlock COPPER_CAMPFIRE = register("copper_campfire", Blocks.CAMPFIRE, (settings, block) -> new PolymerCampfireBlock(true, 1, settings)); + public static final PolymerCampfireBlock COPPER_CAMPFIRE = DecorationsFeature.COPPER_CAMPFIRE.isRegistered() ? register("copper_campfire", Blocks.CAMPFIRE, (settings, block) -> new PolymerCampfireBlock(true, 1, settings)) : null; - public static final GlobeBlock GLOBE = register("globe", BlockBehaviour.Properties.ofFullCopy(Blocks.OAK_PLANKS).noOcclusion(), GlobeBlock::new); - public static final RopeBlock ROPE = register("rope", BlockBehaviour.Properties.of().strength(1f).sound(SoundType.COBWEB).instabreak().noOcclusion(), RopeBlock::new); - public static final DisplayCaseBlock DISPLAY_CASE = register("display_case", BlockBehaviour.Properties.ofFullCopy(Blocks.GLASS).noOcclusion(), DisplayCaseBlock::new); - public static final WindChimeBlock WIND_CHIME = register("wind_chime", BlockBehaviour.Properties.ofFullCopy(Blocks.GLASS).noOcclusion(), WindChimeBlock::new); - public static final TrashCanBlock TRASHCAN = register("trashcan", settings -> new TrashCanBlock(settings - .mapColor(MapColor.METAL).strength(3.5F).sound(SoundType.LANTERN).noOcclusion())); + public static final GlobeBlock GLOBE = DecorationsFeature.GLOBE.isRegistered() ? register("globe", BlockBehaviour.Properties.ofFullCopy(Blocks.OAK_PLANKS).noOcclusion(), GlobeBlock::new) : null; + public static final RopeBlock ROPE = DecorationsFeature.ROPE.isRegistered() ? register("rope", BlockBehaviour.Properties.of().strength(1f).sound(SoundType.COBWEB).instabreak().noOcclusion(), RopeBlock::new) : null; + public static final DisplayCaseBlock DISPLAY_CASE = DecorationsFeature.DISPLAY_CASE.isRegistered() ? register("display_case", BlockBehaviour.Properties.ofFullCopy(Blocks.GLASS).noOcclusion(), DisplayCaseBlock::new) : null; + public static final WindChimeBlock WIND_CHIME = DecorationsFeature.WIND_CHIME.isRegistered() ? register("wind_chime", BlockBehaviour.Properties.ofFullCopy(Blocks.GLASS).noOcclusion(), WindChimeBlock::new) : null; + public static final TrashCanBlock TRASHCAN = DecorationsFeature.TRASHCAN.isRegistered() ? register("trashcan", settings -> new TrashCanBlock(settings + .mapColor(MapColor.METAL).strength(3.5F).sound(SoundType.LANTERN).noOcclusion())) : null; - public static final PickableItemContainerBlock BASKET = register("basket", settings -> new BasketBlock(settings + public static final PickableItemContainerBlock BASKET = DecorationsFeature.BASKET.isRegistered() ? register("basket", settings -> new BasketBlock(settings .mapColor(MapColor.WOOD).strength(0.5F) .ignitedByLava() - .sound(SoundType.SCAFFOLDING).noOcclusion())); + .sound(SoundType.SCAFFOLDING).noOcclusion())) : null; - public static final PickableItemContainerBlock CARDBOARD_BOX = register("cardboard_box", settings -> new PickableItemContainerBlock(settings + public static final PickableItemContainerBlock CARDBOARD_BOX = DecorationsFeature.CARDBOARD_BOX.isRegistered() ? register("cardboard_box", settings -> new PickableItemContainerBlock(settings .mapColor(MapColor.WOOD).strength(0.4F) .ignitedByLava() - .sound(DecorationsSoundEvents.CARDBOARD).noOcclusion(), DecorationsSoundEvents.CARDBOARD_BOX_OPEN, DecorationsSoundEvents.CARDBOARD_BOX_CLOSE)); + .sound(DecorationsSoundEvents.CARDBOARD).noOcclusion(), DecorationsSoundEvents.CARDBOARD_BOX_OPEN, DecorationsSoundEvents.CARDBOARD_BOX_CLOSE)) : null; - public static final LargeFlowerPotBlock LARGE_FLOWER_POT = register("large_flower_pot", settings -> new LargeFlowerPotBlock(settings - .mapColor(MapColor.COLOR_ORANGE).instrument(NoteBlockInstrument.BASEDRUM).strength(1.25F).noOcclusion())); + public static final LargeFlowerPotBlock LARGE_FLOWER_POT = DecorationsFeature.FLOWER_POTS.isRegistered() ? register("large_flower_pot", settings -> new LargeFlowerPotBlock(settings + .mapColor(MapColor.COLOR_ORANGE).instrument(NoteBlockInstrument.BASEDRUM).strength(1.25F).noOcclusion())) : null; - public static final LongFlowerPotBlock LONG_FLOWER_POT = register("long_flower_pot", BlockBehaviour.Properties.of() - .mapColor(MapColor.NONE).instabreak().noOcclusion(), LongFlowerPotBlock::new); + public static final LongFlowerPotBlock LONG_FLOWER_POT = DecorationsFeature.FLOWER_POTS.isRegistered() ? register("long_flower_pot", BlockBehaviour.Properties.of() + .mapColor(MapColor.NONE).instabreak().noOcclusion(), LongFlowerPotBlock::new) : null; - public static final GhostLightBlock GHOST_LIGHT = register("ghost_light", + public static final GhostLightBlock GHOST_LIGHT = DecorationsFeature.GHOST_LIGHTS.isRegistered() ? register("ghost_light", settings -> new GhostLightBlock(settings.noOcclusion() - .noCollision().instabreak().lightLevel(x -> 7), 5, 1, 0.001f, ParticleTypes.SOUL_FIRE_FLAME)); + .noCollision().instabreak().lightLevel(x -> 7), 5, 1, 0.001f, ParticleTypes.SOUL_FIRE_FLAME)) : null; - public static final GhostLightBlock BURNING_GHOST_LIGHT = register("burning_ghost_light", BlockBehaviour.Properties.ofFullCopy(GHOST_LIGHT), - settings -> new GhostLightBlock(settings.lightLevel(x -> 9), 5, 1, 0.001f, ParticleTypes.FLAME)); + public static final GhostLightBlock BURNING_GHOST_LIGHT = DecorationsFeature.GHOST_LIGHTS.isRegistered() ? register("burning_ghost_light", BlockBehaviour.Properties.ofFullCopy(GHOST_LIGHT), + settings -> new GhostLightBlock(settings.lightLevel(x -> 9), 5, 1, 0.001f, ParticleTypes.FLAME)) : null; - public static final GhostLightBlock COPPER_GHOST_LIGHT = register("copper_ghost_light", BlockBehaviour.Properties.ofFullCopy(GHOST_LIGHT), - settings -> new GhostLightBlock(settings.lightLevel(x -> 9), 5, 1, 0.001f, ParticleTypes.COPPER_FIRE_FLAME)); + public static final GhostLightBlock COPPER_GHOST_LIGHT = DecorationsFeature.GHOST_LIGHTS.isRegistered() ? register("copper_ghost_light", BlockBehaviour.Properties.ofFullCopy(GHOST_LIGHT), + settings -> new GhostLightBlock(settings.lightLevel(x -> 9), 5, 1, 0.001f, ParticleTypes.COPPER_FIRE_FLAME)) : null; - public static final Map SHELF = registerWood("shelf", (x, id, settings) -> { + public static final Map SHELF = DecorationsFeature.SHELF.isRegistered() ? registerWood("shelf", (x, id, settings) -> { var planks = WoodUtil.getPlanksId(x); if (BuiltInRegistries.BLOCK.containsKey(planks)) { return new PlainShelfBlock( @@ -113,9 +114,9 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); - public static final Map BENCH = registerWood("bench", (x, id, settings) -> { + public static final Map BENCH = DecorationsFeature.BENCH.isRegistered() ? registerWood("bench", (x, id, settings) -> { var planks = WoodUtil.getPlanksId(x); if (BuiltInRegistries.BLOCK.containsKey(planks)) { return new BenchBlock( @@ -127,9 +128,9 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); - public static final Map TOOL_RACK = registerWood("tool_rack", (x, id, settings) -> { + public static final Map TOOL_RACK = DecorationsFeature.TOOL_RACK.isRegistered() ? registerWood("tool_rack", (x, id, settings) -> { var planks = WoodUtil.getPlanksId(x); if (BuiltInRegistries.BLOCK.containsKey(planks)) { return new ToolRackBlock( @@ -140,9 +141,9 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); - public static final Map TABLE = registerWood("table", (x, id, settings) -> { + public static final Map TABLE = DecorationsFeature.TABLE.isRegistered() ? registerWood("table", (x, id, settings) -> { var planks = WoodUtil.getPlanksId(x); if (BuiltInRegistries.BLOCK.containsKey(planks)) { return new TableBlock(id, @@ -153,9 +154,9 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); - public static final Map STUMP = registerWood("stump", (x, id, settings) -> { + public static final Map STUMP = DecorationsFeature.STUMP.isRegistered() ? registerWood("stump", (x, id, settings) -> { var log = WoodUtil.getLogId(x); if (WoodUtil.hasLog(x) && BuiltInRegistries.BLOCK.containsKey(log)) { @@ -169,9 +170,9 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); - public static final Map STRIPPED_STUMP = registerWood("stripped_", "stump", (x, id, settings) -> { + public static final Map STRIPPED_STUMP = DecorationsFeature.STUMP.isRegistered() ? registerWood("stripped_", "stump", (x, id, settings) -> { var log = WoodUtil.getStrippedLogId(x); if (!log.equals(WoodUtil.getLogId(x)) && WoodUtil.hasLog(x) && BuiltInRegistries.BLOCK.containsKey(log)) { @@ -187,9 +188,9 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); - public static final Map WOOD_SIGN_POST = registerWood("sign_post", (x, id, settings) -> { + public static final Map WOOD_SIGN_POST = DecorationsFeature.SIGN_POST.isRegistered() ? registerWood("sign_post", (x, id, settings) -> { var planks = WoodUtil.getFenceId(x); var block = BuiltInRegistries.BLOCK.getValue(planks); if (block instanceof FenceBlock) { @@ -197,9 +198,9 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); - public static final Map SLEEPING_BAG = registerDye("sleeping_bag", (x, id, settings) -> { + public static final Map SLEEPING_BAG = DecorationsFeature.SLEEPING_BAG.isRegistered() ? registerDye("sleeping_bag", (x, id, settings) -> { var bed = Identifier.parse(x.getSerializedName() + "_bed"); var block = BuiltInRegistries.BLOCK.getValue(bed); if (block instanceof BedBlock) { @@ -207,10 +208,13 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); public static final Map WALL_SIGN_POST = Util.make(() -> { var map = new HashMap(); + if (!DecorationsFeature.SIGN_POST.isRegistered()) { + return map; + } var l = new ArrayList(); for (var b : BuiltInRegistries.BLOCK) { if (b instanceof WallBlock && BuiltInRegistries.BLOCK.getKey(b).getNamespace().equals(Identifier.DEFAULT_NAMESPACE)) { @@ -225,10 +229,10 @@ public class DecorationsBlocks { return map; }); - public static final AttachedSignPostBlock NETHER_BRICK_SIGN_POST = register("nether_brick_sign_post", Blocks.NETHER_BRICK_FENCE, - (settings, block) -> new AttachedSignPostBlock(settings, block, 4)); + public static final AttachedSignPostBlock NETHER_BRICK_SIGN_POST = DecorationsFeature.SIGN_POST.isRegistered() ? register("nether_brick_sign_post", Blocks.NETHER_BRICK_FENCE, + (settings, block) -> new AttachedSignPostBlock(settings, block, 4)) : null; - public static final Map WOODEN_MAILBOX = registerWood("mailbox", (x, id, settings) -> { + public static final Map WOODEN_MAILBOX = DecorationsFeature.MAILBOX.isRegistered() ? registerWood("mailbox", (x, id, settings) -> { var planks = WoodUtil.getPlanksId(x); if (BuiltInRegistries.BLOCK.containsKey(planks)) { var block = BuiltInRegistries.BLOCK.getValue(planks); @@ -236,7 +240,7 @@ public class DecorationsBlocks { } return null; - }); + }) : Map.of(); private static Map registerWood(String id, TriFunction object) { return registerWood("", id, object); @@ -268,7 +272,9 @@ private static Map registerDye(Str } public static void register() { - LongFlowerPotBlock.setupResourcesAndMapping(); + if (DecorationsFeature.FLOWER_POTS.isRegistered()) { + LongFlowerPotBlock.setupResourcesAndMapping(); + } if (ModInit.DEV_MODE) { ServerLifecycleEvents.SERVER_STARTED.register((DecorationsBlocks::validateLootTables)); diff --git a/src/main/java/eu/pb4/polydecorations/datagen/BlockTagsProvider.java b/src/main/java/eu/pb4/polydecorations/datagen/BlockTagsProvider.java index fe7334e..0b998c1 100644 --- a/src/main/java/eu/pb4/polydecorations/datagen/BlockTagsProvider.java +++ b/src/main/java/eu/pb4/polydecorations/datagen/BlockTagsProvider.java @@ -7,8 +7,10 @@ import net.fabricmc.fabric.api.datagen.v1.FabricPackOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagsProvider; import net.minecraft.core.HolderLookup; +import net.minecraft.data.tags.TagAppender; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.BlockTags; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; @@ -119,6 +121,11 @@ protected void addTags(HolderLookup.Provider arg) { } + @Override + protected TagAppender tag(TagKey tag) { + return FeatureConditions.optionalEntries(super.tag(tag)); + } + // Temp workaround private ResourceKey get(Block item) { return item.builtInRegistryHolder().key(); diff --git a/src/main/java/eu/pb4/polydecorations/datagen/CustomAssetProvider.java b/src/main/java/eu/pb4/polydecorations/datagen/CustomAssetProvider.java index 6db96a4..f6edb46 100644 --- a/src/main/java/eu/pb4/polydecorations/datagen/CustomAssetProvider.java +++ b/src/main/java/eu/pb4/polydecorations/datagen/CustomAssetProvider.java @@ -233,7 +233,7 @@ public static void writeWoodenBlocksAndItems(BiConsumer writer, .toJson().getBytes(StandardCharsets.UTF_8)); }); - getValues(DecorationsItems.WOODEN_STATUE, types, (type, item) -> { + getValues(DecorationsItems.SIGN_POST, types, (type, item) -> { writer.accept("assets/polydecorations/models/block/" + type.name().replace(':', '/') + "_sign_post.json", BASE_WOOD_MODEL_JSON .replace("|TYPE|", "sign_post") .replace("|PLANKS|", "polydecorations:block/sign_post_" + type.name().replace(':', '/')) @@ -244,7 +244,9 @@ public static void writeWoodenBlocksAndItems(BiConsumer writer, writer.accept(AssetPaths.itemAsset(id(type.name().replace(':', '/') + "_sign_post")), new ItemAsset(new BasicItemModel(id("block/" + type.name().replace(':', '/') + "_sign_post")), ItemAsset.Properties.DEFAULT) .toJson().getBytes(StandardCharsets.UTF_8)); + }); + getValues(DecorationsItems.WOODEN_STATUE, types, (type, item) -> { writeStatue(type.name().replace(':', '/'), WoodUtil.getPlanksTexture(type).toString(), writer); }); diff --git a/src/main/java/eu/pb4/polydecorations/datagen/FeatureConditions.java b/src/main/java/eu/pb4/polydecorations/datagen/FeatureConditions.java new file mode 100644 index 0000000..643069f --- /dev/null +++ b/src/main/java/eu/pb4/polydecorations/datagen/FeatureConditions.java @@ -0,0 +1,121 @@ +package eu.pb4.polydecorations.datagen; + +import eu.pb4.polydecorations.DecorationsFeature; +import eu.pb4.polydecorations.ModInit; +import eu.pb4.polydecorations.util.FeatureResourceCondition; +import net.fabricmc.fabric.api.datagen.v1.recipe.FabricRecipeOutput; +import net.fabricmc.fabric.api.resource.conditions.v1.ResourceCondition; +import net.fabricmc.fabric.api.resource.conditions.v1.ResourceConditions; +import net.fabricmc.fabric.impl.datagen.FabricDataGenHelper; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.Registry; +import net.minecraft.data.tags.TagAppender; +import net.minecraft.data.worldgen.BootstrapContext; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +// Generated recipes, their advancements and loot tables only load if their feature allows it. +// The feature is found by the name of the entry, the same way as for assets +class FeatureConditions { + // Recipes using items of other features + private static final Map> EXTRA_FEATURES = Map.of( + "basket", List.of(DecorationsFeature.ROPE), + "copper_brazier", List.of(DecorationsFeature.COPPER_CAMPFIRE) + ); + + public static ResourceCondition[] recipe(Identifier id) { + var name = name(id); + var list = new ArrayList(); + list.add(owner(name, false)); + for (var feature : EXTRA_FEATURES.getOrDefault(name, List.of())) { + list.add(new FeatureResourceCondition(feature, true)); + } + return list.toArray(ResourceCondition[]::new); + } + + public static ResourceCondition[] lootTable(Identifier id) { + return new ResourceCondition[] { owner(name(id), true) }; + } + + private static String name(Identifier id) { + return id.getPath().substring(id.getPath().lastIndexOf('/') + 1); + } + + private static ResourceCondition owner(String name, boolean registered) { + var owners = DecorationsFeature.owners(name); + if (owners.isEmpty()) { + throw new IllegalStateException("No feature found for '" + name + "', add it to DecorationsFeature"); + } + + var conditions = owners.stream().map(feature -> new FeatureResourceCondition(feature, registered)).toArray(ResourceCondition[]::new); + return conditions.length == 1 ? conditions[0] : ResourceConditions.or(conditions); + } + + public static BootstrapContext recipes(BootstrapContext context) { + return new ConditionalContext<>(context); + } + + // Entries of this mod might not exist if their feature is hard disabled + public static TagAppender optionalEntries(TagAppender appender) { + return new TagAppender<>() { + @Override + public TagAppender add(ResourceKey key) { + if (key.identifier().getNamespace().equals(ModInit.ID)) { + appender.addOptional(key); + } else { + appender.add(key); + } + return this; + } + + @Override + public TagAppender addOptional(ResourceKey key) { + appender.addOptional(key); + return this; + } + + @Override + public TagAppender addTag(TagKey tag) { + appender.addTag(tag); + return this; + } + + @Override + public TagAppender addOptionalTag(TagKey tag) { + appender.addOptionalTag(tag); + return this; + } + }; + } + + // Implements FabricRecipeOutput, as fabric uses it to get recipe ids + private record ConditionalContext(BootstrapContext context) implements BootstrapContext, FabricRecipeOutput { + @Override + public Holder.Reference register(ResourceKey key, T value) { + FabricDataGenHelper.addConditions(value, FeatureConditions.recipe(key.identifier())); + return this.context.register(key, value); + } + + @Override + public HolderGetter lookup(ResourceKey> key) { + return this.context.lookup(key); + } + + @Override + public Stream> listContextElements(ResourceKey> key) { + return this.context.listContextElements(key); + } + + @Override + public Identifier getRecipeIdentifier(Identifier recipeId) { + return this.context instanceof FabricRecipeOutput output ? output.getRecipeIdentifier(recipeId) : recipeId; + } + } +} diff --git a/src/main/java/eu/pb4/polydecorations/datagen/ItemTagsProvider.java b/src/main/java/eu/pb4/polydecorations/datagen/ItemTagsProvider.java index 0012798..3f1d9a8 100644 --- a/src/main/java/eu/pb4/polydecorations/datagen/ItemTagsProvider.java +++ b/src/main/java/eu/pb4/polydecorations/datagen/ItemTagsProvider.java @@ -6,8 +6,10 @@ import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagsProvider; import net.fabricmc.fabric.api.tag.convention.v2.ConventionalItemTags; import net.minecraft.core.HolderLookup; +import net.minecraft.data.tags.TagAppender; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.ItemTags; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import org.jetbrains.annotations.Nullable; @@ -96,6 +98,11 @@ protected void addTags(HolderLookup.Provider arg) { ; } + @Override + protected TagAppender tag(TagKey tag) { + return FeatureConditions.optionalEntries(super.tag(tag)); + } + // Temp workaround private ResourceKey get(Item item) { return item.builtInRegistryHolder().key(); diff --git a/src/main/java/eu/pb4/polydecorations/datagen/LootTables.java b/src/main/java/eu/pb4/polydecorations/datagen/LootTables.java index a51e3e2..3455fae 100644 --- a/src/main/java/eu/pb4/polydecorations/datagen/LootTables.java +++ b/src/main/java/eu/pb4/polydecorations/datagen/LootTables.java @@ -79,7 +79,9 @@ public void generate() { } @Override - public void generate(BiConsumer, LootTable.Builder> biConsumer) { + public void generate(BiConsumer, LootTable.Builder> output) { + BiConsumer, LootTable.Builder> biConsumer = (key, builder) -> + this.withConditions(output, FeatureConditions.lootTable(key.identifier())).accept(key, builder); super.generate(biConsumer); var registries = ((FabricBlockLootSubProviderAccessor) LootTables.this).getRegistriesFuture().join(); diff --git a/src/main/java/eu/pb4/polydecorations/datagen/RecipesProvider.java b/src/main/java/eu/pb4/polydecorations/datagen/RecipesProvider.java index f077eb4..49692bb 100644 --- a/src/main/java/eu/pb4/polydecorations/datagen/RecipesProvider.java +++ b/src/main/java/eu/pb4/polydecorations/datagen/RecipesProvider.java @@ -53,7 +53,9 @@ public RecipesProvider(FabricPackOutput output, CompletableFuture> recipes, BootstrapContext advancements) { + protected RecipeProvider createRecipeProvider(HolderLookup.Provider registryLookup, BootstrapContext> recipeContext, BootstrapContext advancementContext) { + var recipes = FeatureConditions.recipes(recipeContext); + var advancements = FeatureConditions.recipes(advancementContext); return new RecipeProvider(recipes, advancements) { @Override public void buildRecipes() { diff --git a/src/main/java/eu/pb4/polydecorations/entity/DecorationsEntities.java b/src/main/java/eu/pb4/polydecorations/entity/DecorationsEntities.java index 265497a..0ae9aaa 100644 --- a/src/main/java/eu/pb4/polydecorations/entity/DecorationsEntities.java +++ b/src/main/java/eu/pb4/polydecorations/entity/DecorationsEntities.java @@ -1,5 +1,6 @@ package eu.pb4.polydecorations.entity; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.ModInit; import eu.pb4.polymer.core.api.entity.PolymerEntityUtils; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricDefaultAttributeRegistry; @@ -12,22 +13,24 @@ import net.minecraft.world.entity.decoration.LeashFenceKnotEntity; public class DecorationsEntities { - public static final EntityType CANVAS = register("canvas", EntityType.Builder - .of(CanvasEntity::new, MobCategory.MISC).sized(0.5f, 0.5f)); + public static final EntityType CANVAS = DecorationsFeature.CANVAS.isRegistered() ? register("canvas", EntityType.Builder + .of(CanvasEntity::new, MobCategory.MISC).sized(0.5f, 0.5f)) : null; - public static final EntityType STATUE = register("statue", EntityType.Builder - .of(StatueEntity::new, MobCategory.MISC).sized(EntityTypes.ARMOR_STAND.getDimensions().width(), EntityTypes.ARMOR_STAND.getDimensions().height())); + public static final EntityType STATUE = DecorationsFeature.STATUES.isRegistered() ? register("statue", EntityType.Builder + .of(StatueEntity::new, MobCategory.MISC).sized(EntityTypes.ARMOR_STAND.getDimensions().width(), EntityTypes.ARMOR_STAND.getDimensions().height())) : null; - public static final EntityType SEAT = register("seat", EntityType.Builder - .of(SeatEntity::new, MobCategory.MISC).fireImmune().sized(0f, 0f).noSummon()); + public static final EntityType SEAT = DecorationsFeature.anyRegistered(DecorationsFeature.BENCH, DecorationsFeature.STUMP) ? register("seat", EntityType.Builder + .of(SeatEntity::new, MobCategory.MISC).fireImmune().sized(0f, 0f).noSummon()) : null; - public static final EntityType FIRST_LEASH_FENCE_KNOT = register("first_leash_fence_knot", + public static final EntityType FIRST_LEASH_FENCE_KNOT = DecorationsFeature.FENCE_LEADS.isRegistered() ? register("first_leash_fence_knot", EntityType.Builder.of(FirstLeashFenceKnotEntity::new, MobCategory.MISC).noLootTable().sized(0.375F, 0.5F).eyeHeight(0.0625F).clientTrackingRange(10) - .updateInterval(10)); + .updateInterval(10)) : null; public static void register() { - StatueEntity.Type.STONE.fireproof(); - FabricDefaultAttributeRegistry.register(STATUE, StatueEntity.createLivingAttributes()); + if (STATUE != null) { + StatueEntity.Type.STONE.fireproof(); + FabricDefaultAttributeRegistry.register(STATUE, StatueEntity.createLivingAttributes()); + } } public static EntityType register(String path, EntityType.Builder item) { diff --git a/src/main/java/eu/pb4/polydecorations/item/DecorationsItems.java b/src/main/java/eu/pb4/polydecorations/item/DecorationsItems.java index 6abcd4b..4cd5ff2 100644 --- a/src/main/java/eu/pb4/polydecorations/item/DecorationsItems.java +++ b/src/main/java/eu/pb4/polydecorations/item/DecorationsItems.java @@ -3,6 +3,7 @@ import eu.pb4.factorytools.api.item.FactoryBlockItem; import eu.pb4.factorytools.api.item.MultiBlockItem; import eu.pb4.factorytools.api.block.MultiBlock; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.block.DecorationsBlocks; import eu.pb4.polydecorations.block.item.PickableItemContainerBlock; import eu.pb4.polydecorations.entity.StatueEntity; @@ -36,18 +37,18 @@ public class DecorationsItems { - public static final Item TROWEL = register("trowel", (settings) -> new TrowelItem(settings + public static final Item TROWEL = DecorationsFeature.TROWEL.isRegistered() ? register("trowel", (settings) -> new TrowelItem(settings .attributes(ItemAttributeModifiers.builder() .add(Attributes.BLOCK_INTERACTION_RANGE, new AttributeModifier(id("trowel_bonus"), 1, AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND).build()) - .stacksTo(1))); + .stacksTo(1))) : null; - public static final Item HAMMER = register("hammer", (settings) -> new HammerItem(settings.stacksTo(1))); + public static final Item HAMMER = DecorationsFeature.HAMMER.isRegistered() ? register("hammer", (settings) -> new HammerItem(settings.stacksTo(1))) : null; public static final Item BRAZIER = register(DecorationsBlocks.BRAZIER); public static final Item SOUL_BRAZIER = register(DecorationsBlocks.SOUL_BRAZIER); public static final Item COPPER_BRAZIER = register(DecorationsBlocks.COPPER_BRAZIER); public static final Item COPPER_CAMPFIRE = register(DecorationsBlocks.COPPER_CAMPFIRE ); public static final Item GLOBE = register(DecorationsBlocks.GLOBE); - public static final Item WIND_CHIME = register("wind_chime", (s) -> new WindChimeItem(DecorationsBlocks.WIND_CHIME, s.useBlockDescriptionPrefix())); + public static final Item WIND_CHIME = DecorationsFeature.WIND_CHIME.isRegistered() ? register("wind_chime", (s) -> new WindChimeItem(DecorationsBlocks.WIND_CHIME, s.useBlockDescriptionPrefix())) : null; public static final Item TRASHCAN = register(DecorationsBlocks.TRASHCAN); public static final Item BASKET = register(DecorationsBlocks.BASKET, s -> s.stacksTo(1)); public static final Item CARDBOARD_BOX = register(DecorationsBlocks.CARDBOARD_BOX, s -> s.stacksTo(1)); @@ -58,24 +59,24 @@ public class DecorationsItems { public static final Map WOODEN_MAILBOX = registerWood(DecorationsBlocks.WOODEN_MAILBOX); public static final Map STUMP = registerWood(DecorationsBlocks.STUMP); public static final Map STRIPPED_STUMP = registerWood(DecorationsBlocks.STRIPPED_STUMP); - public static final Map SIGN_POST = registerWood("sign_post", (x) -> (settings) -> new SignPostItem(settings.useBlockDescriptionPrefix())); - public static final Map WOODEN_STATUE = registerWood("statue", (x) -> { + public static final Map SIGN_POST = DecorationsFeature.SIGN_POST.isRegistered() ? registerWood("sign_post", (x) -> (settings) -> new SignPostItem(settings.useBlockDescriptionPrefix())) : Map.of(); + public static final Map WOODEN_STATUE = DecorationsFeature.STATUES.isRegistered() ? registerWood("statue", (x) -> { var planks = BuiltInRegistries.BLOCK.getValue(Identifier.parse(x.name() + "_planks")); return (settings) -> new StatueItem(StatueEntity.Type.of(WoodUtil.asPath(x), planks, false), settings.stacksTo(16)); - }); + }) : Map.of(); public static final Map SLEEPING_BAG = register(DecorationsBlocks.SLEEPING_BAG, DyeColor::name, x -> x.stacksTo(1)); public static final Item GHOST_LIGHT = register(DecorationsBlocks.GHOST_LIGHT); public static final Item BURNING_GHOST_LIGHT = register(DecorationsBlocks.BURNING_GHOST_LIGHT); public static final Item COPPER_GHOST_LIGHT = register(DecorationsBlocks.COPPER_GHOST_LIGHT); public static final Item DISPLAY_CASE = register(DecorationsBlocks.DISPLAY_CASE); - public static final Item ROPE = register("rope", (settings) -> new RopeItem(DecorationsBlocks.ROPE, settings.useBlockDescriptionPrefix())); + public static final Item ROPE = DecorationsFeature.ROPE.isRegistered() ? register("rope", (settings) -> new RopeItem(DecorationsBlocks.ROPE, settings.useBlockDescriptionPrefix())) : null; public static final Item LARGE_FLOWER_POT = register(DecorationsBlocks.LARGE_FLOWER_POT); public static final Item LONG_FLOWER_POT = register(DecorationsBlocks.LONG_FLOWER_POT); - public static final Item CANVAS = register("canvas", (settings) -> new CanvasItem(settings.stacksTo(16))); - public static final Map OTHER_STATUE = registerList(StatueEntity.Type.NON_WOOD, + public static final Item CANVAS = DecorationsFeature.CANVAS.isRegistered() ? register("canvas", (settings) -> new CanvasItem(settings.stacksTo(16))) : null; + public static final Map OTHER_STATUE = DecorationsFeature.STATUES.isRegistered() ? registerList(StatueEntity.Type.NON_WOOD, (t) -> t.type() + "_statue", - (t) -> (settings) -> new StatueItem(t, settings.stacksTo(16))); + (t) -> (settings) -> new StatueItem(t, settings.stacksTo(16))) : Map.of(); private static > Map register(Map blockMap, Function toComparable) { return register(blockMap, toComparable, (s) -> {}); @@ -100,33 +101,46 @@ private static Map registerList(List list, Function } public static void register() { + var icon = BENCH.containsKey(WoodType.OAK) ? BENCH.get(WoodType.OAK) : BuiltInRegistries.ITEM.stream() + .filter(x -> BuiltInRegistries.ITEM.getKey(x).getNamespace().equals(ModInit.ID)).findFirst().orElse(null); + if (icon == null) { + return; + } + PolymerCreativeModeTabUtils.registerPolymerCreativeModeTab(Identifier.fromNamespaceAndPath(ModInit.ID, "a_group"), PolymerCreativeModeTabUtils.builder() - .icon(() -> BENCH.get(WoodType.OAK).getDefaultInstance()) + .icon(icon::getDefaultInstance) .title(Component.translatable("itemgroup." + ModInit.ID)) .displayItems(((context, entries) -> { - entries.accept(TROWEL); - entries.accept(HAMMER); - entries.accept(BRAZIER); - entries.accept(SOUL_BRAZIER); - entries.accept(COPPER_BRAZIER); - entries.accept(COPPER_CAMPFIRE); - entries.accept(GHOST_LIGHT); - entries.accept(BURNING_GHOST_LIGHT); - entries.accept(COPPER_GHOST_LIGHT); - entries.accept(LARGE_FLOWER_POT); - entries.accept(LONG_FLOWER_POT); - entries.accept(DISPLAY_CASE); - entries.accept(GLOBE); - entries.accept(WIND_CHIME); - entries.accept(TRASHCAN); - entries.accept(BASKET); - entries.accept(CARDBOARD_BOX); - entries.accept(ROPE); - entries.accept(CANVAS); - entries.accept(Items.LANTERN); - entries.accept(Items.SOUL_LANTERN); + Consumer accept = (item) -> { + if (item != null) { + entries.accept(item); + } + }; + accept.accept(TROWEL); + accept.accept(HAMMER); + accept.accept(BRAZIER); + accept.accept(SOUL_BRAZIER); + accept.accept(COPPER_BRAZIER); + accept.accept(COPPER_CAMPFIRE); + accept.accept(GHOST_LIGHT); + accept.accept(BURNING_GHOST_LIGHT); + accept.accept(COPPER_GHOST_LIGHT); + accept.accept(LARGE_FLOWER_POT); + accept.accept(LONG_FLOWER_POT); + accept.accept(DISPLAY_CASE); + accept.accept(GLOBE); + accept.accept(WIND_CHIME); + accept.accept(TRASHCAN); + accept.accept(BASKET); + accept.accept(CARDBOARD_BOX); + accept.accept(ROPE); + accept.accept(CANVAS); + if (DecorationsFeature.WALL_LANTERNS.isRegistered()) { + entries.accept(Items.LANTERN); + entries.accept(Items.SOUL_LANTERN); + } WoodUtil.forEach(List.of(BENCH, STUMP, STRIPPED_STUMP, TABLE, SHELF, TOOL_RACK, SIGN_POST, WOODEN_MAILBOX, WOODEN_STATUE), entries::accept); - DecorationsUtil.COLORS_CREATIVE.forEach(a -> entries.accept(SLEEPING_BAG.get(a))); + DecorationsUtil.COLORS_CREATIVE.forEach(a -> accept.accept(SLEEPING_BAG.get(a))); OTHER_STATUE.forEach((a, b) -> entries.accept(b)); })).build() ); @@ -182,6 +196,10 @@ public static BlockItem register(E block) { return register(block, (s) -> {}); } public static BlockItem register(E block, Consumer settingsConsumer) { + if (block == null) { + // Block's feature is disabled + return null; + } var id = BuiltInRegistries.BLOCK.getKey(block); BlockItem item; var settings = new Item.Properties().setId(ResourceKey.create(Registries.ITEM, id)).useBlockDescriptionPrefix(); diff --git a/src/main/java/eu/pb4/polydecorations/mixin/LanternBlockMixin.java b/src/main/java/eu/pb4/polydecorations/mixin/LanternBlockMixin.java index 909ba72..2e5b703 100644 --- a/src/main/java/eu/pb4/polydecorations/mixin/LanternBlockMixin.java +++ b/src/main/java/eu/pb4/polydecorations/mixin/LanternBlockMixin.java @@ -1,5 +1,6 @@ package eu.pb4.polydecorations.mixin; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.ModCompatStatus; import eu.pb4.polydecorations.block.DecorationsBlocks; import eu.pb4.polydecorations.block.extension.WallAttachedLanternBlock; @@ -23,7 +24,7 @@ public abstract class LanternBlockMixin { @Inject(method = "getStateForPlacement", at = @At("HEAD"), cancellable = true) private void swapByDefault(BlockPlaceContext ctx, CallbackInfoReturnable cir) { - if (ModCompatStatus.AURORALANTERNS || !ctx.isSecondaryUseActive() || ctx.getClickedFace().getAxis() == Direction.Axis.Y) { + if (ModCompatStatus.AURORALANTERNS || !DecorationsFeature.WALL_LANTERNS.isEnabled() || !ctx.isSecondaryUseActive() || ctx.getClickedFace().getAxis() == Direction.Axis.Y) { return; } var pos = ctx.getClickedPos().relative(ctx.getClickedFace(), -1); @@ -43,7 +44,7 @@ private void swapByDefault(BlockPlaceContext ctx, CallbackInfoReturnable cir) { - if (ModCompatStatus.AURORALANTERNS || cir.getReturnValue() != null || ctx.getClickedFace().getAxis() == Direction.Axis.Y) { + if (ModCompatStatus.AURORALANTERNS || !DecorationsFeature.WALL_LANTERNS.isEnabled() || cir.getReturnValue() != null || ctx.getClickedFace().getAxis() == Direction.Axis.Y) { return; } var pos = ctx.getClickedPos().relative(ctx.getClickedFace(), -1); @@ -64,7 +65,7 @@ private void swapNullForWallAttached(BlockPlaceContext ctx, CallbackInfoReturnab @Inject(method = "canSurvive", at = @At("RETURN"), cancellable = true) private void attachToRopes(BlockState state, LevelReader world, BlockPos pos, CallbackInfoReturnable cir) { - if (state.getValue(HANGING) && world.getBlockState(pos.relative(Direction.UP)).is(DecorationsBlocks.ROPE)) { + if (DecorationsFeature.ROPE.isRegistered() && state.getValue(HANGING) && world.getBlockState(pos.relative(Direction.UP)).is(DecorationsBlocks.ROPE)) { cir.setReturnValue(true); } } diff --git a/src/main/java/eu/pb4/polydecorations/mixin/LeadItemMixin.java b/src/main/java/eu/pb4/polydecorations/mixin/LeadItemMixin.java index 62dac7a..0658fad 100644 --- a/src/main/java/eu/pb4/polydecorations/mixin/LeadItemMixin.java +++ b/src/main/java/eu/pb4/polydecorations/mixin/LeadItemMixin.java @@ -3,6 +3,7 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Local; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.entity.DecorationsEntities; import eu.pb4.polydecorations.entity.FirstLeashFenceKnotEntity; import net.minecraft.core.BlockPos; @@ -27,7 +28,7 @@ private InteractionResult handleLeadToFence(Player player, Level level, BlockPos List list = Leashable.leashableInArea(level, Vec3.atCenterOf(blockPos), (leashablex) -> leashablex.getLeashHolder() == player); var state = level.getBlockState(blockPos); - if (!list.isEmpty() || !state.is(BlockTags.FENCES)) { + if (!DecorationsFeature.FENCE_LEADS.isEnabled() || !list.isEmpty() || !state.is(BlockTags.FENCES)) { return original.call(player, level, blockPos); } diff --git a/src/main/java/eu/pb4/polydecorations/mixin/ShulkerBoxBlockEntityMixin.java b/src/main/java/eu/pb4/polydecorations/mixin/ShulkerBoxBlockEntityMixin.java index 2c14a0f..d04d4de 100644 --- a/src/main/java/eu/pb4/polydecorations/mixin/ShulkerBoxBlockEntityMixin.java +++ b/src/main/java/eu/pb4/polydecorations/mixin/ShulkerBoxBlockEntityMixin.java @@ -2,6 +2,7 @@ import com.llamalad7.mixinextras.injector.ModifyReturnValue; import com.llamalad7.mixinextras.sugar.Local; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.item.DecorationsDataComponents; import eu.pb4.polydecorations.item.DecorationsItems; import net.minecraft.core.BlockPos; @@ -25,12 +26,12 @@ public ShulkerBoxBlockEntityMixin(BlockEntityType blockEntityType, BlockPos b @ModifyReturnValue(method = "canPlaceItemThroughFace", at = @At("RETURN")) private boolean patchNesting(boolean original, @Local(argsOnly = true) ItemStack stack) { - return original && !stack.is(DecorationsItems.BASKET); + return original && !(DecorationsFeature.BASKET.isRegistered() && stack.is(DecorationsItems.BASKET)); } @Inject(method = "startOpen", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;blockEvent(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;II)V")) private void removeTiesOnOpen(ContainerUser containerUser, CallbackInfo ci) { - if (this.components().has(DecorationsDataComponents.TIED)) { + if (DecorationsFeature.TIED_CONTAINERS.isRegistered() && this.components().has(DecorationsDataComponents.TIED)) { this.setComponents(DataComponentMap.builder().addAll(this.components()).set(DecorationsDataComponents.TIED, null).build()); } } diff --git a/src/main/java/eu/pb4/polydecorations/patch/DecorationsLootTablePatches.java b/src/main/java/eu/pb4/polydecorations/patch/DecorationsLootTablePatches.java index 2dec3a6..f710c80 100644 --- a/src/main/java/eu/pb4/polydecorations/patch/DecorationsLootTablePatches.java +++ b/src/main/java/eu/pb4/polydecorations/patch/DecorationsLootTablePatches.java @@ -1,5 +1,6 @@ package eu.pb4.polydecorations.patch; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.item.DecorationsDataComponents; import net.fabricmc.fabric.api.loot.v3.LootTableEvents; import net.minecraft.core.Holder; @@ -14,7 +15,9 @@ public class DecorationsLootTablePatches { public static void register() { - LootTableEvents.MODIFY_DROPS.register(DecorationsLootTablePatches::modifyDrops); + if (DecorationsFeature.TIED_CONTAINERS.isRegistered()) { + LootTableEvents.MODIFY_DROPS.register(DecorationsLootTablePatches::modifyDrops); + } } private static void modifyDrops(Holder lootTableHolder, LootContext lootContext, List itemStacks) { diff --git a/src/main/java/eu/pb4/polydecorations/polydex/PolydexCompatImpl.java b/src/main/java/eu/pb4/polydecorations/polydex/PolydexCompatImpl.java index e430aaa..1f6165c 100644 --- a/src/main/java/eu/pb4/polydecorations/polydex/PolydexCompatImpl.java +++ b/src/main/java/eu/pb4/polydecorations/polydex/PolydexCompatImpl.java @@ -19,7 +19,9 @@ public class PolydexCompatImpl { public static void register() { - HoverDisplayBuilder.register(DecorationsBlocks.DISPLAY_CASE, PolydexCompatImpl::replaceName); + if (DecorationsBlocks.DISPLAY_CASE != null) { + HoverDisplayBuilder.register(DecorationsBlocks.DISPLAY_CASE, PolydexCompatImpl::replaceName); + } } private static void replaceName(HoverDisplayBuilder builder) { diff --git a/src/main/java/eu/pb4/polydecorations/util/DecorationsUtil.java b/src/main/java/eu/pb4/polydecorations/util/DecorationsUtil.java index 7dcd869..bf9a7ea 100644 --- a/src/main/java/eu/pb4/polydecorations/util/DecorationsUtil.java +++ b/src/main/java/eu/pb4/polydecorations/util/DecorationsUtil.java @@ -1,6 +1,7 @@ package eu.pb4.polydecorations.util; import com.mojang.authlib.GameProfile; +import eu.pb4.polydecorations.DecorationsFeature; import eu.pb4.polydecorations.ModInit; import eu.pb4.polymer.blocks.api.BlockModelType; import eu.pb4.polymer.blocks.api.PolymerBlockResourceUtils; @@ -48,19 +49,23 @@ public class DecorationsUtil { private static final List RUN_NEXT_TICK = new ArrayList<>(); - public static final Map TRAPDOOR_STATES_REGULAR = Util.makeEnumMap(Direction.class, x -> PolymerBlockResourceUtils.requestEmpty(BlockModelType.valueOf("TRAPDOOR_" + switch (x) { + public static final Map TRAPDOOR_STATES_REGULAR = DecorationsFeature.anyRegistered(DecorationsFeature.TOOL_RACK, DecorationsFeature.SLEEPING_BAG) + ? Util.makeEnumMap(Direction.class, x -> PolymerBlockResourceUtils.requestEmpty(BlockModelType.valueOf("TRAPDOOR_" + switch (x) { case UP -> "BOTTOM"; case DOWN -> "TOP"; default -> x.getSerializedName().toUpperCase(Locale.ROOT); - }))); - public static final Map TRAPDOOR_STATES_WATERLOGGED = Util.makeEnumMap(Direction.class, x -> PolymerBlockResourceUtils.requestEmpty(BlockModelType.valueOf("TRAPDOOR_" + switch (x) { + }))) : Map.of(); + public static final Map TRAPDOOR_STATES_WATERLOGGED = DecorationsFeature.TOOL_RACK.isRegistered() + ? Util.makeEnumMap(Direction.class, x -> PolymerBlockResourceUtils.requestEmpty(BlockModelType.valueOf("TRAPDOOR_" + switch (x) { case UP -> "BOTTOM"; case DOWN -> "TOP"; default -> x.getSerializedName().toUpperCase(Locale.ROOT); - } + "_WATERLOGGED"))); + } + "_WATERLOGGED"))) : Map.of(); - public static final BlockState CAMPFIRE_STATE = PolymerBlockResourceUtils.requestEmpty(BlockModelType.CAMPFIRE); - public static final BlockState CAMPFIRE_WATERLOGGED_STATE = PolymerBlockResourceUtils.requestEmpty(BlockModelType.CAMPFIRE_WATERLOGGED); + public static final BlockState CAMPFIRE_STATE = DecorationsFeature.anyRegistered(DecorationsFeature.BENCH, DecorationsFeature.BASKET, DecorationsFeature.COPPER_CAMPFIRE, DecorationsFeature.FLOWER_POTS) + ? PolymerBlockResourceUtils.requestEmpty(BlockModelType.CAMPFIRE) : null; + public static final BlockState CAMPFIRE_WATERLOGGED_STATE = DecorationsFeature.anyRegistered(DecorationsFeature.BENCH, DecorationsFeature.BASKET, DecorationsFeature.COPPER_CAMPFIRE) + ? PolymerBlockResourceUtils.requestEmpty(BlockModelType.CAMPFIRE_WATERLOGGED) : null; public static void runNextTick(Runnable runnable) { RUN_NEXT_TICK.add(runnable); diff --git a/src/main/java/eu/pb4/polydecorations/util/FeatureAssetFilter.java b/src/main/java/eu/pb4/polydecorations/util/FeatureAssetFilter.java new file mode 100644 index 0000000..314b94c --- /dev/null +++ b/src/main/java/eu/pb4/polydecorations/util/FeatureAssetFilter.java @@ -0,0 +1,128 @@ +package eu.pb4.polydecorations.util; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import eu.pb4.polydecorations.DecorationsFeature; +import eu.pb4.polydecorations.ModInit; +import eu.pb4.polymer.resourcepack.api.PackResource; +import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.function.Function; + +public class FeatureAssetFilter { + private static final String ASSETS = "assets/" + ModInit.ID + "/"; + private static final String NAMESPACE = ModInit.ID + ":"; + private static final List TYPE_PREFIXES = List.of("items/-/block/", "items/-/", "items/", "models/block/", "models/item/", "models/", + "textures/block/", "textures/item/", "textures/"); + + public static void register() { + if (DecorationsFeature.anyHardDisabled()) { + PolymerResourcePackUtils.RESOURCE_PACK_CREATION_EVENT.register(builder -> builder.addResourceConverter(FeatureAssetFilter::convert)); + } + } + + @Nullable + private static PackResource convert(String path, PackResource resource) { + if (path.startsWith("assets/minecraft/atlases/") && path.endsWith(".json")) { + return filterAtlas(resource); + } else if (!path.startsWith(ASSETS)) { + return resource; + } + + var local = path.substring(ASSETS.length()); + if (local.startsWith("lang/") && local.endsWith(".json")) { + return filterKeys(resource, FeatureAssetFilter::translationName); + } else if (local.equals("sounds.json")) { + return filterKeys(resource, FeatureAssetFilter::soundName); + } else if (!DecorationsFeature.isUsed(assetName(local))) { + return null; + } else if (local.startsWith("font/") && local.endsWith(".json")) { + return filterFont(resource); + } + return resource; + } + + // models/block/oak_bench_left.json -> oak_bench_left + public static String assetName(String path) { + for (var extension : List.of(".png.mcmeta", ".png", ".json")) { + if (path.endsWith(extension)) { + path = path.substring(0, path.length() - extension.length()); + break; + } + } + for (var prefix : TYPE_PREFIXES) { + if (path.startsWith(prefix)) { + return path.substring(prefix.length()); + } + } + return path; + } + + private static boolean isTextureUsed(String texture) { + return !texture.startsWith(NAMESPACE) || DecorationsFeature.isUsed(assetName("textures/" + texture.substring(NAMESPACE.length()))); + } + + // block.polydecorations.oak_bench -> oak_bench, subtitles.polydecorations.block.trashcan.open -> trashcan + @Nullable + private static String translationName(String key) { + var parts = key.split("\\."); + if (parts.length < 3 || !parts[1].equals(ModInit.ID)) { + return null; + } + var index = parts[0].equals("subtitles") ? 3 : 2; + return index < parts.length ? parts[index] : null; + } + + // block.trashcan.open -> trashcan + @Nullable + private static String soundName(String key) { + var parts = key.split("\\."); + return parts.length > 1 ? parts[1] : null; + } + + private static PackResource filterKeys(PackResource resource, Function nameGetter) { + var json = resource.asJson().getAsJsonObject(); + var removed = json.keySet().removeIf(key -> { + var name = nameGetter.apply(key); + return name != null && !DecorationsFeature.isUsed(name); + }); + return removed ? PackResource.fromJson(json) : resource; + } + + private static PackResource filterFont(PackResource resource) { + var json = resource.asJson().getAsJsonObject(); + if (!json.has("providers")) { + return resource; + } + var providers = json.getAsJsonArray("providers"); + var removed = providers.asList().removeIf(provider -> provider instanceof JsonObject object + && object.has("file") && !isTextureUsed(object.get("file").getAsString().replace(".png", ""))); + return removed ? PackResource.fromJson(json) : resource; + } + + private static PackResource filterAtlas(PackResource resource) { + var json = resource.asJson().getAsJsonObject(); + if (!json.has("sources")) { + return resource; + } + var changed = false; + for (var iterator = json.getAsJsonArray("sources").iterator(); iterator.hasNext(); ) { + if (!(iterator.next() instanceof JsonObject source)) { + continue; + } + if (source.has("resource") && !isTextureUsed(source.get("resource").getAsString())) { + iterator.remove(); + changed = true; + } else if (source.get("textures") instanceof JsonArray textures + && textures.asList().removeIf(texture -> !isTextureUsed(texture.getAsString()))) { + changed = true; + if (textures.isEmpty()) { + iterator.remove(); + } + } + } + return changed ? PackResource.fromJson(json) : resource; + } +} diff --git a/src/main/java/eu/pb4/polydecorations/util/FeatureResourceCondition.java b/src/main/java/eu/pb4/polydecorations/util/FeatureResourceCondition.java new file mode 100644 index 0000000..c46e023 --- /dev/null +++ b/src/main/java/eu/pb4/polydecorations/util/FeatureResourceCondition.java @@ -0,0 +1,44 @@ +package eu.pb4.polydecorations.util; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.MapCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import eu.pb4.polydecorations.DecorationsFeature; +import net.fabricmc.fabric.api.resource.conditions.v1.ResourceCondition; +import net.fabricmc.fabric.api.resource.conditions.v1.ResourceConditionType; +import net.fabricmc.fabric.api.resource.conditions.v1.ResourceConditions; +import net.minecraft.resources.RegistryOps; +import org.jetbrains.annotations.Nullable; + +import static eu.pb4.polydecorations.ModInit.id; + +// {"condition": "polydecorations:feature", "feature": "bench"} passes if the feature is enabled, +// with "registered": true it passes as long as the feature isn't hard disabled +public record FeatureResourceCondition(DecorationsFeature feature, boolean registered) implements ResourceCondition { + private static final Codec FEATURE_CODEC = Codec.STRING.comapFlatMap(key -> { + var feature = DecorationsFeature.byKey(key); + return feature != null ? DataResult.success(feature) : DataResult.error(() -> "Unknown feature '" + key + "'"); + }, DecorationsFeature::key); + + public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(instance -> instance.group( + FEATURE_CODEC.fieldOf("feature").forGetter(FeatureResourceCondition::feature), + Codec.BOOL.optionalFieldOf("registered", false).forGetter(FeatureResourceCondition::registered) + ).apply(instance, FeatureResourceCondition::new)); + + public static final ResourceConditionType TYPE = ResourceConditionType.create(id("feature"), CODEC); + + public static void register() { + ResourceConditions.register(TYPE); + } + + @Override + public ResourceConditionType getType() { + return TYPE; + } + + @Override + public boolean test(@Nullable RegistryOps.RegistryInfoLookup registryInfo) { + return this.registered ? this.feature.isRegistered() : this.feature.isEnabled(); + } +} diff --git a/src/main/resources/polydecorations.mixins.json b/src/main/resources/polydecorations.mixins.json index edaea3c..ad5a6bd 100644 --- a/src/main/resources/polydecorations.mixins.json +++ b/src/main/resources/polydecorations.mixins.json @@ -2,6 +2,7 @@ "required": true, "minVersion": "0.8", "package": "eu.pb4.polydecorations.mixin", + "plugin": "eu.pb4.polydecorations.DecorationsMixinPlugin", "compatibilityLevel": "JAVA_21", "mixins": [ "BlockItemMixin",