Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* Copyright (c) NeoForged and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/

package net.neoforged.neoforge.common.util;

import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import net.minecraft.core.Holder;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import org.jspecify.annotations.Nullable;

/**
* Advanced version of {@link ItemAttributeModifiers.Builder} which supports removal and better sanity-checking.
* <p>
* The original builder only supports additions and does not guarantee that no duplicate modifiers exist for a given id.
*/
public class ItemAttributeModifiersBuilder {
private List<ItemAttributeModifiers.Entry> entries;
private Map<Key, ItemAttributeModifiers.Entry> entriesByKey;

public ItemAttributeModifiersBuilder(ItemAttributeModifiers defaultModifiers) {
this.entries = new LinkedList<>();
this.entriesByKey = new HashMap<>(defaultModifiers.modifiers().size());

for (ItemAttributeModifiers.Entry entry : defaultModifiers.modifiers()) {
entries.add(entry);
entriesByKey.put(new Key(entry.attribute(), entry.modifier().id()), entry);
}
}

/**
* Do not use the returned value to create an {@link ItemAttributeModifiers}
* since the underlying list is not immutable, instead use {@link #build}.
*
* @return an unmodifiable view of the underlying entry list.
*/
public List<ItemAttributeModifiers.Entry> getEntryView() {
return Collections.unmodifiableList(this.entries);
}

/**
* Attempts to add a new modifier, refusing if one is already present with the same id.
*
* @return true if the modifier was added
*/
public boolean addModifier(Holder<Attribute> attribute, AttributeModifier modifier, EquipmentSlotGroup slot) {
Key key = new Key(attribute, modifier.id());
if (entriesByKey.containsKey(key)) {
return false;
}

ItemAttributeModifiers.Entry entry = new ItemAttributeModifiers.Entry(attribute, modifier, slot);
entries.add(entry);
entriesByKey.put(key, entry);
return true;
}

/**
* Removes a modifier for the target attribute with the given id.
*
* @return true if a modifier was removed
*/
public boolean removeModifier(Holder<Attribute> attribute, Identifier id) {
ItemAttributeModifiers.Entry entry = entriesByKey.remove(new Key(attribute, id));

if (entry != null) {
entries.remove(entry);
return true;
}

return false;
}

/**
* Adds a modifier to the list, replacing any existing modifiers with the same id.
*
* @return the previous modifier, or null if there was no previous modifier with the same id
*/
public ItemAttributeModifiers.@Nullable Entry replaceModifier(Holder<Attribute> attribute, AttributeModifier modifier, EquipmentSlotGroup slot) {
Key key = new Key(attribute, modifier.id());
ItemAttributeModifiers.Entry entry = new ItemAttributeModifiers.Entry(attribute, modifier, slot);
if (entriesByKey.containsKey(key)) {
ItemAttributeModifiers.Entry previousEntry = entriesByKey.get(key);
int index = entries.indexOf(previousEntry);
if (index != -1) {
entries.set(index, entry);
} else { // This should never happen, but it can't hurt to have anyways
entries.add(entry);
}
entriesByKey.put(key, entry);
return previousEntry;
} else {
entries.add(entry);
entriesByKey.put(key, entry);
return null;
}
}

/**
* Removes modifiers based on a condition.
*
* @return true if any modifiers were removed
*/
public boolean removeIf(Predicate<ItemAttributeModifiers.Entry> condition) {
this.entries.removeIf(condition);
return this.entriesByKey.values().removeIf(condition);
}

public void clear() {
this.entries.clear();
this.entriesByKey.clear();
}

public ItemAttributeModifiers build() {
return new ItemAttributeModifiers(ImmutableList.copyOf(this.entries));
}

/**
* Internal key class. Attribute modifiers are unique by id for each Attribute.
*/
private record Key(Holder<Attribute> attr, Identifier id) {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@

package net.neoforged.neoforge.event;

import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import net.minecraft.core.Holder;
import net.minecraft.core.component.DataComponents;
Expand All @@ -21,8 +16,8 @@
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.ItemAttributeModifiers;
import net.neoforged.bus.api.Event;
import net.neoforged.neoforge.common.util.ItemAttributeModifiersBuilder;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.Nullable;

/**
* This event is fired when the attributes for an item stack are queried (for any reason) through {@link ItemStack#getAttributeModifiers()}.
Expand Down Expand Up @@ -146,115 +141,4 @@ private ItemAttributeModifiersBuilder getBuilder() {

return this.builder;
}

/**
* Advanced version of {@link ItemAttributeModifiers.Builder} which supports removal and better sanity-checking.
* <p>
* The original builder only supports additions and does not guarantee that no duplicate modifiers exist for a given id.
*/
private static class ItemAttributeModifiersBuilder {
private List<ItemAttributeModifiers.Entry> entries;
private Map<Key, ItemAttributeModifiers.Entry> entriesByKey;

ItemAttributeModifiersBuilder(ItemAttributeModifiers defaultModifiers) {
this.entries = new LinkedList<>();
this.entriesByKey = new HashMap<>(defaultModifiers.modifiers().size());

for (ItemAttributeModifiers.Entry entry : defaultModifiers.modifiers()) {
entries.add(entry);
entriesByKey.put(new Key(entry.attribute(), entry.modifier().id()), entry);
}
}

/**
* {@return an unmodifiable view of the underlying entry list}
*/
List<ItemAttributeModifiers.Entry> getEntryView() {
return Collections.unmodifiableList(this.entries);
}

/**
* Attempts to add a new modifier, refusing if one is already present with the same id.
*
* @return true if the modifier was added
*/
boolean addModifier(Holder<Attribute> attribute, AttributeModifier modifier, EquipmentSlotGroup slot) {
Key key = new Key(attribute, modifier.id());
if (entriesByKey.containsKey(key)) {
return false;
}

ItemAttributeModifiers.Entry entry = new ItemAttributeModifiers.Entry(attribute, modifier, slot);
entries.add(entry);
entriesByKey.put(key, entry);
return true;
}

/**
* Removes a modifier for the target attribute with the given id.
*
* @return true if a modifier was removed
*/
boolean removeModifier(Holder<Attribute> attribute, Identifier id) {
ItemAttributeModifiers.Entry entry = entriesByKey.remove(new Key(attribute, id));

if (entry != null) {
entries.remove(entry);
return true;
}

return false;
}

/**
* Adds a modifier to the list, replacing any existing modifiers with the same id.
*
* @return the previous modifier, or null if there was no previous modifier with the same id
*/
ItemAttributeModifiers.@Nullable Entry replaceModifier(Holder<Attribute> attribute, AttributeModifier modifier, EquipmentSlotGroup slot) {
Key key = new Key(attribute, modifier.id());
ItemAttributeModifiers.Entry entry = new ItemAttributeModifiers.Entry(attribute, modifier, slot);
if (entriesByKey.containsKey(key)) {
ItemAttributeModifiers.Entry previousEntry = entriesByKey.get(key);
int index = entries.indexOf(previousEntry);
if (index != -1) {
entries.set(index, entry);
} else { // This should never happen, but it can't hurt to have anyways
entries.add(entry);
}
entriesByKey.put(key, entry);
return previousEntry;
} else {
entries.add(entry);
entriesByKey.put(key, entry);
return null;
}
}

/**
* Removes modifiers based on a condition.
*
* @return true if any modifiers were removed
*/
boolean removeIf(Predicate<ItemAttributeModifiers.Entry> condition) {
this.entries.removeIf(condition);
return this.entriesByKey.values().removeIf(condition);
}

void clear() {
this.entries.clear();
this.entriesByKey.clear();
}

public ItemAttributeModifiers build() {
return new ItemAttributeModifiers(ImmutableList.copyOf(this.entries));
}

/**
* Internal key class. Attribute modifiers are unique by id for each Attribute.
*/
private static record Key(Holder<Attribute> attr, Identifier id) {

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,21 @@

package net.neoforged.neoforge.event;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.core.component.DataComponentPatch;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.ItemLike;
import net.neoforged.bus.api.Event;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.event.IModBusEvent;
import net.neoforged.neoforge.common.CommonHooks;
import org.jetbrains.annotations.ApiStatus;

/**
Expand All @@ -24,15 +28,20 @@
* <p>
* Example usage:
* {@snippet :
* import net.minecraft.core.component.DataComponents;
* import net.minecraft.world.item.Items;
*
* public void modifyComponents(ModifyDefaultComponentsEvent event) {
* event.modify(Items.MELON_SEEDS, builder -> builder
* .set(DataComponents.MAX_STACK_SIZE, 16)); // Stack melon seeds to at most 16 items
*
* event.modify(Items.APPLE, builder -> builder
* .remove(DataComponents.FOOD)); // Remove the ability of eating apples
*
* event.modify(Items.GOLDEN_SWORD, builder -> builder.modify(DataComponents.ATTRIBUTE_MODIFIERS, orig -> {
* var attributes = new ItemAttributeModifiersBuilder(orig);
* attributes.replaceModifier(Attributes.ATTACK_DAMAGE, // Change golden swords base attack damage to +7
* new AttributeModifier(Item.BASE_ATTACK_DAMAGE_ID, 7, AttributeModifier.Operation.ADD_VALUE),
* EquipmentSlotGroup.MAINHAND);
* return attributes.build();
* }));
* }
*
* // Lowest priority listener
Expand All @@ -52,8 +61,8 @@ public ModifyDefaultComponentsEvent() {}
* @param item the item to modify the default components for
* @param patch the patch to apply
*/
public void modify(ItemLike item, Consumer<DataComponentPatch.Builder> patch) {
var builder = DataComponentPatch.builder();
public void modify(ItemLike item, Consumer<ModifyingBuilder> patch) {
var builder = new ModifyingBuilder(item.asItem().components());
patch.accept(builder);
var compPatch = builder.build();
if (!compPatch.isEmpty()) {
Expand All @@ -71,7 +80,7 @@ public void modify(ItemLike item, Consumer<DataComponentPatch.Builder> patch) {
* @param predicate the item filter
* @param patch the patch to apply
*/
public void modifyMatching(Predicate<? super Item> predicate, Consumer<DataComponentPatch.Builder> patch) {
public void modifyMatching(Predicate<? super Item> predicate, Consumer<ModifyingBuilder> patch) {
getAllItems().filter(predicate).forEach(item -> modify(item, patch));
}

Expand All @@ -81,4 +90,50 @@ public void modifyMatching(Predicate<? super Item> predicate, Consumer<DataCompo
public Stream<Item> getAllItems() {
return BuiltInRegistries.ITEM.stream();
}

/**
* An extension of the vanilla builder that includes some methods for modifying components either already in
* the builder or from a base set of components.
*/
public static class ModifyingBuilder extends DataComponentPatch.Builder {
private final DataComponentMap base;

private ModifyingBuilder(DataComponentMap baseComponents) {
base = baseComponents;
}

/**
* Modify an existing component. {@code modification} will only be called if the data component is present in
* the builder or in the base item's components, and has not been removed by another modification.
* To be able to remove a component, use {@link #modifyOptional}
*/
@SuppressWarnings("unchecked") // Safe provided the map keeps the guarantee that a DCT<T> maps to an Optional<T>
public <T> DataComponentPatch.Builder modify(DataComponentType<T> type, java.util.function.UnaryOperator<T> modification) {
if (map.containsKey(type)) {
Optional<T> val = ((Optional<T>) map.get(type)).map(modification);
val.ifPresent(CommonHooks::validateComponent);
map.put(type, val);
} else {
T val = base.get(type);
if (val != null) {
val = modification.apply(val);
CommonHooks.validateComponent(val);
map.put(type, Optional.of(val));
}
}
return this;
}

/**
* Modify a component, whether it's already present or not. Return {@link Optional#empty} to remove the component.
*/
@SuppressWarnings("unchecked") // Safe provided the map keeps the guarantee that a DCT<T> maps to an Optional<T>
public <T> DataComponentPatch.Builder modifyOptional(DataComponentType<T> type, java.util.function.UnaryOperator<Optional<T>> modification) {
Optional<T> val = map.containsKey(type) ? (Optional<T>) map.get(type) : Optional.ofNullable(base.get(type));
val = modification.apply(val);
val.ifPresent(CommonHooks::validateComponent);
map.put(type, val);
return this;
}
}
}
Loading
Loading