ItemStack .java

net.minecraft.world.item.ItemStack (class): members: OPTIONAL_UNTRUSTED_STREAM_CODEC, canPlaceOnBlockInAdventureMode, OPTIONAL_LIST_STREAM_CODEC, shrink.

net.minecraft.world.itemclass1,150 linescommon42.2 KB

Implements

API Surface (109)

ItemStack decode(final RegistryFriendlyByteBuf input)
void encode(final RegistryFriendlyByteBuf output, final ItemStack itemStack)
DataResult<ItemStack> validateStrict(final ItemStack itemStack)
ItemStack decode(final RegistryFriendlyByteBuf input)
void encode(final RegistryFriendlyByteBuf output, final ItemStack itemStack)
StreamCodec<RegistryFriendlyByteBuf, ItemStack> validatedStreamCodec(final StreamCodec<RegistryFriendlyByteBuf, ItemStack> codec)
ItemStack decode(final RegistryFriendlyByteBuf input)
void encode(final RegistryFriendlyByteBuf output, final ItemStack value)
Optional<TooltipComponent> getTooltipImage()
DataComponentMap getComponents()
DataComponentMap getPrototype()
DataComponentPatch getComponentsPatch()
DataComponentMap immutableComponents()
boolean hasNonDefault(final DataComponentType<?> type)
boolean isEmpty()
boolean isItemEnabled(final FeatureFlagSet enabledFeatures)
ItemStack split(final int amount)
ItemStack copyAndClear()
Item getItem()
Holder<Item> typeHolder()
boolean is(final Predicate<Holder<Item>> item)
InteractionResult useOn(final UseOnContext context)
float getDestroySpeed(final BlockState state)
InteractionResult use(final Level level, final Player player, final InteractionHand hand)
ItemStack finishUsingItem(final Level level, final LivingEntity livingEntity)
boolean isStackable()
boolean isDamageableItem()
boolean isDamaged()
int getDamageValue()
void setDamageValue(final int value)
int getMaxDamage()
boolean isBroken()
boolean nextDamageWillBreak()
void hurtAndBreak(final int amount, final ServerLevel level, final @Nullable ServerPlayer player, final Consumer<ItemStack> onBreak)
void hurtWithoutBreaking(final int amount, final Player player)
void hurtAndBreak(final int amount, final LivingEntity owner, final InteractionHand hand)
void hurtAndBreak(final int amount, final LivingEntity owner, final EquipmentSlot slot)
ItemStack hurtAndConvertOnBreak(final int amount, final ItemLike newItem, final LivingEntity owner, final EquipmentSlot slot)
boolean isBarVisible()
int getBarWidth()
int getBarColor()
boolean overrideStackedOnOther(final Slot slot, final ClickAction clickAction, final Player player)
boolean overrideOtherStackedOnMe(final ItemStack other, final Slot slot, final ClickAction clickAction, final Player player, final SlotAccess carriedItem)
boolean hurtEnemy(final LivingEntity mob, final LivingEntity attacker)
void postHurtEnemy(final LivingEntity mob, final LivingEntity attacker)
void mineBlock(final Level level, final BlockState state, final BlockPos pos, final Player owner)
boolean isCorrectToolForDrops(final BlockState state)
InteractionResult interactLivingEntity(final Player player, final LivingEntity target, final InteractionHand hand)
ItemStack copy()
ItemStack copyWithCount(final int count)
ItemStack transmuteCopy(final ItemLike newItem)
ItemStack transmuteCopy(final ItemLike newItem, final int newCount)
boolean matches(final ItemStack a, final ItemStack b)
boolean listMatches(final List<ItemStack> left, final List<ItemStack> right)
boolean isSameItem(final ItemStack a, final ItemStack b)
boolean isSameItemSameComponents(final ItemStack a, final ItemStack b)
boolean matchesIgnoringComponents(final ItemStack a, final ItemStack b, final Predicate<DataComponentType<?>> ignoredPredicate)
MapCodec<ItemStack> lenientOptionalFieldOf(final String name)
int hashItemAndComponents(final @Nullable ItemStack item)
int hashStackList(final List<ItemStack> items)
String toString()
void inventoryTick(final Level level, final Entity owner, final @Nullable EquipmentSlot slot)
void onCraftedBy(final Player player, final int craftCount)
void onCraftedBySystem(final Level level)
int getUseDuration(final LivingEntity user)
ItemUseAnimation getUseAnimation()
void releaseUsing(final Level level, final LivingEntity entity, final int remainingTime)
void causeUseVibration(final Entity causer, final Holder.Reference<GameEvent> event)
boolean useOnRelease()
<T> void copyFrom(final DataComponentType<T> type, final DataComponentGetter source)
void applyComponentsAndValidate(final DataComponentPatch patch)
void applyComponents(final DataComponentPatch patch)
void applyComponents(final DataComponentMap components)
Component getHoverName()
Component getItemName()
Component getStyledHoverName()
<T> void addToTooltip(final DataComponentType<T> type, final TooltipProvider.Getter<T> tooltipGetter, final Item.TooltipContext context, final TooltipDisplay display, final Consumer<Component> consumer, final TooltipFlag flag)
<T extends TooltipProvider> void addToTooltip(final DataComponentType<T> type, final Item.TooltipContext context, final TooltipDisplay display, final Consumer<Component> consumer, final TooltipFlag flag)
List<Component> getTooltipLines(final Item.TooltipContext context, final @Nullable Player player, final TooltipFlag tooltipFlag)
void addDetailsToTooltip(final Item.TooltipContext context, final TooltipDisplay display, final @Nullable Player player, final TooltipFlag tooltipFlag, final Consumer<Component> builder)
boolean hasFoil()
Rarity getRarity()
boolean isEnchantable()
void enchant(final Holder<Enchantment> enchantment, final int level)
boolean isEnchanted()
ItemEnchantments getEnchantments()
void forEachModifier(final EquipmentSlotGroup slot, final TriConsumer<Holder<Attribute>, AttributeModifier, ItemAttributeModifiers.Display> consumer)
void forEachModifier(final EquipmentSlot slot, final BiConsumer<Holder<Attribute>, AttributeModifier> consumer)
Component getDisplayName()
SwingAnimation getAttackAnimation()
SwingAnimation getInteractAnimation()
boolean canPlaceOnBlockInAdventureMode(final BlockInWorld blockInWorld)
boolean canBreakBlockInAdventureMode(final BlockInWorld blockInWorld)
int getPopTime()
void setPopTime(final int popTime)
int getCount()
int count()
void setCount(final int count)
void limitSize(final int maxStackSize)
void grow(final int amount)
void shrink(final int amount)
void consume(final int amount, final @Nullable LivingEntity owner)
ItemStack consumeAndReturn(final int amount, final @Nullable LivingEntity owner)
void onUseTick(final Level level, final LivingEntity livingEntity, final int ticksRemaining)
void onDestroyed(final ItemEntity itemEntity)
boolean canBeHurtBy(final DamageSource source)
boolean isValidRepairItem(final ItemStack repairItem)
boolean canDestroyBlock(final BlockState state, final Level level, final BlockPos pos, final Player player)
DamageSource getDamageSource(final LivingEntity attacker)

Fields & Constants (24)

OP_NBT_WARNING
UNBREAKABLE_TOOLTIP
INTANGIBLE_TOOLTIP
MAP_CODEC
CODEC
OPTIONAL_CODEC
OPTIONAL_STREAM_CODEC
OPTIONAL_UNTRUSTED_STREAM_CODEC
STREAM_CODEC
OPTIONAL_LIST_STREAM_CODEC
LOGGER
EMPTY
DISABLED_ITEM_TOOLTIP
count
popTime
item
components
player
type
tooltipGetter
context
display
consumer
tooltipFlag

String literals (17)

"item.op_warning.line1"
"item.op_warning.line2"
"item.op_warning.line3"
"item.unbreakable"
"item.intangible"
"count"
"components"
"Empty ItemStack not allowed"
"item.disabled"
"Item stack with stack size of "
" was larger than maximum: "
"Item cannot be both damageable and stackable"
"Item stack with count of "
"SpawnData"
"item.durability"
"item.components"
"item.modifiers."

Code Graph: Dependencies (80)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

ItemStack.java1150 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.item;
2
3
import com.google.common.collect.Lists;
4
import com.mojang.logging.LogUtils;
5
import com.mojang.serialization.Codec;
6
import com.mojang.serialization.DataResult;
7
import com.mojang.serialization.MapCodec;
8
import com.mojang.serialization.DataResult.Error;
9
import com.mojang.serialization.codecs.RecordCodecBuilder;
10
import io.netty.handler.codec.DecoderException;
11
import io.netty.handler.codec.EncoderException;
12
import java.util.List;
13
import java.util.Objects;
14
import java.util.Optional;
15
import java.util.function.BiConsumer;
16
import java.util.function.BiFunction;
17
import java.util.function.Consumer;
18
import java.util.function.Predicate;
19
import java.util.function.UnaryOperator;
20
import net.fabricmc.fabric.api.item.v1.FabricItemStack;
21
import net.minecraft.ChatFormatting;
22
import net.minecraft.advancements.triggers.CriteriaTriggers;
23
import net.minecraft.core.BlockPos;
24
import net.minecraft.core.Holder;
25
import net.minecraft.core.NonNullList;
26
import net.minecraft.core.component.DataComponentGetter;
27
import net.minecraft.core.component.DataComponentHolder;
28
import net.minecraft.core.component.DataComponentMap;
29
import net.minecraft.core.component.DataComponentPatch;
30
import net.minecraft.core.component.DataComponentType;
31
import net.minecraft.core.component.DataComponents;
32
import net.minecraft.core.component.PatchedDataComponentMap;
33
import net.minecraft.core.component.TypedDataComponent;
34
import net.minecraft.core.registries.BuiltInRegistries;
35
import net.minecraft.network.RegistryFriendlyByteBuf;
36
import net.minecraft.network.chat.CommonComponents;
37
import net.minecraft.network.chat.Component;
38
import net.minecraft.network.chat.ComponentUtils;
39
import net.minecraft.network.chat.HoverEvent;
40
import net.minecraft.network.chat.MutableComponent;
41
import net.minecraft.network.codec.ByteBufCodecs;
42
import net.minecraft.network.codec.StreamCodec;
43
import net.minecraft.resources.RegistryOps;
44
import net.minecraft.server.level.ServerLevel;
45
import net.minecraft.server.level.ServerPlayer;
46
import net.minecraft.stats.Stats;
47
import net.minecraft.util.ExtraCodecs;
48
import net.minecraft.util.Mth;
49
import net.minecraft.util.NullOps;
50
import net.minecraft.util.StringUtil;
51
import net.minecraft.util.Unit;
52
import net.minecraft.world.InteractionHand;
53
import net.minecraft.world.InteractionResult;
54
import net.minecraft.world.damagesource.DamageSource;
55
import net.minecraft.world.damagesource.DamageType;
56
import net.minecraft.world.entity.Entity;
57
import net.minecraft.world.entity.EquipmentSlot;
58
import net.minecraft.world.entity.EquipmentSlotGroup;
59
import net.minecraft.world.entity.LivingEntity;
60
import net.minecraft.world.entity.SlotAccess;
61
import net.minecraft.world.entity.ai.attributes.Attribute;
62
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
63
import net.minecraft.world.entity.item.ItemEntity;
64
import net.minecraft.world.entity.player.Player;
65
import net.minecraft.world.flag.FeatureFlagSet;
66
import net.minecraft.world.inventory.ClickAction;
67
import net.minecraft.world.inventory.Slot;
68
import net.minecraft.world.inventory.tooltip.TooltipComponent;
69
import net.minecraft.world.item.component.BundleContents;
70
import net.minecraft.world.item.component.ChargedProjectiles;
71
import net.minecraft.world.item.component.Consumable;
72
import net.minecraft.world.item.component.DamageResistant;
73
import net.minecraft.world.item.component.ItemAttributeModifiers;
74
import net.minecraft.world.item.component.ItemContainerContents;
75
import net.minecraft.world.item.component.KineticWeapon;
76
import net.minecraft.world.item.component.SwingAnimation;
77
import net.minecraft.world.item.component.TooltipDisplay;
78
import net.minecraft.world.item.component.TooltipProvider;
79
import net.minecraft.world.item.component.TypedEntityData;
80
import net.minecraft.world.item.component.UseCooldown;
81
import net.minecraft.world.item.component.UseEffects;
82
import net.minecraft.world.item.component.UseRemainder;
83
import net.minecraft.world.item.component.Weapon;
84
import net.minecraft.world.item.component.WrittenBookContent;
85
import net.minecraft.world.item.context.UseOnContext;
86
import net.minecraft.world.item.enchantment.Enchantment;
87
import net.minecraft.world.item.enchantment.EnchantmentHelper;
88
import net.minecraft.world.item.enchantment.ItemEnchantments;
89
import net.minecraft.world.item.enchantment.Repairable;
90
import net.minecraft.world.item.equipment.Equippable;
91
import net.minecraft.world.level.ItemLike;
92
import net.minecraft.world.level.Level;
93
import net.minecraft.world.level.Spawner;
94
import net.minecraft.world.level.block.entity.BlockEntityType;
95
import net.minecraft.world.level.block.entity.SignText;
96
import net.minecraft.world.level.block.state.BlockState;
97
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
98
import net.minecraft.world.level.gameevent.GameEvent;
99
import org.apache.commons.lang3.function.TriConsumer;
100
import org.apache.commons.lang3.mutable.MutableBoolean;
101
import org.jspecify.annotations.Nullable;
102
import org.slf4j.Logger;
103
104
public final class ItemStack implements DataComponentHolder, ItemInstance, FabricItemStack {
105
	private static final List<Component> OP_NBT_WARNING = List.of(
106
		Component.translatable("item.op_warning.line1").withStyle(ChatFormatting.RED, ChatFormatting.BOLD),
107
		Component.translatable("item.op_warning.line2").withStyle(ChatFormatting.RED),
108
		Component.translatable("item.op_warning.line3").withStyle(ChatFormatting.RED)
109
	);
110
	private static final Component UNBREAKABLE_TOOLTIP = Component.translatable("item.unbreakable").withStyle(ChatFormatting.BLUE);
111
	private static final Component INTANGIBLE_TOOLTIP = Component.translatable("item.intangible").withStyle(ChatFormatting.GRAY);
112
	public static final MapCodec<ItemStack> MAP_CODEC = MapCodec.recursive(
113
		"ItemStack",
114
		subCodec -> RecordCodecBuilder.mapCodec(
115
			i -> i.group(
116
					Item.CODEC_WITH_BOUND_COMPONENTS.fieldOf("id").forGetter(ItemStack::typeHolder),
117
					ExtraCodecs.optionalAlwaysPresentFieldOf(ExtraCodecs.intRange(1, 99), "count", 1).forGetter(ItemStack::getCount),
118
					DataComponentPatch.CODEC.optionalFieldOf("components", DataComponentPatch.EMPTY).forGetter(s -> s.components.asPatch())
119
				)
120
				.apply(i, ItemStack::new)
121
		)
122
	);
123
	public static final Codec<ItemStack> CODEC = Codec.lazyInitialized(MAP_CODEC::codec);
124
	public static final Codec<ItemStack> OPTIONAL_CODEC = ExtraCodecs.optionalEmptyMap(CODEC)
125
		.xmap(itemStack -> itemStack.orElse(ItemStack.EMPTY), itemStack -> itemStack.isEmpty() ? Optional.empty() : Optional.of(itemStack));
126
	public static final StreamCodec<RegistryFriendlyByteBuf, ItemStack> OPTIONAL_STREAM_CODEC = createOptionalStreamCodec(DataComponentPatch.STREAM_CODEC);
127
	public static final StreamCodec<RegistryFriendlyByteBuf, ItemStack> OPTIONAL_UNTRUSTED_STREAM_CODEC = createOptionalStreamCodec(
128
		DataComponentPatch.DELIMITED_STREAM_CODEC
129
	);
130
	public static final StreamCodec<RegistryFriendlyByteBuf, ItemStack> STREAM_CODEC = new StreamCodec<RegistryFriendlyByteBuf, ItemStack>() {
131
		public ItemStack decode(final RegistryFriendlyByteBuf input) {
132
			ItemStack itemStack = ItemStack.OPTIONAL_STREAM_CODEC.decode(input);
133
			if (itemStack.isEmpty()) {
134
				throw new DecoderException("Empty ItemStack not allowed");
135
			} else {
136
				return itemStack;
137
			}
138
		}
139
140
		public void encode(final RegistryFriendlyByteBuf output, final ItemStack itemStack) {
141
			if (itemStack.isEmpty()) {
142
				throw new EncoderException("Empty ItemStack not allowed");
143
			}
144
145
			ItemStack.OPTIONAL_STREAM_CODEC.encode(output, itemStack);
146
		}
147
	};
148
	public static final StreamCodec<RegistryFriendlyByteBuf, List<ItemStack>> OPTIONAL_LIST_STREAM_CODEC = OPTIONAL_STREAM_CODEC.apply(
149
		ByteBufCodecs.collection(NonNullList::createWithCapacity)
150
	);
151
	private static final Logger LOGGER = LogUtils.getLogger();
152
	public static final ItemStack EMPTY = new ItemStack((Void)null);
153
	private static final Component DISABLED_ITEM_TOOLTIP = Component.translatable("item.disabled").withStyle(ChatFormatting.RED);
154
	private int count;
155
	private int popTime;
156
	@Deprecated
157
	private final @Nullable Holder<Item> item;
158
	private final PatchedDataComponentMap components;
159
160
	public static DataResult<ItemStack> validateStrict(final ItemStack itemStack) {
161
		DataResult<?> result = validateComponents(itemStack.getComponents());
162
		if (result.isError()) {
163
			return result.map(unit -> itemStack);
164
		} else {
165
			return itemStack.getCount() > itemStack.getMaxStackSize()
166
				? DataResult.error(() -> "Item stack with stack size of " + itemStack.getCount() + " was larger than maximum: " + itemStack.getMaxStackSize())
167
				: DataResult.success(itemStack);
168
		}
169
	}
170
171
	private static StreamCodec<RegistryFriendlyByteBuf, ItemStack> createOptionalStreamCodec(
172
		final StreamCodec<RegistryFriendlyByteBuf, DataComponentPatch> patchCodec
173
	) {
174
		return new StreamCodec<RegistryFriendlyByteBuf, ItemStack>() {
175
			public ItemStack decode(final RegistryFriendlyByteBuf input) {
176
				int count = input.readVarInt();
177
				if (count <= 0) {
178
					return ItemStack.EMPTY;
179
				}
180
181
				Holder<Item> item = Item.STREAM_CODEC.decode(input);
182
				DataComponentPatch patch = patchCodec.decode(input);
183
				return new ItemStack(item, count, patch);
184
			}
185
186
			public void encode(final RegistryFriendlyByteBuf output, final ItemStack itemStack) {
187
				if (itemStack.isEmpty()) {
188
					output.writeVarInt(0);
189
				} else {
190
					output.writeVarInt(itemStack.getCount());
191
					Item.STREAM_CODEC.encode(output, itemStack.typeHolder());
192
					patchCodec.encode(output, itemStack.components.asPatch());
193
				}
194
			}
195
		};
196
	}
197
198
	public static StreamCodec<RegistryFriendlyByteBuf, ItemStack> validatedStreamCodec(final StreamCodec<RegistryFriendlyByteBuf, ItemStack> codec) {
199
		return new StreamCodec<RegistryFriendlyByteBuf, ItemStack>() {
200
			public ItemStack decode(final RegistryFriendlyByteBuf input) {
201
				ItemStack itemStack = codec.decode(input);
202
				if (!itemStack.isEmpty()) {
203
					RegistryOps<Unit> ops = input.registryAccess().createSerializationContext(NullOps.INSTANCE);
204
					ItemStack.CODEC.encodeStart(ops, itemStack).getOrThrow(DecoderException::new);
205
				}
206
207
				return itemStack;
208
			}
209
210
			public void encode(final RegistryFriendlyByteBuf output, final ItemStack value) {
211
				codec.encode(output, value);
212
			}
213
		};
214
	}
215
216
	public Optional<TooltipComponent> getTooltipImage() {
217
		return this.getItem().getTooltipImage(this);
218
	}
219
220
	@Override
221
	public DataComponentMap getComponents() {
222
		return !this.isEmpty() ? this.components : DataComponentMap.EMPTY;
223
	}
224
225
	public DataComponentMap getPrototype() {
226
		return !this.isEmpty() ? this.typeHolder().components() : DataComponentMap.EMPTY;
227
	}
228
229
	public DataComponentPatch getComponentsPatch() {
230
		return !this.isEmpty() ? this.components.asPatch() : DataComponentPatch.EMPTY;
231
	}
232
233
	public DataComponentMap immutableComponents() {
234
		return !this.isEmpty() ? this.components.toImmutableMap() : DataComponentMap.EMPTY;
235
	}
236
237
	public boolean hasNonDefault(final DataComponentType<?> type) {
238
		return !this.isEmpty() && this.components.hasNonDefault(type);
239
	}
240
241
	public ItemStack(final ItemLike item, final int count) {
242
		this(item.asItem().builtInRegistryHolder(), count);
243
	}
244
245
	public ItemStack(final ItemLike item) {
246
		this(item.asItem().builtInRegistryHolder(), 1);
247
	}
248
249
	public ItemStack(final Holder<Item> item, final int count) {
250
		this(item, count, new PatchedDataComponentMap(item.components()));
251
	}
252
253
	public ItemStack(final Holder<Item> item) {
254
		this(item, 1);
255
	}
256
257
	public ItemStack(final Holder<Item> item, final int count, final DataComponentPatch components) {
258
		this(item, count, PatchedDataComponentMap.fromPatch(item.components(), components));
259
	}
260
261
	private ItemStack(final Holder<Item> item, final int count, final PatchedDataComponentMap components) {
262
		this.item = item;
263
		this.count = count;
264
		this.components = components;
265
	}
266
267
	private ItemStack(final @Nullable Void nullMarker) {
268
		this.item = null;
269
		this.components = new PatchedDataComponentMap(DataComponentMap.EMPTY);
270
	}
271
272
	private static DataResult<?> validateComponents(final DataComponentMap components) {
273
		if (components.has(DataComponents.MAX_DAMAGE) && components.getOrDefault(DataComponents.MAX_STACK_SIZE, 1) > 1) {
274
			return DataResult.error(() -> "Item cannot be both damageable and stackable");
275
		}
276
277
		ItemContainerContents container = components.get(DataComponents.CONTAINER);
278
		if (container != null) {
279
			DataResult<?> validationContents = validateContainedItemSizes(container.nonEmptyItems());
280
			if (validationContents.isError()) {
281
				return validationContents;
282
			}
283
		}
284
285
		BundleContents bundle = components.get(DataComponents.BUNDLE_CONTENTS);
286
		if (bundle != null) {
287
			DataResult<?> validationResult = validateContainedItemSizes(bundle.items());
288
			if (validationResult.isError()) {
289
				return validationResult;
290
			}
291
292
			validationResult = bundle.weight();
293
			if (validationResult.isError()) {
294
				return validationResult;
295
			}
296
		}
297
298
		ChargedProjectiles chargedProjectiles = components.get(DataComponents.CHARGED_PROJECTILES);
299
		if (chargedProjectiles != null) {
300
			DataResult<?> validationResult = validateContainedItemSizes(chargedProjectiles.items());
301
			if (validationResult.isError()) {
302
				return validationResult;
303
			}
304
		}
305
306
		return DataResult.success(Unit.INSTANCE);
307
	}
308
309
	private static DataResult<?> validateContainedItemSizes(final Iterable<? extends ItemInstance> items) {
310
		for (ItemInstance item : items) {
311
			int itemCount = item.count();
312
			int maxStackSize = item.getMaxStackSize();
313
			if (itemCount > maxStackSize) {
314
				return DataResult.error(() -> "Item stack with count of " + itemCount + " was larger than maximum: " + maxStackSize);
315
			}
316
		}
317
318
		return DataResult.success(Unit.INSTANCE);
319
	}
320
321
	public boolean isEmpty() {
322
		return this == EMPTY || this.item.value() == Items.AIR || this.count <= 0;
323
	}
324
325
	public boolean isItemEnabled(final FeatureFlagSet enabledFeatures) {
326
		return this.isEmpty() || this.getItem().isEnabled(enabledFeatures);
327
	}
328
329
	public ItemStack split(final int amount) {
330
		int realAmount = Math.min(amount, this.getCount());
331
		ItemStack result = this.copyWithCount(realAmount);
332
		this.shrink(realAmount);
333
		return result;
334
	}
335
336
	public ItemStack copyAndClear() {
337
		if (this.isEmpty()) {
338
			return EMPTY;
339
		}
340
341
		ItemStack result = this.copy();
342
		this.setCount(0);
343
		return result;
344
	}
345
346
	public Item getItem() {
347
		return this.typeHolder().value();
348
	}
349
350
	@Override
351
	public Holder<Item> typeHolder() {
352
		return this.isEmpty() ? Items.AIR.builtInRegistryHolder() : this.item;
353
	}
354
355
	public boolean is(final Predicate<Holder<Item>> item) {
356
		return item.test(this.typeHolder());
357
	}
358
359
	public InteractionResult useOn(final UseOnContext context) {
360
		Player player = context.getPlayer();
361
		BlockPos pos = context.getClickedPos();
362
		if (player != null && !player.getAbilities().mayBuild && !this.canPlaceOnBlockInAdventureMode(new BlockInWorld(context.getLevel(), pos, false))) {
363
			return InteractionResult.PASS;
364
		} else {
365
			ItemStack stackBeforeUse = this.copy();
366
			Item usedItem = this.getItem();
367
			InteractionResult result = usedItem.useOn(context);
368
			if (player != null && result instanceof InteractionResult.Success success && success.wasItemInteraction()) {
369
				player.awardStat(Stats.ITEM_USED.get(usedItem));
370
				ItemStack transformTo = success.heldItemTransformedTo() == null ? this : success.heldItemTransformedTo();
371
				ItemStack resultItemStack = transformTo.applyAfterUseComponentSideEffects(player, stackBeforeUse);
372
				return success.heldItemTransformedTo(resultItemStack);
373
			} else {
374
				return result;
375
			}
376
		}
377
	}
378
379
	public float getDestroySpeed(final BlockState state) {
380
		return this.getItem().getDestroySpeed(this, state);
381
	}
382
383
	public InteractionResult use(final Level level, final Player player, final InteractionHand hand) {
384
		ItemStack stackBeforeUse = this.copy();
385
		boolean isInstantlyUsed = this.getUseDuration(player) <= 0;
386
		InteractionResult result = this.getItem().use(level, player, hand);
387
		if (isInstantlyUsed && result instanceof InteractionResult.Success success) {
388
			ItemStack transformTo = success.heldItemTransformedTo() == null ? this : success.heldItemTransformedTo();
389
			ItemStack resultItemStack = transformTo.applyAfterUseComponentSideEffects(player, stackBeforeUse);
390
			return success.heldItemTransformedTo(resultItemStack);
391
		} else {
392
			return result;
393
		}
394
	}
395
396
	public ItemStack finishUsingItem(final Level level, final LivingEntity livingEntity) {
397
		ItemStack stackBeforeUse = this.copy();
398
		ItemStack result = this.getItem().finishUsingItem(this, level, livingEntity);
399
		return result.applyAfterUseComponentSideEffects(livingEntity, stackBeforeUse);
400
	}
401
402
	private ItemStack applyAfterUseComponentSideEffects(final LivingEntity user, final ItemStack stackBeforeUsing) {
403
		UseRemainder useRemainder = stackBeforeUsing.get(DataComponents.USE_REMAINDER);
404
		UseCooldown useCooldown = stackBeforeUsing.get(DataComponents.USE_COOLDOWN);
405
		int stackCountBeforeUsing = stackBeforeUsing.getCount();
406
		ItemStack result = this;
407
		if (useRemainder != null) {
408
			result = useRemainder.convertIntoRemainder(result, stackCountBeforeUsing, user.hasInfiniteMaterials(), user::handleExtraItemsCreatedOnUse);
409
		}
410
411
		if (useCooldown != null) {
412
			useCooldown.apply(stackBeforeUsing, user);
413
		}
414
415
		return result;
416
	}
417
418
	public boolean isStackable() {
419
		return this.getMaxStackSize() > 1 && (!this.isDamageableItem() || !this.isDamaged());
420
	}
421
422
	public boolean isDamageableItem() {
423
		return this.has(DataComponents.MAX_DAMAGE) && !this.has(DataComponents.UNBREAKABLE) && this.has(DataComponents.DAMAGE);
424
	}
425
426
	public boolean isDamaged() {
427
		return this.isDamageableItem() && this.getDamageValue() > 0;
428
	}
429
430
	public int getDamageValue() {
431
		return Mth.clamp(this.getOrDefault(DataComponents.DAMAGE, 0), 0, this.getMaxDamage());
432
	}
433
434
	public void setDamageValue(final int value) {
435
		this.set(DataComponents.DAMAGE, Mth.clamp(value, 0, this.getMaxDamage()));
436
	}
437
438
	public int getMaxDamage() {
439
		return this.getOrDefault(DataComponents.MAX_DAMAGE, 0);
440
	}
441
442
	public boolean isBroken() {
443
		return this.isDamageableItem() && this.getDamageValue() >= this.getMaxDamage();
444
	}
445
446
	public boolean nextDamageWillBreak() {
447
		return this.isDamageableItem() && this.getDamageValue() >= this.getMaxDamage() - 1;
448
	}
449
450
	public void hurtAndBreak(final int amount, final ServerLevel level, final @Nullable ServerPlayer player, final Consumer<ItemStack> onBreak) {
451
		int newAmount = this.processDurabilityChange(amount, level, player);
452
		if (newAmount != 0) {
453
			this.applyDamage(this.getDamageValue() + newAmount, player, onBreak);
454
		}
455
	}
456
457
	private int processDurabilityChange(final int amount, final ServerLevel level, final @Nullable ServerPlayer player) {
458
		if (!this.isDamageableItem()) {
459
			return 0;
460
		} else if (player != null && player.hasInfiniteMaterials()) {
461
			return 0;
462
		} else {
463
			return amount > 0 ? EnchantmentHelper.processDurabilityChange(level, this, amount) : amount;
464
		}
465
	}
466
467
	private void applyDamage(final int newDamage, final @Nullable ServerPlayer player, final Consumer<ItemStack> onBreak) {
468
		if (player != null) {
469
			CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger(player, this, newDamage);
470
		}
471
472
		this.setDamageValue(newDamage);
473
		if (this.isBroken()) {
474
			ItemStack broken = this.copy();
475
			this.shrink(1);
476
			onBreak.accept(broken);
477
		}
478
	}
479
480
	public void hurtWithoutBreaking(final int amount, final Player player) {
481
		if (player instanceof ServerPlayer serverPlayer) {
482
			int newAmount = this.processDurabilityChange(amount, serverPlayer.level(), serverPlayer);
483
			if (newAmount == 0) {
484
				return;
485
			}
486
487
			int newDamage = Math.min(this.getDamageValue() + newAmount, this.getMaxDamage() - 1);
488
			this.applyDamage(newDamage, serverPlayer, i -> {});
489
		}
490
	}
491
492
	public void hurtAndBreak(final int amount, final LivingEntity owner, final InteractionHand hand) {
493
		this.hurtAndBreak(amount, owner, hand.asEquipmentSlot());
494
	}
495
496
	public void hurtAndBreak(final int amount, final LivingEntity owner, final EquipmentSlot slot) {
497
		if (owner.level() instanceof ServerLevel serverLevel) {
498
			this.hurtAndBreak(amount, serverLevel, owner instanceof ServerPlayer player ? player : null, brokenItem -> owner.onEquippedItemBroken(brokenItem, slot));
499
		}
500
	}
501
502
	public ItemStack hurtAndConvertOnBreak(final int amount, final ItemLike newItem, final LivingEntity owner, final EquipmentSlot slot) {
503
		this.hurtAndBreak(amount, owner, slot);
504
		if (this.isEmpty()) {
505
			ItemStack replacement = this.transmuteCopyIgnoreEmpty(newItem, 1);
506
			if (replacement.isDamageableItem()) {
507
				replacement.setDamageValue(0);
508
			}
509
510
			return replacement;
511
		} else {
512
			return this;
513
		}
514
	}
515
516
	public boolean isBarVisible() {
517
		return this.getItem().isBarVisible(this);
518
	}
519
520
	public int getBarWidth() {
521
		return this.getItem().getBarWidth(this);
522
	}
523
524
	public int getBarColor() {
525
		return this.getItem().getBarColor(this);
526
	}
527
528
	public boolean overrideStackedOnOther(final Slot slot, final ClickAction clickAction, final Player player) {
529
		return this.getItem().overrideStackedOnOther(this, slot, clickAction, player);
530
	}
531
532
	public boolean overrideOtherStackedOnMe(
533
		final ItemStack other, final Slot slot, final ClickAction clickAction, final Player player, final SlotAccess carriedItem
534
	) {
535
		return this.getItem().overrideOtherStackedOnMe(this, other, slot, clickAction, player, carriedItem);
536
	}
537
538
	public boolean hurtEnemy(final LivingEntity mob, final LivingEntity attacker) {
539
		Item usedItem = this.getItem();
540
		usedItem.hurtEnemy(this, mob, attacker);
541
		if (this.has(DataComponents.WEAPON)) {
542
			if (attacker instanceof Player player) {
543
				player.awardStat(Stats.ITEM_USED.get(usedItem));
544
			}
545
546
			return true;
547
		} else {
548
			return false;
549
		}
550
	}
551
552
	public void postHurtEnemy(final LivingEntity mob, final LivingEntity attacker) {
553
		this.getItem().postHurtEnemy(this, mob, attacker);
554
		Weapon weapon = this.get(DataComponents.WEAPON);
555
		if (weapon != null) {
556
			this.hurtAndBreak(weapon.itemDamagePerAttack(), attacker, EquipmentSlot.MAINHAND);
557
		}
558
	}
559
560
	public void mineBlock(final Level level, final BlockState state, final BlockPos pos, final Player owner) {
561
		Item usedItem = this.getItem();
562
		if (usedItem.mineBlock(this, level, state, pos, owner)) {
563
			owner.awardStat(Stats.ITEM_USED.get(usedItem));
564
		}
565
	}
566
567
	public boolean isCorrectToolForDrops(final BlockState state) {
568
		return this.getItem().isCorrectToolForDrops(this, state);
569
	}
570
571
	public InteractionResult interactLivingEntity(final Player player, final LivingEntity target, final InteractionHand hand) {
572
		Equippable equippable = this.get(DataComponents.EQUIPPABLE);
573
		if (equippable != null && equippable.equipOnInteract()) {
574
			InteractionResult result = equippable.equipOnTarget(player, target, this);
575
			if (result != InteractionResult.PASS) {
576
				return result;
577
			}
578
		}
579
580
		return this.getItem().interactLivingEntity(this, player, target, hand);
581
	}
582
583
	public ItemStack copy() {
584
		if (this.isEmpty()) {
585
			return EMPTY;
586
		}
587
588
		ItemStack copy = new ItemStack(this.typeHolder(), this.count, this.components.copy());
589
		copy.setPopTime(this.getPopTime());
590
		return copy;
591
	}
592
593
	public ItemStack copyWithCount(final int count) {
594
		if (this.isEmpty()) {
595
			return EMPTY;
596
		}
597
598
		ItemStack copy = this.copy();
599
		copy.setCount(count);
600
		return copy;
601
	}
602
603
	public ItemStack transmuteCopy(final ItemLike newItem) {
604
		return this.transmuteCopy(newItem, this.getCount());
605
	}
606
607
	public ItemStack transmuteCopy(final ItemLike newItem, final int newCount) {
608
		return this.isEmpty() ? EMPTY : this.transmuteCopyIgnoreEmpty(newItem, newCount);
609
	}
610
611
	private ItemStack transmuteCopyIgnoreEmpty(final ItemLike newItem, final int newCount) {
612
		return new ItemStack(newItem.asItem().builtInRegistryHolder(), newCount, this.components.asPatch());
613
	}
614
615
	public static boolean matches(final ItemStack a, final ItemStack b) {
616
		if (a == b) {
617
			return true;
618
		} else {
619
			return a.getCount() != b.getCount() ? false : isSameItemSameComponents(a, b);
620
		}
621
	}
622
623
	@Deprecated
624
	public static boolean listMatches(final List<ItemStack> left, final List<ItemStack> right) {
625
		if (left.size() != right.size()) {
626
			return false;
627
		}
628
629
		for (int i = 0; i < left.size(); i++) {
630
			if (!matches(left.get(i), right.get(i))) {
631
				return false;
632
			}
633
		}
634
635
		return true;
636
	}
637
638
	public static boolean isSameItem(final ItemStack a, final ItemStack b) {
639
		return a.is(b.getItem());
640
	}
641
642
	public static boolean isSameItemSameComponents(final ItemStack a, final ItemStack b) {
643
		if (!a.is(b.getItem())) {
644
			return false;
645
		} else {
646
			return a.isEmpty() && b.isEmpty() ? true : Objects.equals(a.components, b.components);
647
		}
648
	}
649
650
	public static boolean matchesIgnoringComponents(final ItemStack a, final ItemStack b, final Predicate<DataComponentType<?>> ignoredPredicate) {
651
		if (a == b) {
652
			return true;
653
		}
654
655
		if (a.getCount() != b.getCount()) {
656
			return false;
657
		}
658
659
		if (!a.is(b.getItem())) {
660
			return false;
661
		}
662
663
		if (a.isEmpty() && b.isEmpty()) {
664
			return true;
665
		}
666
667
		if (a.components.size() != b.components.size()) {
668
			return false;
669
		}
670
671
		for (DataComponentType<?> type : a.components.keySet()) {
672
			Object componentA = a.components.get(type);
673
			Object componentB = b.components.get(type);
674
			if (componentA == null || componentB == null) {
675
				return false;
676
			}
677
678
			if (!Objects.equals(componentA, componentB) && !ignoredPredicate.test(type)) {
679
				return false;
680
			}
681
		}
682
683
		return true;
684
	}
685
686
	public static MapCodec<ItemStack> lenientOptionalFieldOf(final String name) {
687
		return CODEC.lenientOptionalFieldOf(name)
688
			.xmap(itemStack -> itemStack.orElse(EMPTY), itemStack -> itemStack.isEmpty() ? Optional.empty() : Optional.of(itemStack));
689
	}
690
691
	public static int hashItemAndComponents(final @Nullable ItemStack item) {
692
		if (item != null) {
693
			int result = 31 + item.getItem().hashCode();
694
			return 31 * result + item.getComponents().hashCode();
695
		} else {
696
			return 0;
697
		}
698
	}
699
700
	@Deprecated
701
	public static int hashStackList(final List<ItemStack> items) {
702
		int result = 0;
703
704
		for (ItemStack item : items) {
705
			result = result * 31 + hashItemAndComponents(item);
706
		}
707
708
		return result;
709
	}
710
711
	@Override
712
	public String toString() {
713
		return this.getCount() + " " + this.getItem();
714
	}
715
716
	public void inventoryTick(final Level level, final Entity owner, final @Nullable EquipmentSlot slot) {
717
		if (this.popTime > 0) {
718
			this.popTime--;
719
		}
720
721
		if (level instanceof ServerLevel serverLevel) {
722
			this.getItem().inventoryTick(this, serverLevel, owner, slot);
723
		}
724
	}
725
726
	public void onCraftedBy(final Player player, final int craftCount) {
727
		player.awardStat(Stats.ITEM_CRAFTED.get(this.getItem()), craftCount);
728
		this.getItem().onCraftedBy(this, player);
729
	}
730
731
	public void onCraftedBySystem(final Level level) {
732
		this.getItem().onCraftedPostProcess(this, level);
733
	}
734
735
	public int getUseDuration(final LivingEntity user) {
736
		return this.getItem().getUseDuration(this, user);
737
	}
738
739
	public ItemUseAnimation getUseAnimation() {
740
		return this.getItem().getUseAnimation(this);
741
	}
742
743
	public void releaseUsing(final Level level, final LivingEntity entity, final int remainingTime) {
744
		ItemStack stackBeforeUsing = this.copy();
745
		if (this.getItem().releaseUsing(this, level, entity, remainingTime)) {
746
			ItemStack withSideEffects = this.applyAfterUseComponentSideEffects(entity, stackBeforeUsing);
747
			if (withSideEffects != this) {
748
				entity.setItemInHand(entity.getUsedItemHand(), withSideEffects);
749
			}
750
		}
751
	}
752
753
	public void causeUseVibration(final Entity causer, final Holder.Reference<GameEvent> event) {
754
		UseEffects useEffects = this.get(DataComponents.USE_EFFECTS);
755
		if (useEffects != null && useEffects.interactVibrations()) {
756
			causer.gameEvent(event);
757
		}
758
	}
759
760
	public boolean useOnRelease() {
761
		return this.getItem().useOnRelease(this);
762
	}
763
764
	public <T> @Nullable T set(final DataComponentType<T> type, final @Nullable T value) {
765
		return this.components.set(type, value);
766
	}
767
768
	public <T> @Nullable T set(final TypedDataComponent<T> value) {
769
		return this.components.set(value);
770
	}
771
772
	public <T> void copyFrom(final DataComponentType<T> type, final DataComponentGetter source) {
773
		this.set(type, source.get(type));
774
	}
775
776
	public <T, U> @Nullable T update(final DataComponentType<T> type, final T defaultValue, final U value, final BiFunction<T, U, T> combiner) {
777
		return this.set(type, combiner.apply(this.getOrDefault(type, defaultValue), value));
778
	}
779
780
	public <T> @Nullable T update(final DataComponentType<T> type, final T defaultValue, final UnaryOperator<T> function) {
781
		T value = this.getOrDefault(type, defaultValue);
782
		return this.set(type, function.apply(value));
783
	}
784
785
	public <T> @Nullable T remove(final DataComponentType<? extends T> type) {
786
		return this.components.remove(type);
787
	}
788
789
	public void applyComponentsAndValidate(final DataComponentPatch patch) {
790
		DataComponentPatch oldPatch = this.components.asPatch();
791
		this.components.applyPatch(patch);
792
		Optional<Error<ItemStack>> validationError = validateStrict(this).error();
793
		if (validationError.isPresent()) {
794
			LOGGER.error("Failed to apply component patch '{}' to item: '{}'", patch, validationError.get().message());
795
			this.components.restorePatch(oldPatch);
796
		}
797
	}
798
799
	public void applyComponents(final DataComponentPatch patch) {
800
		this.components.applyPatch(patch);
801
	}
802
803
	public void applyComponents(final DataComponentMap components) {
804
		this.components.setAll(components);
805
	}
806
807
	public Component getHoverName() {
808
		Component customName = this.getCustomName();
809
		return customName != null ? customName : this.getItemName();
810
	}
811
812
	public @Nullable Component getCustomName() {
813
		Component customName = this.get(DataComponents.CUSTOM_NAME);
814
		if (customName != null) {
815
			return customName;
816
		}
817
818
		WrittenBookContent content = this.get(DataComponents.WRITTEN_BOOK_CONTENT);
819
		if (content != null) {
820
			String title = content.title().raw();
821
			if (!StringUtil.isBlank(title)) {
822
				return Component.literal(title);
823
			}
824
		}
825
826
		return null;
827
	}
828
829
	public Component getItemName() {
830
		return this.getItem().getName(this);
831
	}
832
833
	public Component getStyledHoverName() {
834
		MutableComponent hoverName = Component.empty().append(this.getHoverName()).withStyle(this.getRarity().color());
835
		if (this.has(DataComponents.CUSTOM_NAME)) {
836
			hoverName.withStyle(ChatFormatting.ITALIC);
837
		}
838
839
		return hoverName;
840
	}
841
842
	public <T> void addToTooltip(
843
		final DataComponentType<T> type,
844
		final TooltipProvider.Getter<T> tooltipGetter,
845
		final Item.TooltipContext context,
846
		final TooltipDisplay display,
847
		final Consumer<Component> consumer,
848
		final TooltipFlag flag
849
	) {
850
		T component = this.get(type);
851
		if (component != null && display.shows(type)) {
852
			tooltipGetter.get(component).addToTooltip(context, consumer, flag, this.components);
853
		}
854
	}
855
856
	public <T extends TooltipProvider> void addToTooltip(
857
		final DataComponentType<T> type, final Item.TooltipContext context, final TooltipDisplay display, final Consumer<Component> consumer, final TooltipFlag flag
858
	) {
859
		this.addToTooltip(type, c -> c, context, display, consumer, flag);
860
	}
861
862
	public List<Component> getTooltipLines(final Item.TooltipContext context, final @Nullable Player player, final TooltipFlag tooltipFlag) {
863
		TooltipDisplay display = this.getOrDefault(DataComponents.TOOLTIP_DISPLAY, TooltipDisplay.DEFAULT);
864
		if (!tooltipFlag.isCreative() && display.hideTooltip()) {
865
			boolean shouldPrintOpWarning = this.getItem().shouldPrintOpWarning(this, player);
866
			return shouldPrintOpWarning ? OP_NBT_WARNING : List.of();
867
		} else {
868
			List<Component> lines = Lists.newArrayList();
869
			lines.add(this.getStyledHoverName());
870
			this.addDetailsToTooltip(context, display, player, tooltipFlag, lines::add);
871
			return lines;
872
		}
873
	}
874
875
	public void addDetailsToTooltip(
876
		final Item.TooltipContext context,
877
		final TooltipDisplay display,
878
		final @Nullable Player player,
879
		final TooltipFlag tooltipFlag,
880
		final Consumer<Component> builder
881
	) {
882
		this.getItem().appendHoverText(this, context, display, builder, tooltipFlag);
883
		this.addToTooltip(DataComponents.TROPICAL_FISH_PATTERN, context, display, builder, tooltipFlag);
884
		this.addToTooltip(DataComponents.INSTRUMENT, context, display, builder, tooltipFlag);
885
		this.addToTooltip(DataComponents.MAP_ID, context, display, builder, tooltipFlag);
886
		this.addToTooltip(DataComponents.BEES, context, display, builder, tooltipFlag);
887
		this.addToTooltip(DataComponents.CONTAINER_LOOT, context, display, builder, tooltipFlag);
888
		this.addToTooltip(DataComponents.CONTAINER, context, display, builder, tooltipFlag);
889
		this.addToTooltip(DataComponents.BANNER_PATTERNS, context, display, builder, tooltipFlag);
890
		this.addToTooltip(DataComponents.POT_DECORATIONS, context, display, builder, tooltipFlag);
891
		this.addToTooltip(DataComponents.WRITTEN_BOOK_CONTENT, context, display, builder, tooltipFlag);
892
		this.addToTooltip(DataComponents.CHARGED_PROJECTILES, context, display, builder, tooltipFlag);
893
		this.addToTooltip(DataComponents.FIREWORKS, context, display, builder, tooltipFlag);
894
		this.addToTooltip(DataComponents.FIREWORK_EXPLOSION, context, display, builder, tooltipFlag);
895
		this.addToTooltip(DataComponents.POTION_CONTENTS, context, display, builder, tooltipFlag);
896
		this.addToTooltip(DataComponents.JUKEBOX_PLAYABLE, context, display, builder, tooltipFlag);
897
		this.addToTooltip(DataComponents.TRIM, context, display, builder, tooltipFlag);
898
		this.addToTooltip(DataComponents.STORED_ENCHANTMENTS, context, display, builder, tooltipFlag);
899
		this.addToTooltip(DataComponents.ENCHANTMENTS, context, display, builder, tooltipFlag);
900
		this.addToTooltip(DataComponents.DYED_COLOR, context, display, builder, tooltipFlag);
901
		this.addToTooltip(DataComponents.PROFILE, context, display, builder, tooltipFlag);
902
		this.addToTooltip(DataComponents.LORE, context, display, builder, tooltipFlag);
903
		this.addToTooltip(DataComponents.SULFUR_CUBE_CONTENT, context, display, builder, tooltipFlag);
904
		this.addAttributeTooltips(builder, display, player);
905
		this.addUnitComponentToTooltip(DataComponents.INTANGIBLE_PROJECTILE, INTANGIBLE_TOOLTIP, display, builder);
906
		this.addUnitComponentToTooltip(DataComponents.UNBREAKABLE, UNBREAKABLE_TOOLTIP, display, builder);
907
		this.addToTooltip(DataComponents.SIGN_TEXT_FRONT, SignText.FRONT_TEXT, context, display, builder, tooltipFlag);
908
		this.addToTooltip(DataComponents.SIGN_TEXT_BACK, SignText.BACK_TEXT, context, display, builder, tooltipFlag);
909
		this.addToTooltip(DataComponents.OMINOUS_BOTTLE_AMPLIFIER, context, display, builder, tooltipFlag);
910
		this.addToTooltip(DataComponents.SUSPICIOUS_STEW_EFFECTS, context, display, builder, tooltipFlag);
911
		this.addToTooltip(DataComponents.BLOCK_STATE, context, display, builder, tooltipFlag);
912
		this.addToTooltip(DataComponents.ENTITY_DATA, context, display, builder, tooltipFlag);
913
		if ((this.is(Items.SPAWNER) || this.is(Items.TRIAL_SPAWNER)) && display.shows(DataComponents.BLOCK_ENTITY_DATA)) {
914
			TypedEntityData<BlockEntityType<?>> blockEntityData = this.get(DataComponents.BLOCK_ENTITY_DATA);
915
			Spawner.appendHoverText(blockEntityData, builder, "SpawnData");
916
		}
917
918
		AdventureModePredicate canBreak = this.get(DataComponents.CAN_BREAK);
919
		if (canBreak != null && display.shows(DataComponents.CAN_BREAK)) {
920
			builder.accept(CommonComponents.EMPTY);
921
			builder.accept(AdventureModePredicate.CAN_BREAK_HEADER);
922
			canBreak.addToTooltip(builder);
923
		}
924
925
		AdventureModePredicate canPlaceOn = this.get(DataComponents.CAN_PLACE_ON);
926
		if (canPlaceOn != null && display.shows(DataComponents.CAN_PLACE_ON)) {
927
			builder.accept(CommonComponents.EMPTY);
928
			builder.accept(AdventureModePredicate.CAN_PLACE_HEADER);
929
			canPlaceOn.addToTooltip(builder);
930
		}
931
932
		if (tooltipFlag.isAdvanced()) {
933
			if (this.isDamaged() && display.shows(DataComponents.DAMAGE)) {
934
				builder.accept(Component.translatable("item.durability", this.getMaxDamage() - this.getDamageValue(), this.getMaxDamage()));
935
			}
936
937
			builder.accept(Component.literal(BuiltInRegistries.ITEM.getKey(this.getItem()).toString()).withStyle(ChatFormatting.DARK_GRAY));
938
			int count = this.components.size();
939
			if (count > 0) {
940
				builder.accept(Component.translatable("item.components", count).withStyle(ChatFormatting.DARK_GRAY));
941
			}
942
		}
943
944
		if (player != null && !this.getItem().isEnabled(player.level().enabledFeatures())) {
945
			builder.accept(DISABLED_ITEM_TOOLTIP);
946
		}
947
948
		boolean shouldPrintOpWarning = this.getItem().shouldPrintOpWarning(this, player);
949
		if (shouldPrintOpWarning) {
950
			OP_NBT_WARNING.forEach(builder);
951
		}
952
	}
953
954
	private void addUnitComponentToTooltip(
955
		final DataComponentType<?> dataComponentType, final Component component, final TooltipDisplay display, final Consumer<Component> builder
956
	) {
957
		if (this.has(dataComponentType) && display.shows(dataComponentType)) {
958
			builder.accept(component);
959
		}
960
	}
961
962
	private void addAttributeTooltips(final Consumer<Component> consumer, final TooltipDisplay display, final @Nullable Player player) {
963
		if (display.shows(DataComponents.ATTRIBUTE_MODIFIERS)) {
964
			for (EquipmentSlotGroup slot : EquipmentSlotGroup.values()) {
965
				MutableBoolean first = new MutableBoolean(true);
966
				this.forEachModifier(slot, (attribute, modifier, tooltip) -> {
967
					if (tooltip != ItemAttributeModifiers.Display.hidden()) {
968
						if (first.isTrue()) {
969
							consumer.accept(CommonComponents.EMPTY);
970
							consumer.accept(Component.translatable("item.modifiers." + slot.getSerializedName()).withStyle(ChatFormatting.GRAY));
971
							first.setFalse();
972
						}
973
974
						tooltip.apply(consumer, player, attribute, modifier);
975
					}
976
				});
977
			}
978
		}
979
	}
980
981
	public boolean hasFoil() {
982
		Boolean enchantmentGlintOverride = this.get(DataComponents.ENCHANTMENT_GLINT_OVERRIDE);
983
		return enchantmentGlintOverride != null ? enchantmentGlintOverride : this.getItem().isFoil(this);
984
	}
985
986
	public Rarity getRarity() {
987
		Rarity baseRarity = this.getOrDefault(DataComponents.RARITY, Rarity.COMMON);
988
		if (!this.isEnchanted()) {
989
			return baseRarity;
990
		}
991
992
		return switch (baseRarity) {
993
			case COMMON, UNCOMMON -> Rarity.RARE;
994
			case RARE -> Rarity.EPIC;
995
			default -> baseRarity;
996
		};
997
	}
998
999
	public boolean isEnchantable() {
1000
		if (!this.has(DataComponents.ENCHANTABLE)) {
1001
			return false;
1002
		}
1003
1004
		ItemEnchantments enchantments = this.get(DataComponents.ENCHANTMENTS);
1005
		return enchantments != null && enchantments.isEmpty();
1006
	}
1007
1008
	public void enchant(final Holder<Enchantment> enchantment, final int level) {
1009
		EnchantmentHelper.updateEnchantments(this, enchantments -> enchantments.upgrade(enchantment, level));
1010
	}
1011
1012
	public boolean isEnchanted() {
1013
		return !this.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY).isEmpty();
1014
	}
1015
1016
	public ItemEnchantments getEnchantments() {
1017
		return this.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY);
1018
	}
1019
1020
	public void forEachModifier(final EquipmentSlotGroup slot, final TriConsumer<Holder<Attribute>, AttributeModifier, ItemAttributeModifiers.Display> consumer) {
1021
		ItemAttributeModifiers modifiers = this.getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY);
1022
		modifiers.forEach(slot, consumer);
1023
		EnchantmentHelper.forEachModifier(this, slot, (a, b) -> consumer.accept(a, b, ItemAttributeModifiers.Display.attributeModifiers()));
1024
	}
1025
1026
	public void forEachModifier(final EquipmentSlot slot, final BiConsumer<Holder<Attribute>, AttributeModifier> consumer) {
1027
		ItemAttributeModifiers modifiers = this.getOrDefault(DataComponents.ATTRIBUTE_MODIFIERS, ItemAttributeModifiers.EMPTY);
1028
		modifiers.forEach(slot, consumer);
1029
		EnchantmentHelper.forEachModifier(this, slot, consumer);
1030
	}
1031
1032
	public Component getDisplayName() {
1033
		MutableComponent hoverName = Component.empty().append(this.getHoverName());
1034
		if (this.has(DataComponents.CUSTOM_NAME)) {
1035
			hoverName.withStyle(ChatFormatting.ITALIC);
1036
		}
1037
1038
		MutableComponent result = ComponentUtils.wrapInSquareBrackets(hoverName);
1039
		if (!this.isEmpty()) {
1040
			result.withStyle(this.getRarity().color()).withStyle(s -> s.withHoverEvent(new HoverEvent.ShowItem(ItemStackTemplate.fromNonEmptyStack(this))));
1041
		}
1042
1043
		return result;
1044
	}
1045
1046
	public SwingAnimation getAttackAnimation() {
1047
		return this.getOrDefault(DataComponents.ATTACK_ANIMATION, SwingAnimation.DEFAULT);
1048
	}
1049
1050
	public SwingAnimation getInteractAnimation() {
1051
		return this.getOrDefault(DataComponents.INTERACT_ANIMATION, SwingAnimation.DEFAULT);
1052
	}
1053
1054
	public boolean canPlaceOnBlockInAdventureMode(final BlockInWorld blockInWorld) {
1055
		AdventureModePredicate canPlaceOn = this.get(DataComponents.CAN_PLACE_ON);
1056
		return canPlaceOn != null && canPlaceOn.test(blockInWorld);
1057
	}
1058
1059
	public boolean canBreakBlockInAdventureMode(final BlockInWorld blockInWorld) {
1060
		AdventureModePredicate canBreak = this.get(DataComponents.CAN_BREAK);
1061
		return canBreak != null && canBreak.test(blockInWorld);
1062
	}
1063
1064
	public int getPopTime() {
1065
		return this.popTime;
1066
	}
1067
1068
	public void setPopTime(final int popTime) {
1069
		this.popTime = popTime;
1070
	}
1071
1072
	public int getCount() {
1073
		return this.isEmpty() ? 0 : this.count;
1074
	}
1075
1076
	@Override
1077
	public int count() {
1078
		return this.getCount();
1079
	}
1080
1081
	public void setCount(final int count) {
1082
		this.count = count;
1083
	}
1084
1085
	public void limitSize(final int maxStackSize) {
1086
		if (!this.isEmpty() && this.getCount() > maxStackSize) {
1087
			this.setCount(maxStackSize);
1088
		}
1089
	}
1090
1091
	public void grow(final int amount) {
1092
		this.setCount(this.getCount() + amount);
1093
	}
1094
1095
	public void shrink(final int amount) {
1096
		this.grow(-amount);
1097
	}
1098
1099
	public void consume(final int amount, final @Nullable LivingEntity owner) {
1100
		if (owner == null || !owner.hasInfiniteMaterials()) {
1101
			this.shrink(amount);
1102
		}
1103
	}
1104
1105
	public ItemStack consumeAndReturn(final int amount, final @Nullable LivingEntity owner) {
1106
		ItemStack split = this.copyWithCount(amount);
1107
		this.consume(amount, owner);
1108
		return split;
1109
	}
1110
1111
	public void onUseTick(final Level level, final LivingEntity livingEntity, final int ticksRemaining) {
1112
		Consumable consumable = this.get(DataComponents.CONSUMABLE);
1113
		if (consumable != null && consumable.shouldEmitParticlesAndSounds(ticksRemaining)) {
1114
			consumable.emitParticlesAndSounds(livingEntity.getRandom(), livingEntity, this, 5);
1115
		}
1116
1117
		KineticWeapon kineticWeapon = this.get(DataComponents.KINETIC_WEAPON);
1118
		if (kineticWeapon != null && !level.isClientSide()) {
1119
			kineticWeapon.damageEntities(this, ticksRemaining, livingEntity, livingEntity.getUsedItemHand().asEquipmentSlot());
1120
		} else {
1121
			this.getItem().onUseTick(level, livingEntity, this, ticksRemaining);
1122
		}
1123
	}
1124
1125
	public void onDestroyed(final ItemEntity itemEntity) {
1126
		this.getItem().onDestroyed(itemEntity);
1127
	}
1128
1129
	public boolean canBeHurtBy(final DamageSource source) {
1130
		DamageResistant damageResistant = this.get(DataComponents.DAMAGE_RESISTANT);
1131
		return damageResistant == null || !damageResistant.isResistantTo(source);
1132
	}
1133
1134
	public boolean isValidRepairItem(final ItemStack repairItem) {
1135
		Repairable repairable = this.get(DataComponents.REPAIRABLE);
1136
		return repairable != null && repairable.isValidRepairItem(repairItem);
1137
	}
1138
1139
	public boolean canDestroyBlock(final BlockState state, final Level level, final BlockPos pos, final Player player) {
1140
		return this.getItem().canDestroyBlock(this, state, level, pos, player);
1141
	}
1142
1143
	public DamageSource getDamageSource(final LivingEntity attacker) {
1144
		return Optional.ofNullable(this.get(DataComponents.DAMAGE_TYPE))
1145
			.map(type -> new DamageSource((Holder<DamageType>)type, attacker))
1146
			.or(() -> Optional.ofNullable(this.getItem().getItemDamageSource(attacker)))
1147
			.orElseGet(attacker::createDamageSource);
1148
	}
1149
}
1150

Decompiled Minecraft 26.3 source of ItemStack (net/minecraft/world/item/ItemStack.java) with Mojang official mappings, stored verbatim on the site.