1.21.3 update

This commit is contained in:
LexManos committed 2024-10-25 18:04:34 -07:00
1 parent c22589b5b3
commit 086bcb7148
806 files changed
+6314 -10501

No files matched your search

@@ -72,7 +72,7 @@ public final class CreativeModeTabRegistry {
*/
@Nullable
public static CreativeModeTab getTab(ResourceLocation name) {
return BuiltInRegistries.CREATIVE_MODE_TAB.get(name);
return BuiltInRegistries.CREATIVE_MODE_TAB.getValue(name);
}
/**
@@ -178,14 +178,15 @@ public final class CreativeModeTabRegistry {
public static void sortTabs() {
edges.clear();
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.HOTBAR));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.SEARCH));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.OP_BLOCKS));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.get(CreativeModeTabs.INVENTORY));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.HOTBAR));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.SEARCH));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.OP_BLOCKS));
DEFAULT_TABS.add(BuiltInRegistries.CREATIVE_MODE_TAB.getValue(CreativeModeTabs.INVENTORY));
final List<Holder<CreativeModeTab>> indexed = BuiltInRegistries.CREATIVE_MODE_TAB.holders()
.filter(c -> !DEFAULT_TABS.contains(c.get()))
.collect(Collectors.toList());
final List<? extends Holder<CreativeModeTab>> indexed = BuiltInRegistries.CREATIVE_MODE_TAB
.listElements()
.filter(c -> !DEFAULT_TABS.contains(c.get()))
.toList();
int vanillaTabs = 10;
for (int i = 0; i < vanillaTabs; i++) { // Vanilla ordering
@@ -104,9 +104,6 @@ public class ForgeConfig {
public final BooleanValue calculateAllNormals;
public final BooleanValue stabilizeDirectionGetNearest;
Client(ForgeConfigSpec.Builder builder) {
builder.comment("Client only settings, mostly things related to rendering")
.push("client");
@@ -142,11 +139,6 @@ public class ForgeConfig {
.translation("forge.configgui.calculateAllNormals")
.define("calculateAllNormals", false);
stabilizeDirectionGetNearest = builder
.comment("When enabled, a slightly biased Direction#getNearest calculation will be used to prevent normal fighting on 45 degree angle faces.")
.translation("forge.configgui.stabilizeDirectionGetNearest")
.define("stabilizeDirectionGetNearest", true);
builder.pop();
}
@@ -16,6 +16,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@@ -40,15 +41,12 @@ import com.mojang.serialization.Lifecycle;
import io.netty.handler.codec.DecoderException;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.commands.arguments.selector.EntitySelectorParser;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.NonNullList;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.particles.ParticleTypes;
@@ -56,12 +54,12 @@ import net.minecraft.core.registries.Registries;
import net.minecraft.network.Connection;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.VarInt;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.TextColor;
import net.minecraft.network.chat.contents.PlainTextContents.LiteralContents;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.TagKey;
@@ -80,11 +78,10 @@ import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.Brain;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.inventory.ContainerLevelAccess;
import net.minecraft.world.item.*;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.material.Fluids;
@@ -92,6 +89,7 @@ import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.WorldData;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootPool;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.entity.item.ItemEntity;
@@ -113,7 +111,6 @@ import net.minecraft.network.protocol.login.ClientboundCustomQueryPacket;
import net.minecraft.network.protocol.login.ServerboundCustomQueryAnswerPacket;
import net.minecraft.stats.Stats;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.level.block.entity.FurnaceBlockEntity;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.level.biome.Biome;
@@ -139,7 +136,7 @@ import net.minecraftforge.event.RegisterStructureConversionsEvent;
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
import net.minecraftforge.event.entity.EntityAttributeModificationEvent;
import net.minecraftforge.event.entity.item.ItemTossEvent;
import net.minecraftforge.event.entity.living.EnderManAngerEvent;
import net.minecraftforge.event.entity.living.MonsterDisguiseEvent;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.living.LivingBreatheEvent;
import net.minecraftforge.event.entity.living.LivingDamageEvent;
@@ -183,7 +180,6 @@ import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import net.minecraft.ChatFormatting;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.damagesource.DamageSource;
@@ -551,8 +547,9 @@ public final class ForgeHooks {
@NotNull
public static ItemStack getCraftingRemainingItem(@NotNull ItemStack stack) {
if (stack.getItem().hasCraftingRemainingItem(stack)) {
stack = stack.getItem().getCraftingRemainingItem(stack);
var remainder = stack.getCraftingRemainder();
if (!remainder.isEmpty()) {
stack = remainder;
if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage()) {
ForgeEventFactory.onPlayerDestroyItem(CRAFTING_PLAYER.get(), stack, (EquipmentSlot)null);
return ItemStack.EMPTY;
@@ -674,7 +671,7 @@ public final class ForgeHooks {
ResourceLocation registryName = ForgeRegistries.ITEMS.getKey(item);
String modId = registryName == null ? null : registryName.getNamespace();
if ("minecraft".equals(modId)) {
if (item instanceof EnchantedBookItem) {
if (itemStack.is(Items.ENCHANTED_BOOK)) {
var enchants = EnchantmentHelper.getEnchantmentsForCrafting(itemStack);
if (enchants.size() == 1) {
var enchant = enchants.keySet().iterator().next();
@@ -695,12 +692,9 @@ public final class ForgeHooks {
return modId;
}
public static boolean onFarmlandTrample(Level level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
if (entity.canTrample(state, pos, fallDistance)) {
BlockEvent.FarmlandTrampleEvent event = new BlockEvent.FarmlandTrampleEvent(level, pos, state, fallDistance, entity);
MinecraftForge.EVENT_BUS.post(event);
return !event.isCanceled();
}
public static boolean onFarmlandTrample(ServerLevel level, BlockPos pos, BlockState state, float fallDistance, Entity entity) {
if (entity.canTrample(level, state, pos, fallDistance))
return !ForgeEventFactory.fireFarmlandTrampleEvent(level, pos, state, fallDistance, entity);
return false;
}
@@ -711,17 +705,6 @@ public final class ForgeHooks {
return event.getVanillaNoteId();
}
public static boolean hasNoElements(Ingredient ingredient) {
ItemStack[] items = ingredient.getItems();
if (items.length == 0) return true;
if (items.length == 1) {
//If we potentially added a barrier due to the ingredient being an empty tag, try and check if it is the stack we added
ItemStack item = items[0];
return item.getItem() == Items.BARRIER && item.getHoverName() instanceof MutableComponent hoverName && hoverName.getString().startsWith("Empty Tag: ");
}
return false;
}
@Nullable
public static EntityDataSerializer<?> getSerializer(int id, CrudeIncrementalIntIdentityHashBiMap<EntityDataSerializer<?>> vanilla) {
EntityDataSerializer<?> serializer = vanilla.byId(id);
@@ -745,34 +728,13 @@ public final class ForgeHooks {
return id;
}
public static boolean canEntityDestroy(Level level, BlockPos pos, LivingEntity entity) {
public static boolean canEntityDestroy(ServerLevel level, BlockPos pos, LivingEntity entity) {
if (!level.isLoaded(pos))
return false;
BlockState state = level.getBlockState(pos);
return ForgeEventFactory.getMobGriefingEvent(level, entity) && state.canEntityDestroy(level, pos, entity) && ForgeEventFactory.onEntityDestroyBlock(entity, pos, state);
}
private static final Map<Holder.Reference<Item>, Integer> VANILLA_BURNS = new HashMap<>();
/**
* Gets the burn time of this itemstack.
*/
public static int getBurnTime(ItemStack stack, @Nullable RecipeType<?> recipeType) {
if (stack.isEmpty())
return 0;
else {
Item item = stack.getItem();
int ret = stack.getBurnTime(recipeType);
return ForgeEventFactory.getItemBurnTime(stack, ret == -1 ? VANILLA_BURNS.getOrDefault(ForgeRegistries.ITEMS.getDelegateOrThrow(item), 0) : ret, recipeType);
}
}
@SuppressWarnings("deprecation")
public static synchronized void updateBurns() {
VANILLA_BURNS.clear();
FurnaceBlockEntity.getFuel().forEach((k, v) -> VANILLA_BURNS.put(ForgeRegistries.ITEMS.getDelegateOrThrow(k), v));
}
/**
* Handles the modification of loot table drops via the registered Global Loot Modifiers,
* so that custom effects can be processed.
@@ -787,10 +749,10 @@ public final class ForgeHooks {
* @apiNote The given context will be modified by this method to also store the ID of the
* loot table being queried.
*/
public static ObjectArrayList<ItemStack> modifyLoot(ResourceLocation lootTableId, ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
context.setQueriedLootTableId(lootTableId); // In case the ID was set via copy constructor, this will be ignored: intended
public static ObjectArrayList<ItemStack> modifyLoot(LootTable table, ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
context.setQueriedLootTableId(table.getLootTableId()); // In case the ID was set via copy constructor, this will be ignored: intended
for (var mod : ForgeInternalHandler.getLootModifierManager().getAllLootMods())
generatedLoot = mod.apply(generatedLoot, context);
generatedLoot = mod.apply(table, generatedLoot, context);
return generatedLoot;
}
@@ -976,8 +938,14 @@ public final class ForgeHooks {
throw new IllegalArgumentException("Unknown lifecycle.");
}
public static boolean shouldSuppressEnderManAnger(EnderMan enderMan, Player player, ItemStack mask) {
return mask.isEnderMask(player, enderMan) || MinecraftForge.EVENT_BUS.post(new EnderManAngerEvent(enderMan, player));
public static Predicate<LivingEntity> isNotDisguised(Monster monster) {
return (entity) -> {
if (!(entity instanceof Player player))
return true;
var mask = player.getItemBySlot(EquipmentSlot.HEAD);
return !mask.isMonsterDisguise(player, monster) || MinecraftForge.EVENT_BUS.post(new MonsterDisguiseEvent(monster, player));
};
}
private static final Lazy<Map<String, StructuresBecomeConfiguredFix.Conversion>> FORGE_CONVERSION_MAP = Lazy.concurrentOf(() -> {
@@ -1031,6 +999,7 @@ public final class ForgeHooks {
* @param refillAirAmount The amount of air to refill when the entity is able to breathe
* @implNote This method needs to closely replicate the logic found right after the call site in {@link LivingEntity#baseTick()} as it overrides it.
*/
@SuppressWarnings("deprecation")
public static void onLivingBreathe(LivingEntity entity, int consumeAirAmount, int refillAirAmount) {
// Check things that vanilla considers to be air - these will cause the air supply to be increased.
boolean isAir = entity.getEyeInFluidType().isAir() || entity.level().getBlockState(BlockPos.containing(entity.getX(), entity.getEyeY(), entity.getZ())).is(Blocks.BUBBLE_COLUMN);
@@ -1160,14 +1129,14 @@ public final class ForgeHooks {
@ApiStatus.Internal
public static Packet<ClientGamePacketListener> getEntitySpawnPacket(Entity entity) {
if (!(entity instanceof IEntityAdditionalSpawnData add))
if (!(entity instanceof IEntityAdditionalSpawnData))
throw new IllegalArgumentException(entity.getClass() + " is not an instance of " + IEntityAdditionalSpawnData.class);
return NetworkDirection.PLAY_TO_CLIENT.buildPacket(NetworkInitialization.PLAY, new SpawnEntity(entity));
}
@ApiStatus.Internal
public static boolean readAndTestCondition(RegistryOps<JsonElement> ops, JsonObject json) {
public static boolean readAndTestCondition(DynamicOps<JsonElement> ops, JsonObject json) {
if (!json.has(ICondition.DEFAULT_FIELD))
return true;
@@ -1187,15 +1156,18 @@ public final class ForgeHooks {
@Nullable
@ApiStatus.Internal
public static JsonObject readConditionalAdvancement(RegistryOps<JsonElement> context, JsonObject json) {
var entries = GsonHelper.getAsJsonArray(json, "advancements", null);
public static JsonElement readConditional(DynamicOps<JsonElement> context, JsonElement json) {
if (!json.isJsonObject())
return json;
var entries = GsonHelper.getAsJsonArray(json.getAsJsonObject(), "forge:conditional", null);
if (entries == null)
return readAndTestCondition(context, json) ? json : null;
return readAndTestCondition(context, json.getAsJsonObject()) ? json : null;
int idx = 0;
for (var ele : entries) {
if (!ele.isJsonObject())
throw new JsonSyntaxException("Invalid advancement entry at index " + idx + " Must be JsonObject");
throw new JsonSyntaxException("Invalid forge:conditonal entry at index " + idx + " Must be JsonObject");
if (readAndTestCondition(context, ele.getAsJsonObject()))
return ele.getAsJsonObject();
@@ -1207,7 +1179,7 @@ public final class ForgeHooks {
}
@ApiStatus.Internal
public static Codec<Ingredient> enhanceIngredientCodec(Codec<Ingredient> vanilla) {
public static Codec<Ingredient> ingredientBaseCodec(Codec<Ingredient> vanilla) {
return Codec.lazyInitialized(() ->
Codec.<Ingredient, Ingredient>either(
ForgeRegistries.INGREDIENT_SERIALIZERS.get().getCodec().dispatch(Ingredient::serializer, IIngredientSerializer::codec),
@@ -1223,39 +1195,31 @@ public final class ForgeHooks {
public static StreamCodec<RegistryFriendlyByteBuf, Ingredient> ingredientStreamCodec() {
return StreamCodec.<RegistryFriendlyByteBuf, Ingredient>of(
(buf, value) -> {
if (value.isVanilla()) {
var items = value.getItems();
ByteBufCodecs.writeCount(buf, items.length, Integer.MAX_VALUE);
for (var item : items) {
ItemStack.STREAM_CODEC.encode(buf, item);
}
} else {
@SuppressWarnings("unchecked")
var serializer = (IIngredientSerializer<Ingredient>)value.serializer();
@SuppressWarnings("unchecked")
var serializer = (IIngredientSerializer<Ingredient>)value.serializer();
if (!value.isVanilla()) {
var key = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getKey(serializer);
if (key == null)
throw new IllegalArgumentException("Tried to write unregistered Ingredient to network: " + value);
buf.writeVarInt(-1); // Our Marker
buf.writeResourceLocation(key);
serializer.write(buf, value);
}
serializer.write(buf, value);
},
(buf) -> {
var size = ByteBufCodecs.readCount(buf, Integer.MAX_VALUE);
buf.markReaderIndex();
var size = VarInt.read(buf);
IIngredientSerializer<?> serializer = Ingredient.VANILLA_SERIALIZER;
if (size != -1) {
var ret = NonNullList.<ItemStack>createWithCapacity(size);
for (int x = 0; x < size; x++) {
ret.add(ItemStack.STREAM_CODEC.decode(buf));
}
return Ingredient.fromValues(ret.stream().map(Ingredient.ItemValue::new));
buf.resetReaderIndex();
} else {
var key = buf.readResourceLocation();
var serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key);
serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key);
if (serializer == null)
throw new DecoderException("Could not read ingredient of type: " + key);
return serializer.read(buf);
}
return serializer.read(buf);
}
);
}
@@ -24,7 +24,7 @@ import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
//TODO, this should be re-evaluated now that ITextComponents are passed everywhere instaed of strings.
//TODO, this should be re-evaluated now that ITextComponents are passed everywhere instead of strings.
public class ForgeI18n {
private static final Logger LOGGER = LogManager.getLogger();
// From FontRenderer.renderCharAtPos
@@ -18,16 +18,15 @@ import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.level.ChunkEvent;
import net.minecraftforge.event.network.ConnectionStartEvent;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.TagsUpdatedEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.TickEvent.ClientTickEvent;
import net.minecraftforge.event.TickEvent.ServerTickEvent;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.filters.NetworkFilters;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.server.command.ForgeCommand;
import net.minecraftforge.server.permission.events.PermissionGatherEvent;
import net.minecraftforge.server.command.ConfigCommand;
public class ForgeInternalHandler {
@@ -44,7 +43,7 @@ public class ForgeInternalHandler {
event.setCanceled(true);
@SuppressWarnings("resource")
var executor = LogicalSidedProvider.WORKQUEUE.get(event.getLevel().isClientSide ? LogicalSide.CLIENT : LogicalSide.SERVER);
executor.tell(new TickTask(0, () -> event.getLevel().addFreshEntity(newEntity)));
executor.schedule(new TickTask(0, () -> event.getLevel().addFreshEntity(newEntity)));
}
}
}
@@ -85,12 +84,6 @@ public class ForgeInternalHandler {
UsernameCache.setUsername(event.getEntity().getUUID(), event.getEntity().getGameProfile().getName());
}
@SubscribeEvent
public void tagsUpdated(TagsUpdatedEvent event) {
if (event.shouldUpdateStaticData())
ForgeHooks.updateBurns();
}
@SubscribeEvent
public void onCommandsRegister(RegisterCommandsEvent event) {
new ForgeCommand(event.getDispatcher());
@@ -126,5 +119,16 @@ public class ForgeInternalHandler {
public void onConnectionStart(ConnectionStartEvent event) {
NetworkFilters.injectIfNecessary(event.getConnection());
}
@SubscribeEvent
public void serverStopping(ServerStoppingEvent evt) {
WorldWorkerManager.clear();
}
@SubscribeEvent
public void registerPermissionNodes(PermissionGatherEvent.Nodes event) {
event.addNodes(ForgeMod.USE_SELECTORS_PERMISSION);
}
}
@@ -28,7 +28,6 @@ import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.RangedAttribute;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.BlockGetter;
@@ -62,8 +61,8 @@ import net.minecraftforge.common.world.ForgeBiomeModifiers.RemoveSpawnsBiomeModi
import net.minecraftforge.common.world.NoneBiomeModifier;
import net.minecraftforge.common.world.NoneStructureModifier;
import net.minecraftforge.common.world.StructureModifier;
import net.minecraftforge.event.TagsUpdatedEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fluids.ForgeFlowingFluid;
import net.minecraftforge.fml.*;
@@ -78,11 +77,10 @@ import net.minecraftforge.registries.holdersets.NotHolderSet;
import net.minecraftforge.registries.holdersets.OrHolderSet;
import net.minecraftforge.network.NetworkInitialization;
import net.minecraftforge.network.tasks.ForgeNetworkConfigurationHandler;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.event.entity.EntityAttributeModificationEvent;
import net.minecraftforge.data.event.GatherDataEvent;
import net.minecraftforge.server.command.EnumArgument;
import net.minecraftforge.server.command.ModIdArgument;
import net.minecraftforge.server.permission.events.PermissionGatherEvent;
import net.minecraftforge.server.permission.nodes.PermissionNode;
import net.minecraftforge.server.permission.nodes.PermissionTypes;
import net.minecraftforge.unsafe.UnsafeHacks;
@@ -393,25 +391,22 @@ public class ForgeMod {
modEventBus.addListener(this::gatherData);
modEventBus.addListener(this::registerFluids);
modEventBus.addListener(this::registerVanillaDisplayContexts);
for (DeferredRegister<?> r : registries) {
r.register(modEventBus);
}
modEventBus.addListener(this::onRegisterAttributes);
ForgeDeferredRegistriesSetup.setup(modEventBus);
for (var reg : registries)
reg.register(modEventBus);
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
context.registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
context.registerConfig(ModConfig.Type.SERVER, ForgeConfig.serverSpec);
context.registerConfig(ModConfig.Type.COMMON, ForgeConfig.commonSpec);
modEventBus.register(ForgeConfig.class);
ForgeDeferredRegistriesSetup.setup(modEventBus);
// Forge does not display problems when the remote is not matching.
context.registerDisplayTest(IExtensionPoint.DisplayTest.IGNORE_ALL_VERSION);
StartupMessageManager.addModMessage("Forge version "+ForgeVersion.getVersion());
MinecraftForge.EVENT_BUS.addListener(VillagerTradingManager::loadTrades);
MinecraftForge.EVENT_BUS.register(MinecraftForge.INTERNAL_HANDLER);
MinecraftForge.EVENT_BUS.addListener(this::mappingChanged);
MinecraftForge.EVENT_BUS.addListener(this::tagsUpdated);
MinecraftForge.EVENT_BUS.addListener(this::registerPermissionNodes);
MinecraftForge.EVENT_BUS.register(new ForgeNetworkConfigurationHandler());
ForgeRegistries.ITEMS.tags().addOptionalTagDefaults(Tags.Items.ENCHANTING_FUELS, Set.of(ForgeRegistries.ITEMS.getDelegateOrThrow(Items.LAPIS_LAZULI)));
@@ -426,16 +421,13 @@ public class ForgeMod {
//VanillaPacketSplitter.register();
}
public void serverStopping(ServerStoppingEvent evt) {
WorldWorkerManager.clear();
}
public void mappingChanged(IdMappingEvent evt) {
Ingredient.invalidateAll();
}
public void tagsUpdated(TagsUpdatedEvent evt) {
Ingredient.invalidateAll();
@SubscribeEvent
public void onRegisterAttributes(EntityAttributeModificationEvent event) {
for (var type : event.getTypes()) {
event.add(type, ForgeMod.SWIM_SPEED.getHolder().get());
event.add(type, ForgeMod.NAMETAG_DISTANCE.getHolder().get());
}
}
public void gatherData(GatherDataEvent event) {
@@ -457,7 +449,7 @@ public class ForgeMod {
gen.addProvider(event.includeServer(), new ForgeEntityTypeTagsProvider(packOutput, lookupProvider, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeFluidTagsProvider(packOutput, lookupProvider, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeEnchantmentTagsProvider(packOutput, lookupProvider, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeRecipeProvider(packOutput, lookupProvider));
gen.addProvider(event.includeServer(), new ForgeRecipeProvider.Runner(packOutput, lookupProvider));
gen.addProvider(event.includeServer(), new ForgeLootTableProvider(packOutput, lookupProvider));
gen.addProvider(event.includeServer(), new ForgeBiomeTagsProvider(packOutput, lookupProvider, existingFileHelper));
gen.addProvider(event.includeServer(), new ForgeStructureTagsProvider(packOutput, lookupProvider, existingFileHelper));
@@ -526,10 +518,6 @@ public class ForgeMod {
public static final PermissionNode<Boolean> USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors",
PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && player.hasPermissions(Commands.LEVEL_GAMEMASTERS));
public void registerPermissionNodes(PermissionGatherEvent.Nodes event) {
event.addNodes(USE_SELECTORS_PERMISSION);
}
/**
* TODO: Remove when {@link ForgeRegistry#addAlias(ResourceLocation, ResourceLocation)} is elevated to {@link IForgeRegistry}.
*/
@@ -7,10 +7,10 @@ package net.minecraftforge.common;
import net.minecraft.core.Direction;
import net.minecraft.core.dispenser.DispenseItemBehavior;
import net.minecraft.util.FastColor;
import net.minecraft.util.ARGB;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.MobSpawnType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SpawnEggItem;
import net.minecraft.world.level.block.DispenserBlock;
@@ -47,6 +47,7 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
return DEFAULT_DISPENSE_BEHAVIOR;
}
@SuppressWarnings("deprecation")
@Nullable
public static SpawnEggItem fromEntityType(@Nullable EntityType<?> type) {
SpawnEggItem ret = TYPE_MAP.get(type);
@@ -63,7 +64,7 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
EntityType<?> type = ((SpawnEggItem)stack.getItem()).getType(stack);
try {
type.spawn(source.level(), stack, null, source.pos().relative(face), MobSpawnType.DISPENSER, face != Direction.UP, false);
type.spawn(source.level(), stack, null, source.pos().relative(face), EntitySpawnReason.DISPENSER, face != Direction.UP, false);
} catch (Exception exception) {
DispenseItemBehavior.LOGGER.error("Error while dispensing spawn egg from dispenser at {}", source.pos(), exception);
return ItemStack.EMPTY;
@@ -95,8 +96,8 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
for (ForgeSpawnEggItem egg : MOD_EGGS) {
event.register((stack, layer) -> {
int color = egg.getColor(layer);
if (FastColor.ARGB32.alpha(color) == 0)
color = FastColor.ARGB32.opaque(color);
if (ARGB.alpha(color) == 0)
color = ARGB.opaque(color);
return color;
}, egg);
}
@@ -1,91 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Tier;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.block.Block;
import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier;
/**
* Helper class to define a custom tier
*/
@SuppressWarnings("ClassCanBeRecord") // can't make it a record because the method names will be obfuscated
public final class ForgeTier implements Tier {
private final int uses;
private final float speed;
private final float attackDamageBonus;
private final int enchantmentValue;
@NotNull
private final TagKey<Block> tag;
@NotNull
private final Supplier<Ingredient> repairIngredient;
@NotNull
public final TagKey<Block> incorrectBlocks;
public ForgeTier(int uses, float speed, float attackDamageBonus, int enchantmentValue,
@NotNull TagKey<Block> tag, @NotNull Supplier<Ingredient> repairIngredient,
@NotNull TagKey<Block> incorrectBlocks) {
this.uses = uses;
this.speed = speed;
this.attackDamageBonus = attackDamageBonus;
this.enchantmentValue = enchantmentValue;
this.tag = tag;
this.repairIngredient = repairIngredient;
this.incorrectBlocks = incorrectBlocks;
}
@Override
public int getUses() {
return this.uses;
}
@Override
public float getSpeed() {
return this.speed;
}
@Override
public float getAttackDamageBonus() {
return this.attackDamageBonus;
}
@Override
public int getEnchantmentValue() {
return this.enchantmentValue;
}
@NotNull
public TagKey<Block> getTag() {
return this.tag;
}
@Override
public TagKey<Block> getIncorrectBlocksForDrops() {
return this.incorrectBlocks;
}
@NotNull
@Override
public Ingredient getRepairIngredient() {
return this.repairIngredient.get();
}
@Override
public String toString() {
return "ForgeTier[" +
"uses=" + uses + ", " +
"speed=" + speed + ", " +
"attackDamageBonus=" + attackDamageBonus + ", " +
"enchantmentValue=" + enchantmentValue + ", " +
"tag=" + tag + ", " +
"incorrect=" + incorrectBlocks+ ", " +
"repairIngredient=" + repairIngredient + ']';
}
}
@@ -1,55 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
/**
* This class defines a replacement for the default minecart collision code.
* Only one handler can be registered at a time. It it registered with AbstractMinecartEntity.registerCollisionHandler().
* If you use this, make it a configuration option.
* @author CovertJaguar
*/
public interface IMinecartCollisionHandler
{
/**
* This basically replaces the function of the same name in EntityMinecart.
* Code in IMinecartHooks.applyEntityCollisionHook is still run.
* @param cart The cart that called the collision.
* @param other The object it collided with.
*/
void onEntityCollision(AbstractMinecart cart, Entity other);
/**
* This function replaced the function of the same name in EntityMinecart.
* It is used to define whether minecarts collide with specific entities,
* for example items.
* @param cart The cart for which the collision box was requested.
* @param other The entity requesting the collision box.
* @return The collision box or null.
*/
AABB getCollisionBox(AbstractMinecart cart, Entity other);
/**
* This function is used to define the box used for detecting minecart collisions.
* It is generally bigger that the normal collision box.
* @param cart The cart for which the collision box was requested.
* @return The collision box, cannot be null.
*/
AABB getMinecartCollisionBox(AbstractMinecart cart);
/**
* This function replaces the function of the same name in EntityMinecart.
* It defines whether minecarts are solid to the player.
* @param cart The cart for which the bounding box was requested.
* @return The bounding box or null.
*/
AABB getBoundingBox(AbstractMinecart cart);
}
@@ -23,14 +23,11 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public class MinecraftForge
{
public class MinecraftForge {
/**
* The EventBus for all the Forge Events.
*
@@ -46,8 +43,7 @@ public class MinecraftForge
/**
* Method invoked by FML before any other mods are loaded.
*/
public static void initialize()
{
public static void initialize() {
LOGGER.info(FORGE,"MinecraftForge v{} Initialized", ForgeVersion.getVersion());
UsernameCache.load();
@@ -5,6 +5,7 @@
package net.minecraftforge.common;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
@@ -47,7 +48,10 @@ public final class TagConventionMigrationHelper {
registryAccess.registries().forEach(registryEntry -> {
if (registryEntry.key().location().getNamespace().equals(ResourceLocation.DEFAULT_NAMESPACE)) {
FOUND_LEGACY_TAGS.addAll(
registryEntry.value().getTagNames().filter(TagConventionMappings.MAPPINGS::containsKey).toList()
registryEntry.value().getTags()
.map(HolderSet.Named::key)
.filter(TagConventionMappings.MAPPINGS::containsKey)
.toList()
);
}
});
@@ -60,7 +64,7 @@ public final class TagConventionMigrationHelper {
Warning for mod devs: Found known legacy tags that have direct common convention equivalents - consider migrating these to improve compatibility with other mods.
Note: This feature isn't fully comprehensive - see Forge's net.minecraftforge.common.Tags class for a full list of tags.
You can disable this message by setting "migrationHelperMode" to "OFF" in Forge's common config.
Here are some suggestions for replacements:""".stripIndent());
for (var legacyTag : FOUND_LEGACY_TAGS) {
@@ -84,7 +84,7 @@ public class ConditionalAdvancement {
public JsonObject build(HolderLookup.Provider lookup) {
var json = new JsonObject();
var array = new JsonArray();
json.add("advancements", array);
json.add("forge:conditional", array);
var ops = lookup.createSerializationContext(JsonOps.INSTANCE);
@@ -28,17 +28,21 @@ import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementHolder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderLookup.Provider;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.recipes.RecipeBuilder;
import net.minecraft.data.recipes.RecipeOutput;
import net.minecraft.world.Container;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingInput;
import net.minecraft.world.item.crafting.PlacementInfo;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.RecipeBookCategories;
import net.minecraft.world.item.crafting.RecipeBookCategory;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.Level;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.conditions.ConditionCodec;
import net.minecraftforge.common.crafting.conditions.ICondition;
@@ -50,7 +54,7 @@ import org.jetbrains.annotations.Nullable;
* disabling the entire recipe, it has sub-recipes that themselves have conditions.
*
* And when being deserialized it returns the first entry that passes the conditional check.
* This basically means that you can have muultiple variants all use the same recipe name, and
* This basically means that you can have multiple variants all use the same recipe name, and
* only one will ever be loaded.
*
* This also means that you can wrap ALL recipes in a Conditional even those that don't explicitly
@@ -67,7 +71,7 @@ public class ConditionalRecipe {
private final RecipeOutput bouncer = new RecipeOutput() {
@Override
public void accept(ResourceLocation id, Recipe<?> value, @Nullable AdvancementHolder advancement) {
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> value, @Nullable AdvancementHolder advancement) {
recipe(id, value, advancement);
}
@@ -78,7 +82,7 @@ public class ConditionalRecipe {
}
@Override
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
AdvancementHolder holder = null;
if (advancement != null) {
Advancement adv = Advancement.CODEC.parse(JsonOps.INSTANCE, advancement).getOrThrow(JsonParseException::new);
@@ -91,6 +95,9 @@ public class ConditionalRecipe {
public Provider registry() {
return null;
}
@Override
public void includeRootAdvancement() { }
};
@Nullable
@@ -120,7 +127,7 @@ public class ConditionalRecipe {
return this;
}
public Builder recipe(ResourceLocation id, Recipe<?> recipe, @Nullable AdvancementHolder advancement) {
public Builder recipe(ResourceKey<Recipe<?>> id, Recipe<?> recipe, @Nullable AdvancementHolder advancement) {
if (condition == null)
throw new IllegalStateException("Can not add a recipe with no conditions.");
recipes.add(new InnerRecipe(this.condition, recipe));
@@ -163,7 +170,8 @@ public class ConditionalRecipe {
advancementId = null;
}
out.accept(id, new Wrapper(mainCondition, recipes), advancementId, advancement);
var key = ResourceKey.create(Registries.RECIPE, id);
out.accept(key, new Wrapper(mainCondition, recipes), advancementId, advancement);
}
}
@@ -173,10 +181,14 @@ public class ConditionalRecipe {
private static class Wrapper implements Recipe<CraftingInput> {
@Override public boolean matches(CraftingInput inv, Level level) { return false; }
@Override public ItemStack assemble(CraftingInput inv, HolderLookup.Provider reg) { return null; }
@Override public boolean canCraftInDimensions(int width, int height) { return false; }
@Override public ItemStack getResultItem(HolderLookup.Provider reg) { return null; }
@Override public RecipeSerializer<?> getSerializer() { return ConditionalRecipe.SERIALZIER; }
@Override public RecipeType<?> getType() { throw new UnsupportedOperationException(); }
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public RecipeSerializer<? extends Recipe<CraftingInput>> getSerializer() {
return (RecipeSerializer)ConditionalRecipe.SERIALZIER;
}
@Override public RecipeType<? extends Recipe<CraftingInput>> getType() { throw new UnsupportedOperationException(); }
@Nullable private final ICondition main;
private final List<InnerRecipe> recipes;
@@ -185,6 +197,16 @@ public class ConditionalRecipe {
this.recipes = recipes;
}
@Override
public PlacementInfo placementInfo() {
return PlacementInfo.NOT_PLACEABLE;
}
@Override
public RecipeBookCategory recipeBookCategory() {
return RecipeBookCategories.STONECUTTER;
}
}
private static final MapCodec<Recipe<?>> CODEC = Codec.of(new MapEncoder.Implementation<>() {
@Override
@@ -7,36 +7,27 @@ package net.minecraftforge.common.crafting.conditions;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagManager;
import net.minecraft.tags.TagKey;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.List;
public class ConditionContext implements ICondition.IContext {
private final TagManager tagManager;
private Map<ResourceKey<?>, Map<ResourceLocation, Collection<Holder<?>>>> loadedTags = null;
private final List<Registry.PendingTags<?>> pendingTags;
public ConditionContext(TagManager tagManager) {
this.tagManager = tagManager;
public ConditionContext(List<Registry.PendingTags<?>> pendingTags) {
this.pendingTags = pendingTags;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
if (loadedTags == null) {
var tags = tagManager.getResult();
if (tags.isEmpty()) throw new IllegalStateException("Tags have not been loaded yet.");
loadedTags = new IdentityHashMap<>();
for (var loadResult : tags) {
var map = Collections.unmodifiableMap(loadResult.tags());
loadedTags.put(loadResult.key(), (Map)map);
}
public <T> Collection<Holder<T>> getTag(TagKey<T> key) {
for (var entry : this.pendingTags) {
if (entry.key() != key.registry())
continue;
@SuppressWarnings("unchecked")
var typed = ((Registry.PendingTags<T>)entry);
return typed.getPending(key);
}
return (Map)loadedTags.getOrDefault(registry, Collections.emptyMap());
return List.of();
}
}
@@ -42,14 +42,14 @@ public interface ICondition {
IContext EMPTY = new IContext() {
@Override
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
return Collections.emptyMap();
public <T> Collection<Holder<T>> getTag(TagKey<T> key) {
return Collections.emptyList();
}
};
IContext TAGS_INVALID = new IContext() {
@Override
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
public <T> Collection<Holder<T>> getTag(TagKey<T> key) {
throw new UnsupportedOperationException("Usage of tag-based conditions is not permitted in this context!");
}
};
@@ -57,14 +57,6 @@ public interface ICondition {
/**
* Return the requested tag if available, or an empty tag otherwise.
*/
default <T> Collection<Holder<T>> getTag(TagKey<T> key) {
return getAllTags(key.registry()).getOrDefault(key.location(), Set.of());
}
/**
* Return all the loaded tags for the passed registry, or an empty map if none is available.
* Note that the map and the tags are unmodifiable.
*/
<T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry);
<T> Collection<Holder<T>> getTag(TagKey<T> key);
}
}
@@ -5,12 +5,12 @@
package net.minecraftforge.common.crafting.ingredients;
import net.minecraft.core.HolderSet;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import java.util.stream.Stream;
/**
* Extension of {@link Ingredient} which makes most methods custom ingredients need to implement abstract, and removes the static constructors
@@ -19,12 +19,11 @@ import java.util.stream.Stream;
public abstract class AbstractIngredient extends Ingredient {
/** Empty constructor, for the sake of dynamic ingredients */
protected AbstractIngredient() {
super(Stream.of());
super(HolderSet.empty(), false);
}
/** Value constructor, for ingredients that have some vanilla representation */
protected AbstractIngredient(Stream<? extends Value> values) {
super(values);
protected AbstractIngredient(HolderSet<Item> items) {
super(items);
}
@Override
@@ -36,12 +35,6 @@ public abstract class AbstractIngredient extends Ingredient {
/* Hide vanilla ingredient static constructors to reduce errors with constructing custom ingredients */
/** @deprecated use {@link Ingredient#fromValues(Stream)} */
@Deprecated
public static Ingredient fromValues(Stream<? extends Ingredient.Value> values) {
throw new UnsupportedOperationException("Use Ingredient.fromValues()");
}
/** @deprecated use {@link Ingredient#of()} */
@Deprecated
public static Ingredient of() {
@@ -60,12 +53,6 @@ public abstract class AbstractIngredient extends Ingredient {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(Stream)} (Stream)} */
@Deprecated
public static Ingredient of(Stream<ItemStack> stacks) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(TagKey)} (Stream)} */
@Deprecated
public static Ingredient of(TagKey<Item> tag) {
@@ -9,15 +9,13 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Lists;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntComparators;
import it.unimi.dsi.fastutil.ints.IntList;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.core.Holder;
import net.minecraft.network.RegistryFriendlyByteBuf;
import org.jetbrains.annotations.NotNull;
@@ -36,8 +34,7 @@ public class CompoundIngredient extends AbstractIngredient {
}
private final List<Ingredient> children;
private ItemStack[] stacks;
private IntList itemIds;
private List<Holder<Item>> items;
private final boolean isSimple;
private CompoundIngredient(List<Ingredient> children) {
@@ -47,32 +44,14 @@ public class CompoundIngredient extends AbstractIngredient {
@Override
@NotNull
public ItemStack[] getItems() {
if (stacks == null) {
List<ItemStack> tmp = Lists.newArrayList();
for (Ingredient child : children)
Collections.addAll(tmp, child.getItems());
stacks = tmp.toArray(new ItemStack[tmp.size()]);
public List<Holder<Item>> items() {
if (this.items == null) {
var tmp = new ArrayList<Holder<Item>>();
for (var child : children)
tmp.addAll(child.items());
this.items = Collections.unmodifiableList(tmp);
}
return stacks;
}
@Override
@NotNull
public IntList getStackingIds() {
boolean childrenNeedInvalidation = false;
for (Ingredient child : children)
childrenNeedInvalidation |= child.checkInvalidation();
if (childrenNeedInvalidation || this.itemIds == null || checkInvalidation()) {
this.markValid();
this.itemIds = new IntArrayList();
for (Ingredient child : children)
this.itemIds.addAll(child.getStackingIds());
this.itemIds.sort(IntComparators.NATURAL_COMPARATOR);
}
return this.itemIds;
return this.items;
}
@Override
@@ -80,7 +59,12 @@ public class CompoundIngredient extends AbstractIngredient {
if (target == null)
return false;
return children.stream().anyMatch(c -> c.test(target));
for (var child : children) {
if (child.test(target))
return true;
}
return false;
}
@Override
@@ -88,11 +72,6 @@ public class CompoundIngredient extends AbstractIngredient {
return isSimple;
}
@Override
public boolean isEmpty() {
return children.stream().allMatch(Ingredient::isEmpty);
}
@Override
public IIngredientSerializer<? extends Ingredient> serializer() {
return SERIALIZER;
@@ -100,7 +79,7 @@ public class CompoundIngredient extends AbstractIngredient {
public static final MapCodec<CompoundIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
builder.group(
Ingredient.CODEC_NONEMPTY.listOf().fieldOf("children").forGetter(i -> i.children)
Ingredient.CODEC.listOf().fieldOf("children").forGetter(i -> i.children)
).apply(builder, CompoundIngredient::new)
);
@@ -8,16 +8,16 @@ package net.minecraftforge.common.crafting.ingredients;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntComparators;
import it.unimi.dsi.fastutil.ints.IntList;
import net.minecraft.core.Holder;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Ingredient that matches everything from the first ingredient that is not included in the second ingredient */
public class DifferenceIngredient extends AbstractIngredient {
@@ -33,8 +33,7 @@ public class DifferenceIngredient extends AbstractIngredient {
private final Ingredient base;
private final Ingredient subtracted;
private ItemStack[] filteredMatchingStacks;
private IntList packedMatchingStacks;
private List<Holder<Item>> items = null;
private DifferenceIngredient(Ingredient base, Ingredient subtracted) {
this.base = base;
@@ -48,18 +47,26 @@ public class DifferenceIngredient extends AbstractIngredient {
return base.test(stack) && !subtracted.test(stack);
}
@SuppressWarnings("deprecation")
@Override
public ItemStack[] getItems() {
if (this.filteredMatchingStacks == null)
this.filteredMatchingStacks = Arrays.stream(base.getItems())
.filter(stack -> !subtracted.test(stack))
.toArray(ItemStack[]::new);
return filteredMatchingStacks;
}
public List<Holder<Item>> items() {
if (this.items == null) {
var tmp = new ArrayList<Holder<Item>>();
@Override
public boolean isEmpty() {
return base.isEmpty();
for (var base : this.base.items()) {
boolean match = false;
for (var item : this.subtracted.items()) {
if (base.is(item)) {
match = true;
break;
}
}
if (!match)
tmp.add(base);
}
this.items = Collections.unmodifiableList(tmp);
}
return items;
}
@Override
@@ -67,27 +74,6 @@ public class DifferenceIngredient extends AbstractIngredient {
return base.isSimple() && subtracted.isSimple();
}
@Override
protected void invalidate() {
super.invalidate();
this.filteredMatchingStacks = null;
this.packedMatchingStacks = null;
}
@Override
public IntList getStackingIds() {
if (this.packedMatchingStacks == null || checkInvalidation()) {
markValid();
var matchingStacks = getItems();
this.packedMatchingStacks = new IntArrayList(matchingStacks.length);
for (var stack : matchingStacks)
this.packedMatchingStacks.add(StackedContents.getStackingIndex(stack));
this.packedMatchingStacks.sort(IntComparators.NATURAL_COMPARATOR);
}
return packedMatchingStacks;
}
@Override
public IIngredientSerializer<DifferenceIngredient> serializer() {
return SERIALIZER;
@@ -7,6 +7,8 @@ package net.minecraftforge.common.crafting.ingredients;
import java.util.Arrays;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.HolderSet;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
@@ -25,19 +27,24 @@ public interface IIngredientBuilder {
return CompoundIngredient.of(values);
}
default Ingredient intersection(@SuppressWarnings("rawtypes") TagKey... values) {
return intersection(Arrays.stream(values).map(Ingredient::of).toArray(Ingredient[]::new));
@SuppressWarnings("unchecked")
default Ingredient intersection(HolderGetter<Item> lookup, @SuppressWarnings("rawtypes") TagKey... values) {
return intersection(Arrays.stream(values).map(k -> holder(lookup, (TagKey<Item>)k)).map(Ingredient::of).toArray(Ingredient[]::new));
}
default Ingredient intersection(Ingredient... values) {
return IntersectionIngredient.of(values);
}
default Ingredient difference(TagKey<Item> base, TagKey<Item> subtracted) {
return difference(Ingredient.of(base), Ingredient.of(subtracted));
default Ingredient difference(HolderGetter<Item> lookup, TagKey<Item> base, TagKey<Item> subtracted) {
return difference(Ingredient.of(holder(lookup, base)), Ingredient.of(holder(lookup, subtracted)));
}
default Ingredient difference(Ingredient base, Ingredient subtracted) {
return DifferenceIngredient.of(base, subtracted);
}
private static HolderSet<Item> holder(HolderGetter<Item> lookup, TagKey<Item> key) {
return lookup.getOrThrow(key);
}
}
@@ -5,12 +5,9 @@
package net.minecraftforge.common.crafting.ingredients;
import java.util.Arrays;
import com.mojang.serialization.MapCodec;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
public interface IIngredientSerializer<T extends Ingredient> {
@@ -18,22 +15,4 @@ public interface IIngredientSerializer<T extends Ingredient> {
void write(RegistryFriendlyByteBuf buffer, T value);
T read(RegistryFriendlyByteBuf buffer);
IIngredientSerializer<Ingredient> VANILLA = new IIngredientSerializer<>() {
@Override
public MapCodec<? extends Ingredient> codec() {
return Ingredient.VANILLA_MAP_CODEC;
}
@Override
public void write(RegistryFriendlyByteBuf buffer, Ingredient value) {
ItemStack.LIST_STREAM_CODEC.encode(buffer, Arrays.asList(value.getItems()));
}
@Override
public Ingredient read(RegistryFriendlyByteBuf buffer) {
return Ingredient.of(ItemStack.LIST_STREAM_CODEC.decode(buffer).stream());
}
};
}
@@ -8,11 +8,9 @@ package net.minecraftforge.common.crafting.ingredients;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntComparators;
import it.unimi.dsi.fastutil.ints.IntList;
import net.minecraft.core.Holder;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.world.entity.player.StackedContents;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import org.jetbrains.annotations.Nullable;
@@ -40,8 +38,7 @@ public class IntersectionIngredient extends AbstractIngredient {
private final List<Ingredient> children;
private final boolean isSimple;
private ItemStack[] intersectedMatchingStacks = null;
private IntList packedMatchingStacks = null;
private List<Holder<Item>> items = null;
private IntersectionIngredient(List<Ingredient> children) {
if (children.size() < 2)
@@ -62,26 +59,33 @@ public class IntersectionIngredient extends AbstractIngredient {
return true;
}
@SuppressWarnings("deprecation")
@Override
public ItemStack[] getItems() {
if (this.intersectedMatchingStacks == null) {
this.intersectedMatchingStacks = Arrays
.stream(children.get(0).getItems())
.filter(stack -> {
// the first ingredient is treated as a base, filtered by the second onwards
for (int i = 1; i < children.size(); i++)
if (!children.get(i).test(stack))
return false;
return true;
})
.toArray(ItemStack[]::new);
}
return intersectedMatchingStacks;
}
public List<Holder<Item>> items() {
if (this.items == null) {
var tmp = new ArrayList<Holder<Item>>();
@Override
public boolean isEmpty() {
return children.stream().anyMatch(Ingredient::isEmpty);
for (var base : children.get(0).items()) {
boolean allMatch = true;
for (int i = 1; i < children.size(); i++) {
boolean match = false;
for (var item : children.get(i).items()) {
if (base.is(item)) {
match = true;
break;
}
}
if (!match) {
allMatch = false;
break;
}
}
if (allMatch)
tmp.add(base);
}
this.items = Collections.unmodifiableList(tmp);
}
return items;
}
@Override
@@ -89,26 +93,6 @@ public class IntersectionIngredient extends AbstractIngredient {
return isSimple;
}
@Override
protected void invalidate() {
super.invalidate();
this.intersectedMatchingStacks = null;
this.packedMatchingStacks = null;
}
@Override
public IntList getStackingIds() {
if (this.packedMatchingStacks == null || checkInvalidation()) {
markValid();
var matchingStacks = getItems();
this.packedMatchingStacks = new IntArrayList(matchingStacks.length);
for (var stack : matchingStacks)
this.packedMatchingStacks.add(StackedContents.getStackingIndex(stack));
this.packedMatchingStacks.sort(IntComparators.NATURAL_COMPARATOR);
}
return packedMatchingStacks;
}
@Override
public IIngredientSerializer<IntersectionIngredient> serializer() {
return SERIALIZER;
@@ -9,21 +9,22 @@ import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.advancements.critereon.NbtPredicate;
import net.minecraft.core.HolderSet;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@@ -33,34 +34,41 @@ public class PartialNBTIngredient extends AbstractIngredient {
return new Builder();
}
private final List<Item> items;
private final CompoundTag nbt;
private final NbtPredicate predicate;
private PartialNBTIngredient(List<Item> items, CompoundTag nbt) {
super(items.stream().map(item -> {
var stack = new ItemStack(item);
// copy NBT to prevent the stack from modifying the original, as capabilities or vanilla item durability will modify the tag
stack.set(DataComponents.CUSTOM_DATA, CustomData.of(nbt.copy()));
return new Ingredient.ItemValue(stack);
}));
private PartialNBTIngredient(HolderSet<Item> items, CompoundTag nbt) {
super(items);
if (items.isEmpty())
if (items.size() == 0)
throw new IllegalArgumentException("Cannot create a PartialNBTIngredient with no items");
this.items = Collections.unmodifiableList(items);
this.nbt = nbt;
this.predicate = new NbtPredicate(nbt);
}
/** Creates a new ingredient matching any item from the list, containing the given NBT */
@SuppressWarnings("deprecation")
public static PartialNBTIngredient of(CompoundTag nbt, ItemLike... items) {
return new PartialNBTIngredient(Arrays.stream(items).map(ItemLike::asItem).toList(), nbt);
return of(
HolderSet.direct(
Arrays.stream(items)
.map(ItemLike::asItem)
.map(Item::builtInRegistryHolder)
.toList()
),
nbt);
}
/** Creates a new ingredient matching the given item, containing the given NBT */
@SuppressWarnings("deprecation")
public static PartialNBTIngredient of(ItemLike item, CompoundTag nbt) {
return new PartialNBTIngredient(List.of(item.asItem()), nbt);
return of(HolderSet.direct(item.asItem().builtInRegistryHolder()), nbt);
}
/** Creates a new ingredient matching the given item, containing the given NBT */
public static PartialNBTIngredient of(HolderSet<Item> items, CompoundTag nbt) {
return new PartialNBTIngredient(items, nbt);
}
@Override
@@ -68,7 +76,7 @@ public class PartialNBTIngredient extends AbstractIngredient {
if (input == null)
return false;
var nbt = input.get(DataComponents.CUSTOM_DATA);
return nbt != null && items.contains(input.getItem()) && predicate.matches(nbt.copyTag());
return nbt != null && input.is(this.values) && predicate.matches(nbt.copyTag());
}
@Override
@@ -83,12 +91,14 @@ public class PartialNBTIngredient extends AbstractIngredient {
public static final MapCodec<PartialNBTIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
builder.group(
ForgeRegistries.ITEMS.getCodec().listOf().fieldOf("items").forGetter(i -> i.items),
Ingredient.NON_AIR_HOLDER_SET_CODEC.fieldOf("items").forGetter(i -> i.values),
TagParser.AS_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
).apply(builder, PartialNBTIngredient::new)
);
public static final IIngredientSerializer<PartialNBTIngredient> SERIALIZER = new IIngredientSerializer<>() {
private final StreamCodec<RegistryFriendlyByteBuf, HolderSet<Item>> HOLDER_SET = ByteBufCodecs.holderSet(Registries.ITEM);
@Override
public MapCodec<? extends PartialNBTIngredient> codec() {
return CODEC;
@@ -96,14 +106,14 @@ public class PartialNBTIngredient extends AbstractIngredient {
@Override
public PartialNBTIngredient read(RegistryFriendlyByteBuf buffer) {
var items = buffer.readList(b -> Item.STREAM_CODEC.decode(buffer).get());
var items = HOLDER_SET.decode(buffer);
var nbt = buffer.readNbt();
return new PartialNBTIngredient(items, Objects.requireNonNull(nbt));
}
@Override
public void write(RegistryFriendlyByteBuf buffer, PartialNBTIngredient value) {
buffer.writeCollection(value.items, (b, item) -> Item.STREAM_CODEC.encode(buffer, item.builtInRegistryHolder()));
HOLDER_SET.encode(buffer, value.values);
buffer.writeNbt(value.nbt);
}
};
@@ -5,8 +5,7 @@
package net.minecraftforge.common.crafting.ingredients;
import java.util.stream.Stream;
import net.minecraft.core.HolderSet;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.world.item.ItemStack;
@@ -24,7 +23,7 @@ public class StrictNBTIngredient extends AbstractIngredient {
private final ItemStack stack;
private StrictNBTIngredient(ItemStack stack) {
super(Stream.of(new Ingredient.ItemValue(stack)));
super(HolderSet.direct(stack.getItemHolder()));
this.stack = stack;
}
@@ -32,6 +31,7 @@ public class StrictNBTIngredient extends AbstractIngredient {
public boolean test(@Nullable ItemStack input) {
if (input == null)
return false;
//Can't use areItemStacksEqualUsingNBTShareTag because it compares stack size as well
var inbt = input.get(DataComponents.CUSTOM_DATA);
var tnbt = this.stack.get(DataComponents.CUSTOM_DATA);
@@ -27,10 +27,37 @@ public final class ForgeEntityTypeTagsProvider extends EntityTypeTagsProvider {
@Override
public void addTags(HolderLookup.Provider lookupProvider) {
tag(BOSSES)
.add(EntityType.ENDER_DRAGON, EntityType.WITHER)
.addOptionalTag(forgeTagKey("bosses"));
tag(MINECARTS).add(EntityType.MINECART, EntityType.CHEST_MINECART, EntityType.FURNACE_MINECART, EntityType.HOPPER_MINECART, EntityType.SPAWNER_MINECART, EntityType.TNT_MINECART, EntityType.COMMAND_BLOCK_MINECART);
tag(BOATS).add(EntityType.BOAT, EntityType.CHEST_BOAT);
.add(EntityType.ENDER_DRAGON, EntityType.WITHER)
.addOptionalTag(forgeTagKey("bosses"));
tag(MINECARTS).add(
EntityType.MINECART,
EntityType.CHEST_MINECART,
EntityType.FURNACE_MINECART,
EntityType.HOPPER_MINECART,
EntityType.SPAWNER_MINECART,
EntityType.TNT_MINECART,
EntityType.COMMAND_BLOCK_MINECART
);
tag(BOATS).add(
EntityType.ACACIA_BOAT,
EntityType.ACACIA_CHEST_BOAT,
EntityType.BIRCH_BOAT,
EntityType.BIRCH_CHEST_BOAT,
EntityType.CHERRY_BOAT,
EntityType.CHERRY_CHEST_BOAT,
EntityType.DARK_OAK_BOAT,
EntityType.DARK_OAK_CHEST_BOAT,
EntityType.JUNGLE_BOAT,
EntityType.JUNGLE_CHEST_BOAT,
EntityType.MANGROVE_BOAT,
EntityType.MANGROVE_CHEST_BOAT,
EntityType.OAK_BOAT,
EntityType.OAK_CHEST_BOAT,
EntityType.PALE_OAK_BOAT,
EntityType.PALE_OAK_CHEST_BOAT,
EntityType.SPRUCE_BOAT,
EntityType.SPRUCE_CHEST_BOAT
);
tag(CAPTURING_NOT_SUPPORTED);
tag(TELEPORTING_NOT_SUPPORTED);
@@ -8,7 +8,6 @@ package net.minecraftforge.common.data;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.data.PackOutput;
import net.minecraft.data.tags.IntrinsicHolderTagsProvider;
import net.minecraft.data.tags.ItemTagsProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BlockTags;
@@ -32,7 +31,7 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider {
super(output, lookupProvider, blockTagProvider, "forge", existingFileHelper);
}
@SuppressWarnings("unchecked")
@SuppressWarnings({ "unchecked", "removal" })
@Override
public void addTags(HolderLookup.Provider lookupProvider) {
copy(Tags.Blocks.BARRELS, Tags.Items.BARRELS);
@@ -518,7 +517,7 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider {
for (DyeColor color : DyeColor.values()) {
ResourceLocation key = ResourceLocation.fromNamespaceAndPath("minecraft", pattern.replace("{color}", color.getName()));
TagKey<Item> tag = getForgeItemTag(prefix + color.getName());
Item item = BuiltInRegistries.ITEM.get(key);
Item item = BuiltInRegistries.ITEM.getValue(key);
if (item == null || item == Items.AIR)
throw new IllegalStateException("Unknown vanilla item: " + key);
tag(tag).add(item);
@@ -582,11 +581,11 @@ public final class ForgeItemTagsProvider extends ItemTagsProvider {
}
private static TagKey<Block> forgeBlockTagKey(String path) {
return BlockTags.create(ResourceLocation.fromNamespaceAndPath("forge", path));
return BlockTags.create(forgeRl(path));
}
private static TagKey<Item> forgeItemTagKey(String path) {
return ItemTags.create(ResourceLocation.fromNamespaceAndPath("forge", path));
return ItemTags.create(forgeRl(path));
}
@Override
@@ -8,21 +8,23 @@ package net.minecraftforge.common.data;
import com.google.gson.JsonElement;
import net.minecraft.advancements.AdvancementHolder;
import net.minecraft.advancements.Advancement.Builder;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderLookup.Provider;
import net.minecraft.data.CachedOutput;
import net.minecraft.core.HolderLookup.RegistryLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.PackOutput;
import net.minecraft.data.recipes.RecipeOutput;
import net.minecraft.data.recipes.RecipeProvider;
import net.minecraft.data.recipes.packs.VanillaRecipeProvider;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.item.crafting.Ingredient.ItemValue;
import net.minecraft.world.item.crafting.Ingredient.TagValue;
import net.minecraft.world.item.crafting.Ingredient.Value;
import net.minecraft.world.item.crafting.Recipe;
import net.minecraft.world.item.crafting.ShapedRecipe;
import net.minecraft.world.item.crafting.ShapedRecipePattern;
@@ -30,10 +32,13 @@ import net.minecraft.world.item.crafting.ShapelessRecipe;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.common.Tags;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.unsafe.UnsafeFieldAccess;
import net.minecraftforge.unsafe.UnsafeHacks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -43,19 +48,26 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture;
public final class ForgeRecipeProvider extends VanillaRecipeProvider {
private static final Logger LOGGER = LogManager.getLogger();
private final RegistryLookup<Item> items;
private final Map<Item, TagKey<Item>> replacements = HashMap.newHashMap(12);
private final Set<ResourceLocation> excludes = HashSet.newHashSet(16);
private final Set<ResourceKey<Recipe<?>>> excludes = HashSet.newHashSet(16);
private final UnsafeFieldAccess<ShapelessRecipe, List<Ingredient>> INGREDIENTS = UnsafeHacks.findField(ShapelessRecipe.class, "ingredients");
private final UnsafeFieldAccess<ShapedRecipe, ShapedRecipePattern> PATTERN = UnsafeHacks.findField(ShapedRecipe.class, "pattern");
private final UnsafeFieldAccess<Ingredient, HolderSet<Item>> VALUES = UnsafeHacks.findField(Ingredient.class, "values");
public ForgeRecipeProvider(PackOutput packOutput, CompletableFuture<HolderLookup.Provider> lookup) {
super(packOutput, lookup);
private ForgeRecipeProvider(HolderLookup.Provider lookup, RecipeOutput output) {
super(lookup, new Wrapped(output));
((Wrapped)this.output).setSelf(this);
this.items = lookup.lookupOrThrow(Registries.ITEM);
}
private void exclude(ItemLike item) {
excludes.add(ForgeRegistries.ITEMS.getKey(item.asItem()));
exclude(BuiltInRegistries.ITEM.getKey(item.asItem()).toString());
}
private void exclude(String name) {
excludes.add(ResourceLocation.parse(name));
excludes.add(ResourceKey.create(Registries.RECIPE, ResourceLocation.parse(name)));
}
private void replace(ItemLike item, TagKey<Item> tag) {
@@ -63,7 +75,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
}
@Override
protected void buildRecipes(RecipeOutput consumer) {
protected void buildRecipes() {
replace(Items.STICK, Tags.Items.RODS_WOODEN);
replace(Items.GOLD_INGOT, Tags.Items.INGOTS_GOLD);
replace(Items.IRON_INGOT, Tags.Items.INGOTS_IRON);
@@ -96,32 +108,11 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
exclude(Blocks.COBBLED_DEEPSLATE_SLAB);
exclude(Blocks.COBBLED_DEEPSLATE_WALL);
super.buildRecipes(new RecipeOutput() {
@Override
public void accept(ResourceLocation id, Recipe<?> recipe, AdvancementHolder advancement) {
var modified = enhance(id, recipe);
if (modified != null)
consumer.accept(id, modified, advancement);
}
@Override
public Builder advancement() {
return consumer.advancement();
}
@Override
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
}
@Override
public Provider registry() {
return consumer.registry();
}
});
super.buildRecipes();
}
@Nullable
private Recipe<?> enhance(ResourceLocation id, Recipe<?> vanilla) {
private Recipe<?> enhance(ResourceKey<Recipe<?>> id, Recipe<?> vanilla) {
if (vanilla instanceof ShapelessRecipe shapeless)
return enhance(id, shapeless);
if (vanilla instanceof ShapedRecipe shaped)
@@ -130,8 +121,8 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
}
@Nullable
private Recipe<?> enhance(ResourceLocation id, ShapelessRecipe vanilla) {
List<Ingredient> ingredients = getField(ShapelessRecipe.class, vanilla, 3);
private Recipe<?> enhance(ResourceKey<Recipe<?>> id, ShapelessRecipe vanilla) {
List<Ingredient> ingredients = INGREDIENTS.get(vanilla);
boolean modified = false;
for (int x = 0; x < ingredients.size(); x++) {
Ingredient ing = enhance(id, ingredients.get(x));
@@ -144,21 +135,8 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
}
@Nullable
@Override
protected CompletableFuture<?> saveAdvancement(CachedOutput output, ResourceLocation advancementId, JsonElement advancement) {
// NOOP - We don't replace any of the advancement things yet...
return null;
}
@Override
protected CompletableFuture<?> buildAdvancement(CachedOutput p_253674_, HolderLookup.Provider p_335995_, AdvancementHolder p_297687_) {
// NOOP - We don't replace any of the advancement things yet...
return CompletableFuture.allOf();
}
@Nullable
private Recipe<?> enhance(ResourceLocation id, ShapedRecipe vanilla) {
ShapedRecipePattern pattern = getField(ShapedRecipe.class, vanilla, 2);
private Recipe<?> enhance(ResourceKey<Recipe<?>> id, ShapedRecipe vanilla) {
ShapedRecipePattern pattern = PATTERN.get(vanilla);
var data = pattern.data().orElseThrow(() -> new IllegalStateException("Weird shaped recipe, data is missing? " + id + " " + vanilla));
Map<Character, Ingredient> ingredients = data.key();
boolean modified = false;
@@ -173,36 +151,92 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
}
@Nullable
private Ingredient enhance(ResourceLocation name, Ingredient vanilla) {
private Ingredient enhance(ResourceKey<Recipe<?>> name, Ingredient vanilla) {
if (excludes.contains(name))
return null;
boolean modified = false;
List<Value> items = new ArrayList<>();
Value[] vanillaItems = getField(Ingredient.class, vanilla, 3); //This will probably crash between versions, if null fix index
for (Value entry : vanillaItems) {
if (entry instanceof ItemValue) {
ItemStack stack = entry.getItems().stream().findFirst().orElse(ItemStack.EMPTY);
TagKey<Item> replacement = replacements.get(stack.getItem());
if (replacement != null) {
items.add(new TagValue(replacement));
modified = true;
} else
items.add(entry);
HolderSet<Item> vanillaItems = VALUES.get(vanilla);
var unwraped = vanillaItems.unwrap();
if (unwraped.left().isPresent()) // Already a tag
return null;
Ingredient ret = null;
var items = new ArrayList<Holder<Item>>();
for (var entry : unwraped.right().get()) {
var item = entry.get();
var replacement = replacements.get(item);
if (replacement != null) {
if (ret != null) {
LOGGER.warn("Failed to enahnce {} ingredient has multiple input items", name);
return null;
}
ret = Ingredient.of(this.items.getOrThrow(replacement));
} else
items.add(entry);
}
return modified ? Ingredient.fromValues(items.stream()) : null;
if (ret != null && !items.isEmpty()) {
LOGGER.warn("Failed to enahnce {} ingredient has multiple input items", name);
return null;
}
return ret;
}
@SuppressWarnings("unchecked")
private static <T, R> R getField(Class<T> clz, T inst, int index) {
Field fld = clz.getDeclaredFields()[index];
fld.setAccessible(true);
try {
return (R) fld.get(inst);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
public static class Runner extends RecipeProvider.Runner {
public Runner(PackOutput output, CompletableFuture<Provider> registries) {
super(output, registries);
}
@Override
public String getName() {
return ForgeRecipeProvider.class.getSimpleName();
}
@Override
protected RecipeProvider createRecipeProvider(Provider registries, RecipeOutput output) {
return new ForgeRecipeProvider(registries, output);
}
}
private static class Wrapped implements RecipeOutput {
private final RecipeOutput wrapped;
private ForgeRecipeProvider self;
private Wrapped(RecipeOutput wrapped) {
this.wrapped = wrapped;
}
private void setSelf(ForgeRecipeProvider self) {
this.self = self;
}
@Override
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> recipe, AdvancementHolder advancement) {
var modified = self.enhance(id, recipe);
if (modified != null)
wrapped.accept(id, modified, null);
}
@Override
public Builder advancement() {
return wrapped.advancement();
}
@Override
public void accept(ResourceKey<Recipe<?>> id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
var modified = self.enhance(id, recipe);
if (modified != null)
wrapped.accept(id, modified, null);
}
@Override
public Provider registry() {
return wrapped.registry();
}
@Override
public void includeRootAdvancement() {}
}
}
@@ -80,7 +80,7 @@ public abstract class LanguageProvider implements DataProvider {
}
public void add(ItemStack key, String name) {
add(key.getDescriptionId(), name);
add(key.getItem().getDescriptionId(), name);
}
public void addEnchantment(Supplier<? extends Enchantment> key, String name) {
@@ -26,8 +26,7 @@ import org.apache.logging.log4j.Logger;
* Data provider for the {@code sounds.json} file, which identifies sound definitions
* for the various sound events in Minecraft.
*/
public abstract class SoundDefinitionsProvider implements DataProvider
{
public abstract class SoundDefinitionsProvider implements DataProvider {
private static final Logger LOGGER = LogManager.getLogger();
private final PackOutput output;
private final String modId;
@@ -42,8 +41,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* @param modId The mod ID of the current mod.
* @param helper The existing file helper provided by the event you are initializing this provider in.
*/
protected SoundDefinitionsProvider(final PackOutput output, final String modId, final ExistingFileHelper helper)
{
protected SoundDefinitionsProvider(final PackOutput output, final String modId, final ExistingFileHelper helper) {
this.output = output;
this.modId = modId;
this.helper = helper;
@@ -55,13 +53,11 @@ public abstract class SoundDefinitionsProvider implements DataProvider
public abstract void registerSounds();
@Override
public CompletableFuture<?> run(CachedOutput cache)
{
public CompletableFuture<?> run(CachedOutput cache) {
this.sounds.clear();
this.registerSounds();
this.validate();
if (!this.sounds.isEmpty())
{
if (!this.sounds.isEmpty()) {
return this.save(cache, this.output.getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(this.modId).resolve("sounds.json"));
}
@@ -69,8 +65,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
}
@Override
public String getName()
{
public String getName() {
return "Sound Definitions";
}
@@ -79,8 +74,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* Creates a new {@link SoundDefinition}, which will host a set of
* {@link SoundDefinition.Sound}s and the necessary parameters.
*/
protected static SoundDefinition definition()
{
protected static SoundDefinition definition() {
return SoundDefinition.definition();
}
@@ -90,8 +84,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* @param name The name of the sound to create.
* @param type The type of sound to create.
*/
protected static SoundDefinition.Sound sound(final ResourceLocation name, final SoundDefinition.SoundType type)
{
protected static SoundDefinition.Sound sound(final ResourceLocation name, final SoundDefinition.SoundType type) {
return SoundDefinition.Sound.sound(name, type);
}
@@ -101,8 +94,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
*
* @param name The name of the sound to create.
*/
protected static SoundDefinition.Sound sound(final ResourceLocation name)
{
protected static SoundDefinition.Sound sound(final ResourceLocation name) {
return sound(name, SoundDefinition.SoundType.SOUND);
}
@@ -112,8 +104,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* @param name The name of the sound to create.
* @param type The type of sound to create.
*/
protected static SoundDefinition.Sound sound(final String name, final SoundDefinition.SoundType type)
{
protected static SoundDefinition.Sound sound(final String name, final SoundDefinition.SoundType type) {
return sound(ResourceLocation.parse(name), type);
}
@@ -123,8 +114,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
*
* @param name The name of the sound to create.
*/
protected static SoundDefinition.Sound sound(final String name)
{
protected static SoundDefinition.Sound sound(final String name) {
return sound(ResourceLocation.parse(name));
}
@@ -139,8 +129,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* @param soundEvent A {@code Supplier} for the given {@link SoundEvent}.
* @param definition A {@link SoundDefinition} that defines the given sound.
*/
protected void add(final Supplier<SoundEvent> soundEvent, final SoundDefinition definition)
{
protected void add(final Supplier<SoundEvent> soundEvent, final SoundDefinition definition) {
this.add(soundEvent.get(), definition);
}
@@ -155,9 +144,8 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* @param soundEvent A {@link SoundEvent}.
* @param definition The {@link SoundDefinition} that defines the given event.
*/
protected void add(final SoundEvent soundEvent, final SoundDefinition definition)
{
this.add(soundEvent.getLocation(), definition);
protected void add(final SoundEvent soundEvent, final SoundDefinition definition) {
this.add(soundEvent.location(), definition);
}
/**
@@ -167,8 +155,7 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* @param soundEvent The {@link ResourceLocation} that identifies the event.
* @param definition The {@link SoundDefinition} that defines the given event.
*/
protected void add(final ResourceLocation soundEvent, final SoundDefinition definition)
{
protected void add(final ResourceLocation soundEvent, final SoundDefinition definition) {
this.addSounds(soundEvent.getPath(), definition);
}
@@ -184,42 +171,32 @@ public abstract class SoundDefinitionsProvider implements DataProvider
* @param soundEvent The name of the {@link SoundEvent}.
* @param definition The {@link SoundDefinition} that defines the given event.
*/
protected void add(final String soundEvent, final SoundDefinition definition)
{
protected void add(final String soundEvent, final SoundDefinition definition) {
this.add(ResourceLocation.parse(soundEvent), definition);
}
private void addSounds(final String soundEvent, final SoundDefinition definition)
{
private void addSounds(final String soundEvent, final SoundDefinition definition) {
if (this.sounds.put(soundEvent, definition) != null)
{
throw new IllegalStateException("Sound event '" + this.modId + ":" + soundEvent + "' already exists");
}
}
// Internal handling stuff
private void validate()
{
private void validate() {
final List<String> notValid = this.sounds.entrySet().stream()
.filter(it -> !this.validate(it.getKey(), it.getValue()))
.map(Map.Entry::getKey)
.map(it -> this.modId + ":" + it)
.toList();
if (!notValid.isEmpty())
{
throw new IllegalStateException("Found invalid sound events: " + notValid);
}
}
private boolean validate(final String name, final SoundDefinition def)
{
private boolean validate(final String name, final SoundDefinition def) {
return def.soundList().stream().allMatch(it -> this.validate(name,it));
}
private boolean validate(final String name, final SoundDefinition.Sound sound)
{
switch (sound.type())
{
private boolean validate(final String name, final SoundDefinition.Sound sound) {
switch (sound.type()) {
case SOUND: return this.validateSound(name, sound.name());
case EVENT: return this.validateEvent(name, sound.name());
}
@@ -230,34 +207,27 @@ public abstract class SoundDefinitionsProvider implements DataProvider
throw new IllegalArgumentException("The given sound '" + sound.name() + "' does not have a valid type: expected either SOUND or EVENT, but found " + sound.type());
}
private boolean validateSound(final String soundName, final ResourceLocation name)
{
private boolean validateSound(final String soundName, final ResourceLocation name) {
final boolean valid = this.helper.exists(name, PackType.CLIENT_RESOURCES, ".ogg", "sounds");
if (!valid)
{
if (!valid) {
final String path = name.getNamespace() + ":sounds/" + name.getPath() + ".ogg";
LOGGER.warn("Unable to find corresponding OGG file '{}' for sound event '{}'", path, soundName);
}
return valid;
}
private boolean validateEvent(final String soundName, final ResourceLocation name)
{
private boolean validateEvent(final String soundName, final ResourceLocation name) {
final boolean valid = this.sounds.containsKey(soundName) || ForgeRegistries.SOUND_EVENTS.containsKey(name);
if (!valid)
{
LOGGER.warn("Unable to find event '{}' referenced from '{}'", name, soundName);
}
return valid;
}
private CompletableFuture<?> save(final CachedOutput cache, final Path targetFile)
{
private CompletableFuture<?> save(final CachedOutput cache, final Path targetFile) {
return DataProvider.saveStable(cache, mapToJson(this.sounds), targetFile);
}
private static JsonObject mapToJson(final Map<String, SoundDefinition> map)
{
private static JsonObject mapToJson(final Map<String, SoundDefinition> map) {
final JsonObject obj = new JsonObject();
// namespaces are ignored when serializing
map.forEach((k, v) -> obj.add(k, v.serialize()));
@@ -6,15 +6,14 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.AbstractBoat;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.material.FluidState;
import net.minecraftforge.fluids.FluidType;
public interface IForgeBoat
{
private Boat self()
{
return (Boat) this;
public interface IForgeAbstractBoat {
private AbstractBoat self() {
return (AbstractBoat)this;
}
/**
@@ -23,8 +22,7 @@ public interface IForgeBoat
* @param state the state of the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean canBoatInFluid(FluidState state)
{
default boolean canBoatInFluid(FluidState state) {
return state.supportsBoating(self());
}
@@ -34,8 +32,7 @@ public interface IForgeBoat
* @param type the type of the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean canBoatInFluid(FluidType type)
{
default boolean canBoatInFluid(FluidType type) {
return type.supportsBoating(self());
}
@@ -47,8 +44,7 @@ public interface IForgeBoat
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateFluidWhileRiding(FluidState state, Entity rider)
{
default boolean shouldUpdateFluidWhileRiding(FluidState state, Entity rider) {
return state.shouldUpdateWhileBoating(self(), rider);
}
}
@@ -10,8 +10,7 @@ import net.minecraft.tags.BlockTags;
import net.minecraft.core.BlockPos;
import net.minecraft.util.Mth;
public interface IForgeAbstractMinecart
{
public interface IForgeAbstractMinecart {
public static float DEFAULT_MAX_SPEED_AIR_LATERAL = 0.4f;
public static float DEFAULT_MAX_SPEED_AIR_VERTICAL = -1.0f;
public static double DEFAULT_AIR_DRAG = 0.95f;
@@ -23,8 +22,7 @@ public interface IForgeAbstractMinecart
/**
* Internal, returns the current spot to look for the attached rail.
*/
default BlockPos getCurrentRailPosition()
{
default BlockPos getCurrentRailPosition() {
int x = Mth.floor(self().getX());
int y = Mth.floor(self().getY());
int z = Mth.floor(self().getZ());
@@ -35,12 +33,6 @@ public interface IForgeAbstractMinecart
double getMaxSpeedWithRail();
/**
* Moved to allow overrides.
* This code handles minecart movement and speed capping when on a rail.
*/
void moveMinecartOnRail(BlockPos pos);
/**
* Returns true if this cart can currently use rails.
* This function is mainly used to gracefully detach a minecart from a rail.
@@ -55,30 +47,6 @@ public interface IForgeAbstractMinecart
*/
void setCanUseRail(boolean use);
/**
* Return false if this cart should not call onMinecartPass() and should ignore Powered Rails.
* @return True if this cart should call onMinecartPass().
*/
default boolean shouldDoRailFunctions() {
return true;
}
/**
* Returns true if this cart is self propelled.
* @return True if powered.
*/
default boolean isPoweredCart() {
return self().getMinecartType() == AbstractMinecart.Type.FURNACE;
}
/**
* Returns true if this cart can be ridden by an Entity.
* @return True if this cart can be ridden.
*/
default boolean canBeRidden() {
return self().getMinecartType() == AbstractMinecart.Type.RIDEABLE;
}
/**
* Returns the carts max speed when traveling on rails. Carts going faster
* than 1.1 cause issues with chunk loading. Carts cant traverse slopes or
@@ -107,10 +75,6 @@ public interface IForgeAbstractMinecart
double getDragAir();
void setDragAir(double value);
default double getSlopeAdjustment() {
return 0.0078125D;
}
/**
* Called from Detector Rails to retrieve a redstone power level for comparators.
*/
@@ -666,7 +666,7 @@ public interface IForgeBlock {
* @param pos Block position in level
* @param explosion The explosion instance affecting the block
*/
default void onBlockExploded(BlockState state, Level level, BlockPos pos, Explosion explosion) {
default void onBlockExploded(BlockState state, ServerLevel level, BlockPos pos, Explosion explosion) {
level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3);
self().wasExploded(level, pos, explosion);
}
@@ -575,7 +575,7 @@ public interface IForgeBlockState {
* @param pos Block position in level
* @param explosion The explosion instance affecting the block
*/
default void onBlockExploded(Level level, BlockPos pos, Explosion explosion) {
default void onBlockExploded(ServerLevel level, BlockPos pos, Explosion explosion) {
self().getBlock().onBlockExploded(self(), level, pos, explosion);
}
@@ -11,7 +11,7 @@ import java.util.function.BiPredicate;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.entity.boss.enderdragon.EnderDragon;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.entity.vehicle.AbstractBoat;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.entity.Entity;
@@ -19,6 +19,7 @@ import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.world.level.material.FluidState;
@@ -115,7 +116,7 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag> {
* @param fallDistance The fall distance
* @return {@code true} if this entity can trample, {@code false} otherwise
*/
boolean canTrample(BlockState state, BlockPos pos, float fallDistance);
boolean canTrample(ServerLevel level, BlockState state, BlockPos pos, float fallDistance);
/**
* Returns The classification of this entity
@@ -381,13 +382,13 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag> {
/**
* When {@code false}, the fluid will no longer update its height value while
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
* within a boat while it is not within a fluid ({@link AbstractBoat#isUnderWater()}.
*
* @param state the state of the fluid the rider is within
* @param boat the boat the rider is within that is not inside a fluid
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateFluidWhileBoating(FluidState state, Boat boat) {
default boolean shouldUpdateFluidWhileBoating(FluidState state, AbstractBoat boat) {
return boat.shouldUpdateFluidWhileRiding(state, self());
}
}
@@ -6,13 +6,13 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.entity.vehicle.AbstractBoat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.PathType;
@@ -68,7 +68,7 @@ public interface IForgeFluid {
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(FluidState state, Level level, BlockPos pos) {
default boolean canConvertToSource(FluidState state, ServerLevel level, BlockPos pos) {
return getFluidType().canConvertToSource(state, level, pos);
}
@@ -79,20 +79,20 @@ public interface IForgeFluid {
* @param boat the boat trying to be used on the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean supportsBoating(FluidState state, Boat boat) {
default boolean supportsBoating(FluidState state, AbstractBoat boat) {
return getFluidType().supportsBoating(state, boat);
}
/**
* When {@code false}, the fluid will no longer update its height value while
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
* within a boat while it is not within a fluid ({@link AbstractBoat#isUnderWater()}.
*
* @param state the state of the fluid the rider is within
* @param boat the boat the rider is within that is not inside a fluid
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateWhileBoating(FluidState state, Boat boat, Entity rider) {
default boolean shouldUpdateWhileBoating(FluidState state, AbstractBoat boat, Entity rider) {
return getFluidType().shouldUpdateWhileBoating(state, boat, rider);
}
@@ -6,13 +6,14 @@
package net.minecraftforge.common.extensions;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.vehicle.AbstractBoat;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.pathfinder.PathType;
@@ -67,7 +68,7 @@ public interface IForgeFluidState {
* @param pos the location of the fluid
* @return {@code true} if the fluid can create a source, {@code false} otherwise
*/
default boolean canConvertToSource(Level level, BlockPos pos) {
default boolean canConvertToSource(ServerLevel level, BlockPos pos) {
return self().getType().canConvertToSource(self(), level, pos);
}
@@ -77,7 +78,7 @@ public interface IForgeFluidState {
* @param boat the boat trying to be used on the fluid
* @return {@code true} if the boat can be used, {@code false} otherwise
*/
default boolean supportsBoating(Boat boat) {
default boolean supportsBoating(AbstractBoat boat) {
return self().getType().supportsBoating(self(), boat);
}
@@ -89,7 +90,7 @@ public interface IForgeFluidState {
* @param rider the rider of the boat
* @return {@code true} if the fluid height should be updated, {@code false} otherwise
*/
default boolean shouldUpdateWhileBoating(Boat boat, Entity rider) {
default boolean shouldUpdateWhileBoating(AbstractBoat boat, Entity rider) {
return self().getType().shouldUpdateWhileBoating(self(), boat, rider);
}
@@ -1,132 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.extensions;
import com.google.common.base.Preconditions;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.RegistryManager;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
/**
* Extension-Interface providing methods for writing registry-id's instead of their registry-names.
* /
public interface IForgeFriendlyByteBuf {
private FriendlyByteBuf self() {
return (FriendlyByteBuf)this;
}
/**
* Writes the given entries integer id to the buffer. Notice however that this will only write the id of the given entry and will not check whether it actually exists
* in the given registry. Therefore no safety checks can be performed whilst reading it and if the entry is not in the registry a default value will be written.
* @param registry The registry containing the given entry
* @param entry The entry who's registryName is to be written
* @param <T> The type of the entry.
* /
default <T> void writeRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry, @NotNull T entry) {
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
int id = forgeRegistry.getID(entry);
self().writeVarInt(id);
}
/**
* Writes the given entries integer id to the buffer. Notice however that this will only write the id of the given entry and will not check whether it actually exists
* in the given registry. Therefore no safety checks can be performed whilst reading it and if the entry is not in the registry a default value will be written.
* @param registry The registry containing the entry represented by this key
* @param entryKey The registry-name of an entry in this {@link IForgeRegistry}
* /
default void writeRegistryIdUnsafe(@NotNull IForgeRegistry<?> registry, @NotNull ResourceLocation entryKey) {
ForgeRegistry<?> forgeRegistry = (ForgeRegistry<?>) registry;
int id = forgeRegistry.getID(entryKey);
self().writeVarInt(id);
}
/**
* Reads an integer value from the buffer, which will be interpreted as an registry-id in the given registry. Notice that if there is no value in the specified registry for the
* read id, that the registry's default value will be returned.
* @param registry The registry containing the entry
* /
default <T> T readRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry) {
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
int id = self().readVarInt();
return forgeRegistry.getValue(id);
}
/**
* Writes a given registry-entry's integer id to the specified buffer in combination with writing the containing registry's id. In contrast to
* {@link #writeRegistryIdUnsafe(IForgeRegistry, Object)} this method checks every single step performed as well as
* writing the registry-id to the buffer, in order to prevent any unexpected behaviour. Therefore this method is to be preferred whenever possible,
* over using the unsafe methods.
*
* @param registry The registry containing the entry
* @param entry The entry to write
* @param <T> The type of the registry-entry
* @throws NullPointerException if the registry or entry was null
* @throws IllegalArgumentException if the registry does not contain the specified value
* /
default <T> void writeRegistryId(@NotNull IForgeRegistry<T> registry, @NotNull T entry) {
Objects.requireNonNull(registry, "Cannot write a null registry key!");
Objects.requireNonNull(entry,"Cannot write a null registry entry!");
ResourceLocation name = registry.getRegistryName();
Preconditions.checkArgument(registry.containsValue(entry), "Cannot find %s in %s", registry.getKey(entry) != null ? registry.getKey(entry) : entry, name);
ForgeRegistry<T> reg = (ForgeRegistry<T>) registry;
self().writeResourceLocation(name); //TODO change to writing a varInt once registries use id's
self().writeVarInt(reg.getID(entry));
}
/**
* Reads an registry-entry from the specified buffer. Notice however that the type cannot be checked without providing an additional class parameter
* - see {@link #readRegistryIdSafe(Class)} for an safe version.
* @param <T> The type of the registry-entry. Notice that this should match the actual type written to the buffer.
* @throws NullPointerException if the registry could not be found.
* /
default <T> T readRegistryId() {
ResourceLocation location = self().readResourceLocation(); //TODO change to reading a varInt once registries use id's
ForgeRegistry<T> registry = RegistryManager.ACTIVE.getRegistry(location);
return registry.getValue(self().readVarInt());
}
/**
* Reads an registry-entry from the specified buffer. This method also verifies, that the value read is of the appropriate type.
* @param <T> The type of the registry-entry.
* @throws IllegalArgumentException if the retrieved entries registryType doesn't match the one passed in.
* @throws NullPointerException if the registry could not be found.
* /
default <T> T readRegistryIdSafe(Class<? super T> registrySuperType) {
T value = readRegistryId();
if (!registrySuperType.isAssignableFrom(value.getClass()))
throw new IllegalArgumentException("Attempted to read an registryValue of the wrong type from the Buffer!");
return value;
}
/**
* Writes a FluidStack to the packet buffer, easy enough. If EMPTY, writes a FALSE.
* This behavior provides parity with the ItemStack method in PacketBuffer.
*
* @param stack FluidStack to be written to the packet buffer.
* /
default void writeFluidStack(FluidStack stack) {
if (stack.isEmpty())
self().writeBoolean(false);
else {
self().writeBoolean(true);
stack.writeToPacket(self());
}
}
/**
* Reads a FluidStack from this buffer.
* /
default FluidStack readFluidStack() {
return !self().readBoolean() ? FluidStack.EMPTY : FluidStack.readFromPacket(self());
}
}
*/
@@ -50,6 +50,7 @@ public interface IForgeGameTestHelper {
}
};
var connection = new Connection(PacketFlow.SERVERBOUND);
@SuppressWarnings("unused") // The constructor has side effects
var channel = new EmbeddedChannel(connection);
var server = level.getServer();
@@ -10,25 +10,22 @@ import java.util.function.Consumer;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.*;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.monster.piglin.PiglinAi;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.InteractionResult;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.ToolAction;
@@ -43,21 +40,6 @@ public interface IForgeItem {
return (Item)this;
}
/**
* @deprecated In favor of {@link #getDefaultAttributeModifiers(ItemStack)} as it matches vanilla name, and not all cases that call this has the EquipmentSlot argument
*/
@Deprecated(forRemoval = true, since = "1.21")
default ItemAttributeModifiers getAttributeModifiers(EquipmentSlot slot, ItemStack stack) {
return getDefaultAttributeModifiers(stack);
}
/**
* ItemStack sensitive version of {@link Item#getDefaultAttributeModifiers}
*/
default ItemAttributeModifiers getDefaultAttributeModifiers(ItemStack stack) {
return self().getDefaultAttributeModifiers();
}
/**
* Called when a player drops the item into the world, returning false from this
* will prevent the item from being removed from the players inventory and
@@ -110,7 +92,7 @@ public interface IForgeItem {
* @return True if piglins are neutral to players wearing this item in an armor slot
*/
default boolean makesPiglinsNeutral(ItemStack stack, LivingEntity wearer) {
return stack.getItem() instanceof ArmorItem && ((ArmorItem) stack.getItem()).getMaterial() == ArmorMaterials.GOLD;
return stack.is(ItemTags.PIGLIN_SAFE_ARMOR);
}
/**
@@ -163,28 +145,15 @@ public interface IForgeItem {
}
/**
* ItemStack sensitive version of {@link Item#getCraftingRemainingItem()}.
* ItemStack sensitive version of {@link Item#getCraftingRemainder()}.
* Returns a full ItemStack instance of the result.
*
* @param itemStack The current ItemStack
* @return The resulting ItemStack
*/
@SuppressWarnings("deprecation")
default ItemStack getCraftingRemainingItem(ItemStack itemStack) {
if (!hasCraftingRemainingItem(itemStack))
return ItemStack.EMPTY;
return new ItemStack(self().getCraftingRemainingItem());
}
/**
* ItemStack sensitive version of {@link Item#hasCraftingRemainingItem()}.
*
* @param stack The current item stack
* @return True if this item has a crafting remaining item
*/
@SuppressWarnings("deprecation")
default boolean hasCraftingRemainingItem(ItemStack stack) {
return self().hasCraftingRemainingItem();
default ItemStack getCraftingRemainder(ItemStack itemStack) {
return self().getCraftingRemainder();
}
/**
@@ -324,10 +293,12 @@ public interface IForgeItem {
* @param inner Weither or not to use the inner texture layer.
* @return Path of texture to bind, or null to use default
*/
/*
@Nullable
default ResourceLocation getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, ArmorMaterial.Layer layer, boolean inner) {
default ResourceLocation getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, EquipmentModel.Layer layer, boolean inner) {
return null;
}
*/
/**
* Called when a entity tries to play the 'swing' animation.
@@ -350,17 +321,6 @@ public interface IForgeItem {
return false;
}
/**
* ItemStack sensitive version of {@link Item#getEnchantmentValue()}.
*
* @param stack The ItemStack
* @return the enchantment value
*/
@SuppressWarnings("deprecation")
default int getEnchantmentValue(ItemStack stack) {
return self().getEnchantmentValue();
}
/**
* Checks whether an item can be enchanted with a certain enchantment. This
* applies specifically to enchanting an item in the enchanting table and is
@@ -512,15 +472,15 @@ public interface IForgeItem {
}
/**
* Whether this Item can be used to hide player head for enderman.
* Whether this Item can be used to hide player the player from a monster
*
* @param stack the ItemStack
* @param player The player watching the enderman
* @param endermanEntity The enderman that the player look
* @return true if this Item can be used to hide player head for enderman
* @param player The player watching the monster
* @param monster The monster that the player look
* @return true if this Item can be used to hide player from monsters
*/
default boolean isEnderMask(ItemStack stack, Player player, EnderMan endermanEntity) {
return stack.getItem() == Blocks.CARVED_PUMPKIN.asItem();
default boolean isMonsterDisguise(ItemStack stack, Player player, Monster monster) {
return stack.is(ItemTags.GAZE_DISGUISE_EQUIPMENT);
}
/**
@@ -6,7 +6,7 @@
package net.minecraftforge.common.extensions;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.monster.EnderMan;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
@@ -18,10 +18,8 @@ import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.stats.Stats;
import net.minecraft.world.InteractionResult;
@@ -43,22 +41,13 @@ public interface IForgeItemStack {
}
/**
* ItemStack sensitive version of {@link Item#getCraftingRemainingItem()}.
* ItemStack sensitive version of {@link Item#getCraftingRemainder()}.
* Returns a full ItemStack instance of the result.
*
* @return The resulting ItemStack
*/
default ItemStack getCraftingRemainingItem() {
return self().getItem().getCraftingRemainingItem(self());
}
/**
* ItemStack sensitive version of {@link Item#hasCraftingRemainingItem()}.
*
* @return True if this item has a crafting remaining item
*/
default boolean hasCraftingRemainingItem() {
return self().getItem().hasCraftingRemainingItem(self());
default ItemStack getCraftingRemainder() {
return self().getItem().getCraftingRemainder(self());
}
/**
@@ -139,15 +128,6 @@ public interface IForgeItemStack {
return self().getItem().canApplyAtEnchantingTable(self(), enchantment);
}
/**
* ItemStack sensitive version of {@link Item#getEnchantmentValue()}.
*
* @return the enchantment value of this ItemStack
*/
default int getEnchantmentValue() {
return self().getItem().getEnchantmentValue(self());
}
/**
* Override this to set a non-default armor slot for an ItemStack, but <em>do
* not use this to get the armor slot of said stack; for that, use
@@ -316,14 +296,14 @@ public interface IForgeItemStack {
}
/**
* Whether this Item can be used to hide player head for enderman.
* Whether this Item can be used to hide player from enderman/Creaking.
*
* @param player The player watching the enderman
* @param endermanEntity The enderman that the player look
* @param monster The monster you're trying to hide from
* @return true if this Item can be used.
*/
default boolean isEnderMask(Player player, EnderMan endermanEntity) {
return self().getItem().isEnderMask(self(), player, endermanEntity);
default boolean isMonsterDisguise(Player player, Monster monster) {
return self().getItem().isMonsterDisguise(self(), player, monster);
}
/**
@@ -405,11 +385,4 @@ public interface IForgeItemStack {
default boolean canGrindstoneRepair() {
return self().getItem().canGrindstoneRepair(self());
}
/**
* ItemStack and Slot sensitive version of {@link Item#getItemAttributeModifiers}
*/
default ItemAttributeModifiers getDefaultAttributeModifiers() {
return self().getItem().getDefaultAttributeModifiers(self());
}
}
@@ -37,6 +37,6 @@ public interface IForgeResourceKey<T> {
*/
default Holder<T> getOrThrow(RegistryAccess registryAccess) {
Objects.requireNonNull(registryAccess, "registryAccess was null");
return registryAccess.registryOrThrow(self().registryKey()).getHolderOrThrow(self());
return registryAccess.lookupOrThrow(self().registryKey()).getOrThrow(self());
}
}
@@ -9,9 +9,9 @@ import com.google.common.collect.ImmutableSet;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.context.ContextKey;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParam;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType;
@@ -35,13 +35,13 @@ public record CanToolPerformAction(ToolAction action) implements LootItemConditi
}
@Override
public @NotNull Set<LootContextParam<?>> getReferencedContextParams() {
public @NotNull Set<ContextKey<?>> getReferencedContextParams() {
return ImmutableSet.of(LootContextParams.TOOL);
}
@Override
public boolean test(LootContext ctx) {
ItemStack itemstack = ctx.getParamOrNull(LootContextParams.TOOL);
ItemStack itemstack = ctx.getOptionalParameter(LootContextParams.TOOL);
return itemstack != null && itemstack.canPerformAction(this.action);
}
@@ -14,8 +14,8 @@ import com.mojang.serialization.MapCodec;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemConditions;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.NotNull;
@@ -49,7 +49,7 @@ public interface IGlobalLootModifier {
* @return modified loot drops
*/
@NotNull
ObjectArrayList<ItemStack> apply(ObjectArrayList<ItemStack> generatedLoot, LootContext context);
ObjectArrayList<ItemStack> apply(LootTable table, ObjectArrayList<ItemStack> generatedLoot, LootContext context);
/**
* Returns the registered codec for this modifier
@@ -15,6 +15,7 @@ import net.minecraft.Util;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.levelgen.feature.trunkplacers.BendingTrunkPlacer;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import org.jetbrains.annotations.NotNull;
@@ -51,8 +52,8 @@ public abstract class LootModifier implements IGlobalLootModifier {
@NotNull
@Override
public final ObjectArrayList<ItemStack> apply(ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
return this.combinedConditions.test(context) ? this.doApply(generatedLoot, context) : generatedLoot;
public final ObjectArrayList<ItemStack> apply(LootTable table, ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
return this.combinedConditions.test(context) ? this.doApply(table, generatedLoot, context) : generatedLoot;
}
/**
@@ -63,5 +64,5 @@ public abstract class LootModifier implements IGlobalLootModifier {
* @return modified loot drops
*/
@NotNull
protected abstract ObjectArrayList<ItemStack> doApply(ObjectArrayList<ItemStack> generatedLoot, LootContext context);
protected abstract ObjectArrayList<ItemStack> doApply(LootTable table, ObjectArrayList<ItemStack> generatedLoot, LootContext context);
}
@@ -22,20 +22,21 @@ import com.google.gson.JsonObject;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.util.GsonHelper;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.HolderLookup;
import net.minecraft.resources.ResourceLocation;
public class LootModifierManager extends SimpleJsonResourceReloadListener {
public class LootModifierManager extends SimpleJsonResourceReloadListener<JsonElement> {
private static final Logger LOGGER = LogManager.getLogger();
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final String FOLDER = "loot_modifiers";
private final RegistryAccess registries;
private final HolderLookup.Provider registries;
private Map<ResourceLocation, IGlobalLootModifier> modifiers = ImmutableMap.of();
public LootModifierManager(RegistryAccess registries) {
super(GSON, FOLDER);
public LootModifierManager(HolderLookup.Provider registries) {
super(registries, ExtraCodecs.JSON, FOLDER);
this.registries = registries;
}
@@ -1,22 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.util;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.saveddata.SavedData;
public class DummySavedData extends SavedData {
public static final DummySavedData DUMMY = new DummySavedData();
private DummySavedData() {
super();
}
@Override
public CompoundTag save(final CompoundTag compound, HolderLookup.Provider lookup) {
return null;
}
}
@@ -11,8 +11,7 @@ import java.util.List;
import java.util.Queue;
import java.util.function.Predicate;
public class RecipeMatcher
{
public class RecipeMatcher {
/**
* Attempts to match inputs to the specified tests. In the best way that all inputs are used by one test.
* Will return null in any of these cases:
@@ -23,8 +22,7 @@ public class RecipeMatcher
*
* @return An array mapping inputs to tests. ret[x] = y means input[x] = test[y]
*/
public static <T> int[] findMatches(List<T> inputs, List<? extends Predicate<T>> tests)
{
public static <T> int[] findMatches(List<T> inputs, List<? extends Predicate<T>> tests) {
int elements = inputs.size();
if (elements != tests.size())
return null; // There will not be a 1:1 mapping of inputs -> tests
@@ -35,19 +33,16 @@ public class RecipeMatcher
// [UnusedInputs] [UnusedIngredients] [IngredientMatchMask]...
BitSet data = new BitSet((elements + 2) * elements);
for (int x = 0; x < elements; x++)
{
for (int x = 0; x < elements; x++) {
int matched = 0;
int offset = (x + 2) * elements;
Predicate<T> test = tests.get(x);
for (int y = 0; y < elements; y++)
{
for (int y = 0; y < elements; y++) {
if (data.get(y))
continue;
if (test.test(inputs.get(y)))
{
if (test.test(inputs.get(y))) {
data.set(offset + y);
matched++;
}
@@ -56,8 +51,7 @@ public class RecipeMatcher
if (matched == 0)
return null; //We have an test that matched non of the inputs
if (matched == 1)
{
if (matched == 1) {
if (!claim(ret, data, x, elements))
return null; //We failed to claim this index, which means it caused something else to go to 0 matches, which makes the whole thing fail
}
@@ -66,7 +60,7 @@ public class RecipeMatcher
if (data.nextClearBit(0) >= elements) //All items have been used, which means all tests have a match!
return ret;
// We should be in a state where multiple tests are satified by multiple inputs. So we need to try a branching recursive test.
// We should be in a state where multiple tests are satisfied by multiple inputs. So we need to try a branching recursive test.
// However for performance reasons, we should probably make that check a sub-set of the entire graph.
if (backtrack(data, ret, 0, elements))
return ret;
@@ -75,13 +69,11 @@ public class RecipeMatcher
}
// This is bad... need to think of a better cascade, recursion instead of stack?
private static boolean claim(int[] ret, BitSet data, int claimed, int elements)
{
private static boolean claim(int[] ret, BitSet data, int claimed, int elements) {
Queue<Integer> pending = new LinkedList<Integer>();
pending.add(claimed);
while (pending.peek() != null)
{
while (pending.peek() != null) {
int test = pending.poll();
int offset = (test + 2) * elements;
int used = data.nextSetBit(offset) - offset;
@@ -93,11 +85,9 @@ public class RecipeMatcher
data.set(elements + test);
ret[used] = test;
for (int x = 0; x < elements; x++)
{
for (int x = 0; x < elements; x++) {
offset = (x + 2) * elements;
if (data.get(offset + used) && !data.get(elements + x))
{
if (data.get(offset + used) && !data.get(elements + x)) {
data.clear(offset + used);
int count = 0;
for (int y = offset; y < offset + elements; y++)
@@ -117,32 +107,29 @@ public class RecipeMatcher
}
//We use recursion here, why? Because I feel like it. Also because we should only ever be working in data sets < 9
private static boolean backtrack(BitSet data, int[] ret, int start, int elements)
{
int test = data.nextClearBit(elements + start) - elements;
if (test >= elements)
return true; //Could not find the next unused test.
private static boolean backtrack(BitSet data, int[] ret, int start, int elements) {
int test = data.nextClearBit(elements + start) - elements;
if (test >= elements)
return true; //Could not find the next unused test.
if (test < 0)
throw new IllegalStateException("This should never happen, negative test in backtrack!");
if (test < 0)
throw new IllegalStateException("This should never happen, negative test in backtrack!");
int offset = (test + 2) * elements;
for (int x = 0; x < elements; x++)
{
if (!data.get(offset + x) || data.get(x))
continue;
int offset = (test + 2) * elements;
for (int x = 0; x < elements; x++) {
if (!data.get(offset + x) || data.get(x))
continue;
data.set(x);
data.set(x);
if (backtrack(data, ret, test + 1, elements))
{
ret[x] = test;
return true;
if (backtrack(data, ret, test + 1, elements)) {
ret[x] = test;
return true;
}
data.clear(x);
}
data.clear(x);
}
return false;
return false;
}
}
@@ -1,41 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.world;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.core.Holder;
import net.minecraft.world.level.biome.BiomeGenerationSettings;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver;
import net.minecraft.world.level.levelgen.placement.PlacedFeature;
public class BiomeGenerationSettingsBuilder extends BiomeGenerationSettings.PlainBuilder
{
public BiomeGenerationSettingsBuilder(BiomeGenerationSettings orig)
{
for (GenerationStep.Carving k : orig.getCarvingStages()) {
carvers.put(k, new ArrayList<>());
for (Holder<ConfiguredWorldCarver<?>> v : orig.getCarvers(k)) {
carvers.get(k).add(v);
}
}
orig.features().forEach(l -> {
final ArrayList<Holder<PlacedFeature>> featureList = new ArrayList<>();
l.forEach(featureList::add);
features.add(featureList);
});
}
public List<Holder<PlacedFeature>> getFeatures(GenerationStep.Decoration stage) {
addFeatureStepsUpTo(stage.ordinal());
return features.get(stage.ordinal());
}
public List<Holder<ConfiguredWorldCarver<?>>> getCarvers(GenerationStep.Carving stage) {
return carvers.computeIfAbsent(stage, key -> new ArrayList<>());
}
}
@@ -56,7 +56,7 @@ public final class ForgeBiomeModifiers {
@Override
public void modify(Holder<Biome> biome, Phase phase, Builder builder) {
if (phase == Phase.ADD && this.biomes.contains(biome)) {
BiomeGenerationSettingsBuilder generationSettings = builder.getGenerationSettings();
var generationSettings = builder.getGenerationSettings();
this.features.forEach(holder -> generationSettings.addFeature(this.step, holder));
}
}
@@ -105,7 +105,7 @@ public final class ForgeBiomeModifiers {
@Override
public void modify(Holder<Biome> biome, Phase phase, Builder builder) {
if (phase == Phase.REMOVE && this.biomes.contains(biome)) {
BiomeGenerationSettingsBuilder generationSettings = builder.getGenerationSettings();
var generationSettings = builder.getGenerationSettings();
for (Decoration step : this.steps)
generationSettings.getFeatures(step).removeIf(this.features::contains);
}
@@ -24,76 +24,67 @@ import net.minecraft.world.level.biome.MobSpawnSettings;
* Memoizers are not used because it's important to return null
* without evaluating the biome info if it's accessed outside of a server context.
*/
public class ModifiableBiomeInfo
{
public class ModifiableBiomeInfo {
@NotNull
private final BiomeInfo originalBiomeInfo;
@Nullable
private BiomeInfo modifiedBiomeInfo = null;
/**
* @param originalBiomeInfo BiomeInfo representing the original state of a biome when the biome was constructed.
*/
public ModifiableBiomeInfo(@NotNull final BiomeInfo originalBiomeInfo)
{
public ModifiableBiomeInfo(@NotNull final BiomeInfo originalBiomeInfo) {
this.originalBiomeInfo = originalBiomeInfo;
}
/**
* {@return The modified biome info if modified biome info has been generated, otherwise gets original biome info}
*/
@NotNull
public BiomeInfo get()
{
public BiomeInfo get() {
return this.modifiedBiomeInfo == null
? originalBiomeInfo
: modifiedBiomeInfo;
}
/**
* {@return The original biome info that the associated biome was created with}
*/
@NotNull
public BiomeInfo getOriginalBiomeInfo()
{
public BiomeInfo getOriginalBiomeInfo() {
return this.originalBiomeInfo;
}
/**
* {@return Modified biome info; null if it hasn't been set yet}
*/
@Nullable
public BiomeInfo getModifiedBiomeInfo()
{
public BiomeInfo getModifiedBiomeInfo() {
return this.modifiedBiomeInfo;
}
/**
* Internal forge method; the game will crash if mods invoke this.
* Creates and caches the modified biome info.
* @param biome named biome with original data.
* @param biomeModifiers biome modifiers to apply.
*
*
* @throws IllegalStateException if invoked more than once.
*/
@ApiStatus.Internal
public void applyBiomeModifiers(final Holder<Biome> biome, final List<BiomeModifier> biomeModifiers)
{
public void applyBiomeModifiers(final Holder<Biome> biome, final List<BiomeModifier> biomeModifiers) {
if (this.modifiedBiomeInfo != null)
throw new IllegalStateException(String.format(Locale.ENGLISH, "Biome %s already modified", biome));
BiomeInfo original = this.getOriginalBiomeInfo();
final BiomeInfo.Builder builder = BiomeInfo.Builder.copyOf(original);
for (BiomeModifier.Phase phase : BiomeModifier.Phase.values())
{
for (BiomeModifier modifier : biomeModifiers)
{
var original = this.getOriginalBiomeInfo();
var builder = BiomeInfo.Builder.copyOf(original);
for (var phase : BiomeModifier.Phase.values()) {
for (var modifier : biomeModifiers)
modifier.modify(biome, phase, builder);
}
}
this.modifiedBiomeInfo = builder.build();
}
/**
* Record containing raw biome data.
* @param climateSettings Weather and temperature settings.
@@ -101,26 +92,24 @@ public class ModifiableBiomeInfo
* @param generationSettings Worldgen features and carvers.
* @param mobSpawnSettings Mob spawn settings.
*/
public record BiomeInfo(ClimateSettings climateSettings, BiomeSpecialEffects effects, BiomeGenerationSettings generationSettings, MobSpawnSettings mobSpawnSettings)
{
public static class Builder
{
public record BiomeInfo(ClimateSettings climateSettings, BiomeSpecialEffects effects, BiomeGenerationSettings generationSettings, MobSpawnSettings mobSpawnSettings) {
public static class Builder {
private ClimateSettingsBuilder climateSettings;
private BiomeSpecialEffectsBuilder effects;
private BiomeGenerationSettingsBuilder generationSettings;
private BiomeGenerationSettings.PlainBuilder generationSettings;
private MobSpawnSettingsBuilder mobSpawnSettings;
/**
* @param original the biome to copy
* @return A ModifiedBiomeInfo.Builder with a copy of the biome's data
*/
public static Builder copyOf(final BiomeInfo original)
{
public static Builder copyOf(final BiomeInfo original) {
final ClimateSettingsBuilder climateBuilder = ClimateSettingsBuilder.copyOf(original.climateSettings());
final BiomeSpecialEffectsBuilder effectsBuilder = BiomeSpecialEffectsBuilder.copyOf(original.effects());
final BiomeGenerationSettingsBuilder generationBuilder = new BiomeGenerationSettingsBuilder(original.generationSettings());
final var generationBuilder = new BiomeGenerationSettings.PlainBuilder();
generationBuilder.addFrom(original.generationSettings());
final MobSpawnSettingsBuilder mobSpawnBuilder = new MobSpawnSettingsBuilder(original.mobSpawnSettings());
return new Builder(
climateBuilder,
effectsBuilder,
@@ -128,37 +117,31 @@ public class ModifiableBiomeInfo
mobSpawnBuilder
);
}
private Builder(final ClimateSettingsBuilder climateSettings, final BiomeSpecialEffectsBuilder effects, final BiomeGenerationSettingsBuilder generationSettings, final MobSpawnSettingsBuilder mobSpawnSettings)
{
private Builder(final ClimateSettingsBuilder climateSettings, final BiomeSpecialEffectsBuilder effects, final BiomeGenerationSettings.PlainBuilder generationSettings, final MobSpawnSettingsBuilder mobSpawnSettings) {
this.climateSettings = climateSettings;
this.effects = effects;
this.generationSettings = generationSettings;
this.mobSpawnSettings = mobSpawnSettings;
}
public BiomeInfo build()
{
public BiomeInfo build() {
return new BiomeInfo(this.climateSettings.build(), this.effects.build(), this.generationSettings.build(), this.mobSpawnSettings.build());
}
public ClimateSettingsBuilder getClimateSettings()
{
public ClimateSettingsBuilder getClimateSettings() {
return climateSettings;
}
public BiomeSpecialEffectsBuilder getSpecialEffects()
{
public BiomeSpecialEffectsBuilder getSpecialEffects() {
return effects;
}
public BiomeGenerationSettingsBuilder getGenerationSettings()
{
public BiomeGenerationSettings.PlainBuilder getGenerationSettings() {
return generationSettings;
}
public MobSpawnSettingsBuilder getMobSpawnSettings()
{
public MobSpawnSettingsBuilder getMobSpawnSettings() {
return mobSpawnSettings;
}
}