ItemEntity .java

net.minecraft.world.entity.item.ItemEntity (class, 449 lines): members: INFINITE_PICKUP_DELAY, setDefaultPickUpDelay, DEFAULT_PICKUP_DELAY, hasPickUpDelay.

net.minecraft.world.entity.itemclass449 linescommonextends Entity13.6 KB

Implements

API Surface (36)

boolean dampensVibrations()
void restoreFrom(final Entity oldEntity)
Entity.MovementEmission getMovementEmission()
void defineSynchedData(final SynchedEntityData.Builder entityData)
double getDefaultGravity()
void tick()
BlockPos getBlockPosBelowThatAffectsMyMovement()
boolean areMergable(final ItemStack thisItemStack, final ItemStack otherItemStack)
ItemStack merge(final ItemStack toStack, final ItemStack fromStack, final int maxCount)
boolean fireImmune()
boolean shouldPlayLavaHurtSound()
boolean hurtClient(final DamageSource source)
boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage)
boolean ignoreExplosion(final Explosion explosion)
void addAdditionalSaveData(final ValueOutput output)
void readAdditionalSaveData(final ValueInput input)
void playerTouch(final Player player)
Component getName()
boolean isAttackable()
ItemStack getItem()
void setItem(final ItemStack itemStack)
void setTarget(final @Nullable UUID target)
void setThrower(final Entity thrower)
int getAge()
void setDefaultPickUpDelay()
void setNoPickUpDelay()
void setNeverPickUp()
void setPickUpDelay(final int ticks)
boolean hasPickUpDelay()
void setUnlimitedLifetime()
void setExtendedLifetime()
void makeFakeItem()
float getSpin(final float ageInTicks, final float bobOffset)
SoundSource getSoundSource()
float getVisualRotationYInDegrees()
MoveSimulationType getMoveSimulationType()

Fields & Constants (16)

DATA_ITEM
FLOAT_HEIGHT
EYE_HEIGHT
LIFETIME
INFINITE_PICKUP_DELAY
INFINITE_LIFETIME
DEFAULT_HEALTH
DEFAULT_AGE
DEFAULT_PICKUP_DELAY
age
pickupDelay
health
thrower
target
bobOffs
deltaY

String literals (5)

"Health"
"PickupDelay"
"Thrower"
"Owner"
"Item"

Full Source

ItemEntity.java449 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.item;
2
3
import java.util.Objects;
4
import java.util.UUID;
5
import net.minecraft.core.BlockPos;
6
import net.minecraft.core.UUIDUtil;
7
import net.minecraft.network.chat.Component;
8
import net.minecraft.network.syncher.EntityDataAccessor;
9
import net.minecraft.network.syncher.EntityDataSerializers;
10
import net.minecraft.network.syncher.SynchedEntityData;
11
import net.minecraft.server.level.ServerLevel;
12
import net.minecraft.sounds.SoundSource;
13
import net.minecraft.stats.Stats;
14
import net.minecraft.tags.FluidTags;
15
import net.minecraft.tags.ItemTags;
16
import net.minecraft.util.Mth;
17
import net.minecraft.world.damagesource.DamageSource;
18
import net.minecraft.world.entity.Entity;
19
import net.minecraft.world.entity.EntityReference;
20
import net.minecraft.world.entity.EntityType;
21
import net.minecraft.world.entity.EntityTypes;
22
import net.minecraft.world.entity.Mob;
23
import net.minecraft.world.entity.MoveSimulationType;
24
import net.minecraft.world.entity.MoverType;
25
import net.minecraft.world.entity.SlotAccess;
26
import net.minecraft.world.entity.TraceableEntity;
27
import net.minecraft.world.entity.player.Player;
28
import net.minecraft.world.item.Item;
29
import net.minecraft.world.item.ItemStack;
30
import net.minecraft.world.level.Explosion;
31
import net.minecraft.world.level.Level;
32
import net.minecraft.world.level.gameevent.GameEvent;
33
import net.minecraft.world.level.gamerules.GameRules;
34
import net.minecraft.world.level.portal.TeleportTransition;
35
import net.minecraft.world.level.storage.ValueInput;
36
import net.minecraft.world.level.storage.ValueOutput;
37
import net.minecraft.world.phys.Vec3;
38
import org.jspecify.annotations.Nullable;
39
40
public class ItemEntity extends Entity implements TraceableEntity {
41
	private static final EntityDataAccessor<ItemStack> DATA_ITEM = SynchedEntityData.defineId(ItemEntity.class, EntityDataSerializers.ITEM_STACK);
42
	private static final float FLOAT_HEIGHT = 0.1F;
43
	public static final float EYE_HEIGHT = 0.2125F;
44
	private static final int LIFETIME = 6000;
45
	private static final int INFINITE_PICKUP_DELAY = 32767;
46
	private static final int INFINITE_LIFETIME = -32768;
47
	public static final int DEFAULT_HEALTH = 5;
48
	private static final short DEFAULT_AGE = 0;
49
	private static final short DEFAULT_PICKUP_DELAY = 0;
50
	private int age = 0;
51
	private int pickupDelay = 0;
52
	private int health = 5;
53
	private @Nullable EntityReference<Entity> thrower;
54
	private @Nullable UUID target;
55
	public final float bobOffs = this.random.nextFloat() * (float) Math.PI * 2.0F;
56
57
	public ItemEntity(final EntityType<? extends ItemEntity> type, final Level level) {
58
		super(type, level);
59
		this.setYRot(this.random.nextFloat() * 360.0F);
60
	}
61
62
	public ItemEntity(final Level level, final double x, final double y, final double z, final ItemStack itemStack) {
63
		this(EntityTypes.ITEM, level);
64
		this.setPos(x, y, z);
65
		this.setItem(itemStack);
66
		this.setDeltaMovement(this.random.nextDouble() * 0.2 - 0.1, 0.2, this.random.nextDouble() * 0.2 - 0.1);
67
	}
68
69
	public ItemEntity(
70
		final Level level, final double x, final double y, final double z, final ItemStack itemStack, final double deltaX, final double deltaY, final double deltaZ
71
	) {
72
		this(EntityTypes.ITEM, level);
73
		this.setPos(x, y, z);
74
		this.setItem(itemStack);
75
		this.setDeltaMovement(deltaX, deltaY, deltaZ);
76
	}
77
78
	@Override
79
	public boolean dampensVibrations() {
80
		return this.getItem().is(ItemTags.DAMPENS_VIBRATIONS);
81
	}
82
83
	@Override
84
	public @Nullable Entity getOwner() {
85
		return EntityReference.getEntity(this.thrower, this.level());
86
	}
87
88
	@Override
89
	public void restoreFrom(final Entity oldEntity) {
90
		super.restoreFrom(oldEntity);
91
		if (oldEntity instanceof ItemEntity item) {
92
			this.thrower = item.thrower;
93
		}
94
	}
95
96
	@Override
97
	protected Entity.MovementEmission getMovementEmission() {
98
		return Entity.MovementEmission.NONE;
99
	}
100
101
	@Override
102
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
103
		entityData.define(DATA_ITEM, ItemStack.EMPTY);
104
	}
105
106
	@Override
107
	protected double getDefaultGravity() {
108
		return 0.04;
109
	}
110
111
	@Override
112
	public void tick() {
113
		if (this.getItem().isEmpty()) {
114
			this.discard();
115
		} else {
116
			super.tick();
117
			if (this.pickupDelay > 0 && this.pickupDelay != 32767) {
118
				this.pickupDelay--;
119
			}
120
121
			this.xo = this.getX();
122
			this.yo = this.getY();
123
			this.zo = this.getZ();
124
			Vec3 oldMovement = this.getDeltaMovement();
125
			if (this.isInWater() && this.getFluidHeight(FluidTags.WATER) > 0.1F) {
126
				this.setUnderwaterMovement();
127
			} else if (this.isInLava() && this.getFluidHeight(FluidTags.LAVA) > 0.1F) {
128
				this.setUnderLavaMovement();
129
			} else {
130
				this.applyGravity();
131
			}
132
133
			if (this.level().isClientSide()) {
134
				this.noPhysics = false;
135
			} else {
136
				this.noPhysics = !this.level().noCollision(this, this.getBoundingBox().deflate(1.0E-7));
137
				if (this.noPhysics) {
138
					this.moveTowardsClosestSpace(this.getX(), (this.getBoundingBox().minY + this.getBoundingBox().maxY) / 2.0, this.getZ());
139
				}
140
			}
141
142
			if (this.onGround() && !(this.getDeltaMovement().horizontalDistanceSqr() > 1.0E-5F) && (this.tickCount + this.getId()) % 4 != 0) {
143
				this.applyEffectsFromBlocksForLastMovements();
144
			} else {
145
				this.move(MoverType.SELF, this.getDeltaMovement());
146
				this.applyEffectsFromBlocks();
147
				float airDrag = this.getAirDrag();
148
				float groundFriction = airDrag;
149
				if (this.onGround()) {
150
					groundFriction *= this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction();
151
				}
152
153
				this.setDeltaMovement(this.getDeltaMovement().multiply(groundFriction, airDrag, groundFriction));
154
				if (this.onGround()) {
155
					Vec3 movement = this.getDeltaMovement();
156
					if (movement.y < 0.0) {
157
						this.setDeltaMovement(movement.multiply(1.0, -0.5, 1.0));
158
					}
159
				}
160
			}
161
162
			boolean moved = Mth.floor(this.xo) != Mth.floor(this.getX()) || Mth.floor(this.yo) != Mth.floor(this.getY()) || Mth.floor(this.zo) != Mth.floor(this.getZ());
163
			int rate = moved ? 2 : 40;
164
			if (this.tickCount % rate == 0 && !this.level().isClientSide() && this.isMergable()) {
165
				this.mergeWithNeighbours();
166
			}
167
168
			if (this.age != -32768) {
169
				this.age++;
170
			}
171
172
			this.needsSync = this.needsSync | this.updateFluidInteraction();
173
			if (!this.level().isClientSide()) {
174
				double value = this.getDeltaMovement().subtract(oldMovement).lengthSqr();
175
				if (value > 0.01) {
176
					this.needsSync = true;
177
				}
178
			}
179
180
			if (!this.level().isClientSide() && this.age >= 6000) {
181
				this.discard();
182
			}
183
		}
184
	}
185
186
	@Override
187
	public BlockPos getBlockPosBelowThatAffectsMyMovement() {
188
		return this.getOnPos(0.999999F);
189
	}
190
191
	private void setUnderwaterMovement() {
192
		this.setFluidMovement(0.99F);
193
	}
194
195
	private void setUnderLavaMovement() {
196
		this.setFluidMovement(0.95F);
197
	}
198
199
	private void setFluidMovement(final double multiplier) {
200
		Vec3 movement = this.getDeltaMovement();
201
		this.setDeltaMovement(movement.x * multiplier, movement.y + (movement.y < 0.06F ? 5.0E-4F : 0.0F), movement.z * multiplier);
202
	}
203
204
	private void mergeWithNeighbours() {
205
		if (this.isMergable()) {
206
			for (ItemEntity entity : this.level()
207
				.getEntitiesOfClass(ItemEntity.class, this.getBoundingBox().inflate(0.5, 0.0, 0.5), other -> other != this && other.isMergable())) {
208
				if (entity.isMergable()) {
209
					this.tryToMerge(entity);
210
					if (this.isRemoved()) {
211
						break;
212
					}
213
				}
214
			}
215
		}
216
	}
217
218
	private boolean isMergable() {
219
		ItemStack item = this.getItem();
220
		return this.isAlive() && this.pickupDelay != 32767 && this.age != -32768 && this.age < 6000 && item.getCount() < item.getMaxStackSize();
221
	}
222
223
	private void tryToMerge(final ItemEntity other) {
224
		ItemStack thisItemStack = this.getItem();
225
		ItemStack otherItemStack = other.getItem();
226
		if (Objects.equals(this.target, other.target) && areMergable(thisItemStack, otherItemStack)) {
227
			if (otherItemStack.getCount() < thisItemStack.getCount()) {
228
				merge(this, thisItemStack, other, otherItemStack);
229
			} else {
230
				merge(other, otherItemStack, this, thisItemStack);
231
			}
232
		}
233
	}
234
235
	public static boolean areMergable(final ItemStack thisItemStack, final ItemStack otherItemStack) {
236
		return otherItemStack.getCount() + thisItemStack.getCount() > otherItemStack.getMaxStackSize()
237
			? false
238
			: ItemStack.isSameItemSameComponents(thisItemStack, otherItemStack);
239
	}
240
241
	public static ItemStack merge(final ItemStack toStack, final ItemStack fromStack, final int maxCount) {
242
		int delta = Math.min(Math.min(toStack.getMaxStackSize(), maxCount) - toStack.getCount(), fromStack.getCount());
243
		ItemStack newToStack = toStack.copyWithCount(toStack.getCount() + delta);
244
		fromStack.shrink(delta);
245
		return newToStack;
246
	}
247
248
	private static void merge(final ItemEntity toItem, final ItemStack toStack, final ItemStack fromStack) {
249
		ItemStack newToStack = merge(toStack, fromStack, 64);
250
		toItem.setItem(newToStack);
251
	}
252
253
	private static void merge(final ItemEntity toItem, final ItemStack toStack, final ItemEntity fromItem, final ItemStack fromStack) {
254
		merge(toItem, toStack, fromStack);
255
		toItem.pickupDelay = Math.max(toItem.pickupDelay, fromItem.pickupDelay);
256
		toItem.age = Math.min(toItem.age, fromItem.age);
257
		if (fromStack.isEmpty()) {
258
			fromItem.discard();
259
		}
260
	}
261
262
	@Override
263
	public boolean fireImmune() {
264
		return !this.getItem().canBeHurtBy(this.damageSources().inFire()) || super.fireImmune();
265
	}
266
267
	@Override
268
	protected boolean shouldPlayLavaHurtSound() {
269
		return this.health <= 0 ? true : this.tickCount % 10 == 0;
270
	}
271
272
	@Override
273
	public final boolean hurtClient(final DamageSource source) {
274
		return this.isInvulnerableToBase(source) ? false : this.getItem().canBeHurtBy(source);
275
	}
276
277
	@Override
278
	public final boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage) {
279
		if (this.isInvulnerableToBase(source)) {
280
			return false;
281
		}
282
283
		if (!level.getGameRules().get(GameRules.MOB_GRIEFING) && source.getEntity() instanceof Mob) {
284
			return false;
285
		}
286
287
		if (!this.getItem().canBeHurtBy(source)) {
288
			return false;
289
		}
290
291
		this.markHurt();
292
		this.health = (int)(this.health - damage);
293
		this.gameEvent(GameEvent.ENTITY_DAMAGE, source.getEntity());
294
		if (this.health <= 0) {
295
			this.getItem().onDestroyed(this);
296
			this.discard();
297
		}
298
299
		return true;
300
	}
301
302
	@Override
303
	public boolean ignoreExplosion(final Explosion explosion) {
304
		return explosion.shouldAffectBlocklikeEntities() ? super.ignoreExplosion(explosion) : true;
305
	}
306
307
	@Override
308
	protected void addAdditionalSaveData(final ValueOutput output) {
309
		output.putShort("Health", (short)this.health);
310
		output.putShort("Age", (short)this.age);
311
		output.putShort("PickupDelay", (short)this.pickupDelay);
312
		EntityReference.store(this.thrower, output, "Thrower");
313
		output.storeNullable("Owner", UUIDUtil.CODEC, this.target);
314
		if (!this.getItem().isEmpty()) {
315
			output.store("Item", ItemStack.CODEC, this.getItem());
316
		}
317
	}
318
319
	@Override
320
	protected void readAdditionalSaveData(final ValueInput input) {
321
		this.health = input.getShortOr("Health", (short)5);
322
		this.age = input.getShortOr("Age", (short)0);
323
		this.pickupDelay = input.getShortOr("PickupDelay", (short)0);
324
		this.target = input.read("Owner", UUIDUtil.CODEC).orElse(null);
325
		this.thrower = EntityReference.read(input, "Thrower");
326
		this.setItem(input.read("Item", ItemStack.CODEC).orElse(ItemStack.EMPTY));
327
		if (this.getItem().isEmpty()) {
328
			this.discard();
329
		}
330
	}
331
332
	@Override
333
	public void playerTouch(final Player player) {
334
		if (!this.level().isClientSide()) {
335
			ItemStack itemStack = this.getItem();
336
			Item item = itemStack.getItem();
337
			int orgCount = itemStack.getCount();
338
			if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && player.getInventory().add(itemStack)) {
339
				player.take(this, orgCount);
340
				if (itemStack.isEmpty()) {
341
					this.discard();
342
					itemStack.setCount(orgCount);
343
				}
344
345
				player.awardStat(Stats.ITEM_PICKED_UP.get(item), orgCount);
346
				player.onItemPickup(this);
347
			}
348
		}
349
	}
350
351
	@Override
352
	public Component getName() {
353
		Component name = this.getCustomName();
354
		return name != null ? name : this.getItem().getItemName();
355
	}
356
357
	@Override
358
	public boolean isAttackable() {
359
		return false;
360
	}
361
362
	@Override
363
	public @Nullable Entity teleport(final TeleportTransition transition) {
364
		Entity entity = super.teleport(transition);
365
		if (!this.level().isClientSide() && entity instanceof ItemEntity item) {
366
			item.mergeWithNeighbours();
367
		}
368
369
		return entity;
370
	}
371
372
	public ItemStack getItem() {
373
		return this.getEntityData().get(DATA_ITEM);
374
	}
375
376
	public void setItem(final ItemStack itemStack) {
377
		this.getEntityData().set(DATA_ITEM, itemStack);
378
	}
379
380
	public void setTarget(final @Nullable UUID target) {
381
		this.target = target;
382
	}
383
384
	public void setThrower(final Entity thrower) {
385
		this.thrower = EntityReference.of(thrower);
386
	}
387
388
	public int getAge() {
389
		return this.age;
390
	}
391
392
	public void setDefaultPickUpDelay() {
393
		this.pickupDelay = 10;
394
	}
395
396
	public void setNoPickUpDelay() {
397
		this.pickupDelay = 0;
398
	}
399
400
	public void setNeverPickUp() {
401
		this.pickupDelay = 32767;
402
	}
403
404
	public void setPickUpDelay(final int ticks) {
405
		this.pickupDelay = ticks;
406
	}
407
408
	public boolean hasPickUpDelay() {
409
		return this.pickupDelay > 0;
410
	}
411
412
	public void setUnlimitedLifetime() {
413
		this.age = -32768;
414
	}
415
416
	public void setExtendedLifetime() {
417
		this.age = -6000;
418
	}
419
420
	public void makeFakeItem() {
421
		this.setNeverPickUp();
422
		this.age = 5999;
423
	}
424
425
	public static float getSpin(final float ageInTicks, final float bobOffset) {
426
		return ageInTicks / 20.0F + bobOffset;
427
	}
428
429
	@Override
430
	public SoundSource getSoundSource() {
431
		return SoundSource.AMBIENT;
432
	}
433
434
	@Override
435
	public float getVisualRotationYInDegrees() {
436
		return 180.0F - getSpin(this.getAge() + 0.5F, this.bobOffs) / (float) (Math.PI * 2) * 360.0F;
437
	}
438
439
	@Override
440
	public @Nullable SlotAccess getSlot(final int slot) {
441
		return slot == 0 ? SlotAccess.of(this::getItem, this::setItem) : super.getSlot(slot);
442
	}
443
444
	@Override
445
	public MoveSimulationType getMoveSimulationType() {
446
		return MoveSimulationType.SERVER_AND_CLIENT;
447
	}
448
}
449

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