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
Expand Up @@ -6,6 +6,7 @@
import com.denizenscript.denizen.nms.interfaces.packets.PacketOutChat;
import com.denizenscript.denizen.objects.EntityTag;
import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizen.paper.datacomponents.ComponentAdaptersRegistry;
import com.denizenscript.denizen.paper.events.*;
import com.denizenscript.denizen.paper.properties.*;
import com.denizenscript.denizen.paper.tags.PaperTagBase;
Expand Down Expand Up @@ -127,6 +128,12 @@ public static void init() {
PropertyParser.registerProperty(EntityWitherInvulnerable.class, EntityTag.class);
PropertyParser.registerProperty(ItemArmorStand.class, ItemTag.class);

// Component adapters
if (NMSHandler.getVersion().isAtLeast(NMSVersion.v1_21)) {
PropertyParser.registerProperty(ItemRemoved.class, ItemTag.class);
ComponentAdaptersRegistry.register();
}

// Paper object extensions
PaperElementExtensions.register();
PaperEntityExtensions.register();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.denizenscript.denizen.paper.datacomponents;

public class ComponentAdaptersRegistry {

public static void register() {
DataComponentAdapter.register(new FoodAdapter());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package com.denizenscript.denizen.paper.datacomponents;

import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizen.objects.MaterialTag;
import com.denizenscript.denizen.objects.properties.item.ItemComponentsPatch;
import com.denizenscript.denizen.objects.properties.item.ItemProperty;
import com.denizenscript.denizen.utilities.Utilities;
import com.denizenscript.denizencore.objects.Mechanism;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.MapTag;
import com.denizenscript.denizencore.objects.properties.PropertyParser;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import io.papermc.paper.datacomponent.DataComponentType;
import org.bukkit.Material;
import org.bukkit.Registry;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

public abstract class DataComponentAdapter<TP, TD extends ObjectTag> {

// <--[language]
// @name Item Components
// @group Minecraft Logic
// @description
// Minecraft item components (see <@link url https://minecraft.wiki/w/Data_component_format>) are managed as follows:
// Each item type has a default set of component values; a food item will have food components by default, a tool item will have tool components by default, etc.
// Different items can override their type's default components, either by setting values that weren't there previously (e.g. making an inedible item edible), or by removing values that are there by default (e.g. making a shield item that can't block).
// Items' overrides can later be reset, making them use their type's default values again.
//
// In Denizen, different item components are represented by item properties.
// These properties allow both setting a component override on an item, and clearing/resetting it by providing no input.
// Item properties' name will generally match their respective item component's name, but not always!
// Due to this, features that take item component names as input (such as <@link tag ItemTag.is_overridden>) accept both Minecraft component names and Denizen property names.
//
// Here is an example of applying all of this in a script:
// <code>
// # We define a default apple item
// - define apple <item[apple]>
// # We remove the apple's "food" component, making eating it restore no food points (it is still consumable due to the "consumable" component).
// - adjust def:apple removed:food
// # This check will pass, as the apple's "food" component is overridden to have no value.
// - if <[apple].is_overridden[food]>:
// - narrate "The apple has a changed food component! It will behave differently to a normal apple."
// # We reset the apple item's food component, making it a normal apple.
// - adjust def:apple food:
// </code>
// -->

public static final Map<String, DataComponentType> COMPONENTS_BY_PROPERTY = new HashMap<>();
public static final String[] EMPTY_STRING_ARRAY = new String[0];

public static DataComponentType getComponentType(String name) {
String nameLower = CoreUtilities.toLowerCase(name);
DataComponentType componentType = Registry.DATA_COMPONENT_TYPE.get(Utilities.parseNamespacedKey(nameLower));
if (componentType == null) {
componentType = COMPONENTS_BY_PROPERTY.get(nameLower);
}
return componentType;
}

public static <TP, TD extends ObjectTag> void register(DataComponentAdapter<TP, TD> adapter) {
DataComponentAdapter.Property.currentlyRegisteringComponentAdapter = adapter;
PropertyParser.registerPropertyGetter(
item -> !item.getItemStack().isEmpty() ? adapter.new Property(item) : null,
ItemTag.class, EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY, DataComponentAdapter.Property.class);
DataComponentAdapter.Property.currentlyRegisteringComponentAdapter = null;
MaterialTag.tagProcessor.registerTag(adapter.denizenType, adapter.name, (attribute, materialTag) -> {
Material material = materialTag.getMaterial();
if (!material.isItem()) {
attribute.echoError("Cannot get item component values from a block material.");
return null;
}
TP internalValue = material.getDefaultData(adapter.componentType);
return internalValue != null ? adapter.toDenizen(internalValue) : null;
});
String componentName = adapter.componentType.key().value();
ItemComponentsPatch.registerHandledComponent(componentName);
if (!adapter.name.equals(componentName)) {
COMPONENTS_BY_PROPERTY.put(adapter.name, adapter.componentType);
}
}

static {

// <--[tag]
// @attribute <ItemTag.is_overridden[<component>]>
// @returns ElementTag(Boolean)
// @description
// Returns whether an item has a specific item component type overridden, see <@link language Item Components>.
// -->
ItemTag.tagProcessor.registerTag(ElementTag.class, ElementTag.class, "is_overridden", (attribute, object, param) -> {
DataComponentType componentType = getComponentType(param.asString());
if (componentType == null) {
attribute.echoError("Invalid type specified, must be a valid item component type or property name.");
return null;
}
return new ElementTag(object.getItemStack().isDataOverridden(componentType));
});
}

public final DataComponentType.Valued<TP> componentType;
public final Class<TD> denizenType;
public final String name;

public DataComponentAdapter(DataComponentType.Valued<TP> componentType, Class<TD> denizenType, String name) {
this.componentType = componentType;
this.denizenType = denizenType;
this.name = name;
}

public abstract TD toDenizen(TP value);

public abstract TP toPaper(TD value, Mechanism mechanism);

public static <T> void setIfValid(Consumer<T> setter, MapTag data, String key, String type, Predicate<ElementTag> checker, Function<ElementTag, T> converter, Mechanism mechanism) {
ElementTag value = data.getElement(key);
if (value == null) {
return;
}
T converted;
if (!checker.test(value) || (converted = converter.apply(value)) == null) {
mechanism.echoError("Invalid '" + key + "' specified: must be a " + type + '.');
return;
}
setter.accept(converted);
}

public class Property extends ItemProperty<TD> {

private static DataComponentAdapter<?, ?> currentlyRegisteringComponentAdapter;

public Property(ItemTag item) {
this.object = item;
}

@Override
public TD getPropertyValue() {
TP internalValue = getItemStack().getData(componentType);
return internalValue == null ? null : toDenizen(internalValue);
}

@Override
public TD getPropertyValueNoDefault() {
return getItemStack().isDataOverridden(componentType) ? getPropertyValue() : null;
}

@Override
public void setPropertyValue(TD value, Mechanism mechanism) {
if (value == null) {
getItemStack().resetData(componentType);
return;
}
TP converted = toPaper(value, mechanism);
if (converted != null) {
getItemStack().setData(componentType, converted);
}
}

@Override
public String getPropertyId() {
return name;
}

public static void register() {
autoRegisterNullable(currentlyRegisteringComponentAdapter.name, DataComponentAdapter.Property.class, currentlyRegisteringComponentAdapter.denizenType, false);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.denizenscript.denizen.paper.datacomponents;

import com.denizenscript.denizencore.objects.Mechanism;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.MapTag;
import io.papermc.paper.datacomponent.DataComponentTypes;
import io.papermc.paper.datacomponent.item.FoodProperties;

public class FoodAdapter extends DataComponentAdapter<FoodProperties, MapTag> {

// <--[property]
// @object ItemTag
// @name food
// @input MapTag
// @description
// Controls an item's food <@link language Item Components>.
// The map includes keys:
// - "nutrition", ElementTag(Number) representing the amount of food points restored by this item.
// - "saturation", ElementTag(Decimal) representing the amount of saturation points restored by this item.
// - "can_always_eat", ElementTag(Boolean) controlling whether the item can always be eaten, even if the player isn't hungry.
// -->

// <--[tag]
// @attribute <MaterialTag.food>
// @returns MapTag
// @description
// Gets the material's default food value, in the same format as <@link tag ItemTag.food>.
// -->

public FoodAdapter() {
super(DataComponentTypes.FOOD, MapTag.class, "food");
}

@Override
public MapTag toDenizen(FoodProperties value) {
MapTag foodData = new MapTag();
foodData.putObject("nutrition", new ElementTag(value.nutrition()));
foodData.putObject("saturation", new ElementTag(value.saturation()));
foodData.putObject("can_always_eat", new ElementTag(value.canAlwaysEat()));
return foodData;
}

@Override
public FoodProperties toPaper(MapTag value, Mechanism mechanism) {
FoodProperties.Builder builder = FoodProperties.food();
setIfValid(builder::nutrition, value, "nutrition", "number", ElementTag::isInt, ElementTag::asInt, mechanism);
setIfValid(builder::saturation, value, "saturation", "decimal number", ElementTag::isFloat, ElementTag::asFloat, mechanism);
setIfValid(builder::canAlwaysEat, value, "can_always_eat", "boolean", ElementTag::isBoolean, ElementTag::asBoolean, mechanism);
return builder.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.denizenscript.denizen.paper.properties;

import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizen.objects.properties.item.ItemProperty;
import com.denizenscript.denizen.paper.datacomponents.DataComponentAdapter;
import com.denizenscript.denizencore.objects.Mechanism;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.ListTag;
import io.papermc.paper.datacomponent.DataComponentType;

public class ItemRemoved extends ItemProperty<ListTag> {

// <--[property]
// @object ItemTag
// @name removed
// @input ListTag
// @description
// Controls the properties explicitly removed from an item.
// This can be used to remove item's default behavior, such as making consumable items non-consumable.
// See also <@link language Item Components>.
// -->

public static boolean describes(ItemTag item) {
return !item.getItemStack().isEmpty();
}

@Override
public ListTag getPropertyValue() {
return new ListTag(getMaterial().getDefaultDataTypes(),
componentType -> getItemStack().isDataOverridden(componentType) && !getItemStack().hasData(componentType),
componentType -> new ElementTag(componentType.key().asMinimalString(), true));
}

@Override
public boolean isDefaultValue(ListTag value) {
return value.isEmpty();
}

@Override
public void setPropertyValue(ListTag value, Mechanism mechanism) {
for (String input : value) {
DataComponentType componentType = DataComponentAdapter.getComponentType(input);
if (componentType == null) {
mechanism.echoError("Invalid type to remove '" + input + "' specified: must be a valid property or item component name.");
continue;
}
getItemStack().unsetData(componentType);
}
}

@Override
public String getPropertyId() {
return "removed";
}

public static void register() {
autoRegister("removed", ItemRemoved.class, ListTag.class, false);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.denizenscript.denizen.nms.v1_21.helpers;

import com.denizenscript.denizen.Denizen;
import com.denizenscript.denizen.nms.interfaces.ItemHelper;
import com.denizenscript.denizen.nms.util.PlayerProfile;
import com.denizenscript.denizen.nms.v1_21.Handler;
Expand Down Expand Up @@ -450,6 +451,12 @@ public MapTag getRawComponentsPatch(ItemStack item, boolean excludeHandled) {
}
RegistryOps<net.minecraft.nbt.Tag> registryOps = CraftRegistry.getMinecraftRegistry().createSerializationContext(NbtOps.INSTANCE);
CompoundTag nmsPatch = (CompoundTag) DataComponentPatch.CODEC.encodeStart(registryOps, patch).getOrThrow();
if (excludeHandled && Denizen.supportsPaper) {
nmsPatch.keySet().removeIf(s -> s.charAt(0) == '!');
if (nmsPatch.isEmpty()) {
return new MapTag();
}
}
MapTag rawComponents = (MapTag) ItemRawNBT.nbtTagToObject(NBTAdapter.toAPI(nmsPatch));
rawComponents.putObject(ItemComponentsPatch.DATA_VERSION_KEY, new ElementTag(CraftMagicNumbers.INSTANCE.getDataVersion()));
return rawComponents;
Expand Down