ExperienceOrb .java

net.minecraft.world.entity.ExperienceOrb (class, 393 lines): members: ORB_GROUPS_PER_AREA, ENTITY_SCAN_PERIOD, ORB_MERGE_DISTANCE, awardWithDirection, age.

net.minecraft.world.entityclass393 linescommonextends Entity12.1 KB

API Surface (22)

void unstuckIfPossible(final double maxDistance)
Entity.MovementEmission getMovementEmission()
void defineSynchedData(final SynchedEntityData.Builder entityData)
double getDefaultGravity()
void tick()
float getAirDrag()
BlockPos getBlockPosBelowThatAffectsMyMovement()
void award(final ServerLevel level, final Vec3 pos, final int amount)
void awardWithDirection(final ServerLevel level, final Vec3 pos, final Vec3 roughDirection, int amount)
void doWaterSplashEffect()
boolean hurtClient(final DamageSource source)
boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage)
void addAdditionalSaveData(final ValueOutput output)
void readAdditionalSaveData(final ValueInput input)
void playerTouch(final Player player)
int getValue()
int getIcon()
int getExperienceValue(final int maxValue)
boolean isAttackable()
SoundSource getSoundSource()
InterpolationHandler createInterpolationHandler()
MoveSimulationType getMoveSimulationType()

Fields & Constants (14)

DATA_VALUE
LIFETIME
ENTITY_SCAN_PERIOD
MAX_FOLLOW_DIST
ORB_GROUPS_PER_AREA
ORB_MERGE_DISTANCE
DEFAULT_HEALTH
DEFAULT_AGE
DEFAULT_VALUE
DEFAULT_COUNT
age
health
count
followingPlayer

String literals (2)

"Health"
"Count"

Full Source

ExperienceOrb.java393 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity;
2
3
import java.util.List;
4
import java.util.Optional;
5
import net.minecraft.core.BlockPos;
6
import net.minecraft.network.syncher.EntityDataAccessor;
7
import net.minecraft.network.syncher.EntityDataSerializers;
8
import net.minecraft.network.syncher.SynchedEntityData;
9
import net.minecraft.server.level.ServerLevel;
10
import net.minecraft.server.level.ServerPlayer;
11
import net.minecraft.sounds.SoundSource;
12
import net.minecraft.tags.FluidTags;
13
import net.minecraft.util.ExtraCodecs;
14
import net.minecraft.world.damagesource.DamageSource;
15
import net.minecraft.world.entity.player.Player;
16
import net.minecraft.world.item.ItemStack;
17
import net.minecraft.world.item.enchantment.EnchantedItemInUse;
18
import net.minecraft.world.item.enchantment.EnchantmentEffectComponents;
19
import net.minecraft.world.item.enchantment.EnchantmentHelper;
20
import net.minecraft.world.level.Level;
21
import net.minecraft.world.level.entity.EntityTypeTest;
22
import net.minecraft.world.level.storage.ValueInput;
23
import net.minecraft.world.level.storage.ValueOutput;
24
import net.minecraft.world.phys.AABB;
25
import net.minecraft.world.phys.Vec3;
26
import net.minecraft.world.phys.shapes.Shapes;
27
import net.minecraft.world.phys.shapes.VoxelShape;
28
import org.jspecify.annotations.Nullable;
29
30
public class ExperienceOrb extends Entity {
31
	protected static final EntityDataAccessor<Integer> DATA_VALUE = SynchedEntityData.defineId(ExperienceOrb.class, EntityDataSerializers.INT);
32
	private static final int LIFETIME = 6000;
33
	private static final int ENTITY_SCAN_PERIOD = 20;
34
	private static final int MAX_FOLLOW_DIST = 8;
35
	private static final int ORB_GROUPS_PER_AREA = 40;
36
	private static final double ORB_MERGE_DISTANCE = 0.5;
37
	private static final short DEFAULT_HEALTH = 5;
38
	private static final short DEFAULT_AGE = 0;
39
	private static final short DEFAULT_VALUE = 0;
40
	private static final int DEFAULT_COUNT = 1;
41
	private int age = 0;
42
	private int health = 5;
43
	private int count = 1;
44
	private @Nullable Player followingPlayer;
45
46
	public ExperienceOrb(final Level level, final double x, final double y, final double z, final int value) {
47
		this(level, new Vec3(x, y, z), Vec3.ZERO, value);
48
	}
49
50
	public ExperienceOrb(final Level level, final Vec3 pos, final Vec3 roughly, final int value) {
51
		this(EntityTypes.EXPERIENCE_ORB, level);
52
		this.setPos(pos);
53
		if (!level.isClientSide()) {
54
			this.setYRot(this.random.nextFloat() * 360.0F);
55
			Vec3 randomMovement = new Vec3(
56
				(this.random.nextDouble() * 0.2 - 0.1) * 2.0, this.random.nextDouble() * 0.2 * 2.0, (this.random.nextDouble() * 0.2 - 0.1) * 2.0
57
			);
58
			if (roughly.lengthSqr() > 0.0 && roughly.dot(randomMovement) < 0.0) {
59
				randomMovement = randomMovement.scale(-1.0);
60
			}
61
62
			double size = this.getBoundingBox().getSize();
63
			this.setPos(pos.add(roughly.normalize().scale(size * 0.5)));
64
			this.setDeltaMovement(randomMovement);
65
			if (!level.noCollision(this.getBoundingBox())) {
66
				this.unstuckIfPossible(size);
67
			}
68
		}
69
70
		this.setValue(value);
71
	}
72
73
	public ExperienceOrb(final EntityType<? extends ExperienceOrb> type, final Level level) {
74
		super(type, level);
75
	}
76
77
	protected void unstuckIfPossible(final double maxDistance) {
78
		Vec3 center = this.position().add(0.0, this.getBbHeight() / 2.0, 0.0);
79
		VoxelShape allowedCenters = Shapes.create(AABB.ofSize(center, maxDistance, maxDistance, maxDistance));
80
		this.level()
81
			.findFreePosition(this, allowedCenters, center, this.getBbWidth(), this.getBbHeight(), this.getBbWidth())
82
			.ifPresent(pos -> this.setPos(pos.add(0.0, -this.getBbHeight() / 2.0, 0.0)));
83
	}
84
85
	@Override
86
	protected Entity.MovementEmission getMovementEmission() {
87
		return Entity.MovementEmission.NONE;
88
	}
89
90
	@Override
91
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
92
		entityData.define(DATA_VALUE, 0);
93
	}
94
95
	@Override
96
	protected double getDefaultGravity() {
97
		return 0.03;
98
	}
99
100
	@Override
101
	public void tick() {
102
		if (this.firstTick && this.level().isClientSide()) {
103
			this.firstTick = false;
104
		} else {
105
			super.tick();
106
			boolean colliding = !this.level().noCollision(this.getBoundingBox());
107
			if (this.isEyeInFluid(FluidTags.WATER)) {
108
				this.setUnderwaterMovement();
109
			} else if (!colliding) {
110
				this.applyGravity();
111
			}
112
113
			if (this.level().getFluidState(this.blockPosition()).is(FluidTags.LAVA)) {
114
				this.setDeltaMovement((this.random.nextFloat() - this.random.nextFloat()) * 0.2F, 0.2F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F);
115
			}
116
117
			if (this.tickCount % 20 == 1) {
118
				this.scanForMerges();
119
			}
120
121
			this.followNearbyPlayer();
122
			if (this.followingPlayer == null && !this.level().isClientSide() && colliding) {
123
				boolean nextColliding = !this.level().noCollision(this.getBoundingBox().move(this.getDeltaMovement()));
124
				if (nextColliding) {
125
					this.moveTowardsClosestSpace(this.getX(), (this.getBoundingBox().minY + this.getBoundingBox().maxY) / 2.0, this.getZ());
126
					this.needsSync = true;
127
				}
128
			}
129
130
			double fallSpeed = this.getDeltaMovement().y;
131
			this.move(MoverType.SELF, this.getDeltaMovement());
132
			this.applyEffectsFromBlocks();
133
			float friction = this.getAirDrag();
134
			if (this.onGround()) {
135
				friction *= this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction();
136
			}
137
138
			this.setDeltaMovement(this.getDeltaMovement().scale(friction));
139
			if (this.verticalCollisionBelow && fallSpeed < -this.getGravity()) {
140
				this.setDeltaMovement(new Vec3(this.getDeltaMovement().x, -fallSpeed * 0.4, this.getDeltaMovement().z));
141
			}
142
143
			this.age++;
144
			if (this.age >= 6000) {
145
				this.discard();
146
			}
147
		}
148
	}
149
150
	@Override
151
	protected float getAirDrag() {
152
		return 0.98F;
153
	}
154
155
	private void followNearbyPlayer() {
156
		if (this.followingPlayer == null || this.followingPlayer.isSpectator() || this.followingPlayer.distanceToSqr(this) > 64.0) {
157
			Player nearestPlayer = this.level().getNearestPlayer(this, 8.0);
158
			if (nearestPlayer != null && !nearestPlayer.isSpectator() && !nearestPlayer.isDeadOrDying()) {
159
				this.followingPlayer = nearestPlayer;
160
			} else {
161
				this.followingPlayer = null;
162
			}
163
		}
164
165
		if (this.followingPlayer != null) {
166
			Vec3 delta = new Vec3(
167
				this.followingPlayer.getX() - this.getX(),
168
				this.followingPlayer.getY() + this.followingPlayer.getEyeHeight() / 2.0 - this.getY(),
169
				this.followingPlayer.getZ() - this.getZ()
170
			);
171
			double length = delta.lengthSqr();
172
			double power = 1.0 - Math.sqrt(length) / 8.0;
173
			this.setDeltaMovement(this.getDeltaMovement().add(delta.normalize().scale(power * power * 0.1)));
174
		}
175
	}
176
177
	@Override
178
	public BlockPos getBlockPosBelowThatAffectsMyMovement() {
179
		return this.getOnPos(0.999999F);
180
	}
181
182
	private void scanForMerges() {
183
		if (this.level() instanceof ServerLevel) {
184
			for (ExperienceOrb orb : this.level().getEntities(EntityTypeTest.forClass(ExperienceOrb.class), this.getBoundingBox().inflate(0.5), this::canMerge)) {
185
				this.merge(orb);
186
			}
187
		}
188
	}
189
190
	public static void award(final ServerLevel level, final Vec3 pos, final int amount) {
191
		awardWithDirection(level, pos, Vec3.ZERO, amount);
192
	}
193
194
	public static void awardWithDirection(final ServerLevel level, final Vec3 pos, final Vec3 roughDirection, int amount) {
195
		while (amount > 0) {
196
			int newCount = getExperienceValue(amount);
197
			amount -= newCount;
198
			if (!tryMergeToExisting(level, pos, newCount)) {
199
				level.addFreshEntity(new ExperienceOrb(level, pos, roughDirection, newCount));
200
			}
201
		}
202
	}
203
204
	private static boolean tryMergeToExisting(final ServerLevel level, final Vec3 pos, final int value) {
205
		AABB box = AABB.ofSize(pos, 1.0, 1.0, 1.0);
206
		int id = level.getRandom().nextInt(40);
207
		List<ExperienceOrb> orbs = level.getEntities(EntityTypeTest.forClass(ExperienceOrb.class), box, orbx -> canMerge(orbx, id, value));
208
		if (!orbs.isEmpty()) {
209
			ExperienceOrb orb = orbs.get(0);
210
			orb.count++;
211
			orb.age = 0;
212
			return true;
213
		} else {
214
			return false;
215
		}
216
	}
217
218
	private boolean canMerge(final ExperienceOrb orb) {
219
		return orb != this && canMerge(orb, this.getId(), this.getValue());
220
	}
221
222
	private static boolean canMerge(final ExperienceOrb orb, final int id, final int value) {
223
		return !orb.isRemoved() && (orb.getId() - id) % 40 == 0 && orb.getValue() == value;
224
	}
225
226
	private void merge(final ExperienceOrb orb) {
227
		this.count = this.count + orb.count;
228
		this.age = Math.min(this.age, orb.age);
229
		orb.discard();
230
	}
231
232
	private void setUnderwaterMovement() {
233
		Vec3 movement = this.getDeltaMovement();
234
		this.setDeltaMovement(movement.x * 0.99F, Math.min(movement.y + 5.0E-4F, 0.06F), movement.z * 0.99F);
235
	}
236
237
	@Override
238
	protected void doWaterSplashEffect() {
239
	}
240
241
	@Override
242
	public final boolean hurtClient(final DamageSource source) {
243
		return !this.isInvulnerableToBase(source);
244
	}
245
246
	@Override
247
	public final boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage) {
248
		if (this.isInvulnerableToBase(source)) {
249
			return false;
250
		}
251
252
		this.markHurt();
253
		this.health = (int)(this.health - damage);
254
		if (this.health <= 0) {
255
			this.discard();
256
		}
257
258
		return true;
259
	}
260
261
	@Override
262
	protected void addAdditionalSaveData(final ValueOutput output) {
263
		output.putShort("Health", (short)this.health);
264
		output.putShort("Age", (short)this.age);
265
		output.putShort("Value", (short)this.getValue());
266
		output.putInt("Count", this.count);
267
	}
268
269
	@Override
270
	protected void readAdditionalSaveData(final ValueInput input) {
271
		this.health = input.getShortOr("Health", (short)5);
272
		this.age = input.getShortOr("Age", (short)0);
273
		this.setValue(input.getShortOr("Value", (short)0));
274
		this.count = input.read("Count", ExtraCodecs.POSITIVE_INT).orElse(1);
275
	}
276
277
	@Override
278
	public void playerTouch(final Player player) {
279
		if (player instanceof ServerPlayer serverPlayer) {
280
			if (player.takeXpDelay == 0) {
281
				player.takeXpDelay = 2;
282
				player.take(this, 1);
283
				int remaining = this.repairPlayerItems(serverPlayer, this.getValue());
284
				if (remaining > 0) {
285
					player.giveExperiencePoints(remaining);
286
				}
287
288
				this.count--;
289
				if (this.count == 0) {
290
					this.discard();
291
				}
292
			}
293
		}
294
	}
295
296
	private int repairPlayerItems(final ServerPlayer player, final int amount) {
297
		Optional<EnchantedItemInUse> selected = EnchantmentHelper.getRandomItemWith(EnchantmentEffectComponents.REPAIR_WITH_XP, player, ItemStack::isDamaged);
298
		if (selected.isPresent()) {
299
			ItemStack itemStack = selected.get().itemStack();
300
			int toRepairFromXpAmount = EnchantmentHelper.modifyDurabilityToRepairFromXp(player.level(), itemStack, amount);
301
			int repair = Math.min(toRepairFromXpAmount, itemStack.getDamageValue());
302
			itemStack.setDamageValue(itemStack.getDamageValue() - repair);
303
			if (repair > 0) {
304
				int remaining = amount - repair * amount / toRepairFromXpAmount;
305
				if (remaining > 0) {
306
					return this.repairPlayerItems(player, remaining);
307
				}
308
			}
309
310
			return 0;
311
		} else {
312
			return amount;
313
		}
314
	}
315
316
	public int getValue() {
317
		return this.entityData.get(DATA_VALUE);
318
	}
319
320
	private void setValue(final int value) {
321
		this.entityData.set(DATA_VALUE, value);
322
	}
323
324
	public int getIcon() {
325
		int value = this.getValue();
326
		if (value >= 2477) {
327
			return 10;
328
		} else if (value >= 1237) {
329
			return 9;
330
		} else if (value >= 617) {
331
			return 8;
332
		} else if (value >= 307) {
333
			return 7;
334
		} else if (value >= 149) {
335
			return 6;
336
		} else if (value >= 73) {
337
			return 5;
338
		} else if (value >= 37) {
339
			return 4;
340
		} else if (value >= 17) {
341
			return 3;
342
		} else if (value >= 7) {
343
			return 2;
344
		} else {
345
			return value >= 3 ? 1 : 0;
346
		}
347
	}
348
349
	public static int getExperienceValue(final int maxValue) {
350
		if (maxValue >= 2477) {
351
			return 2477;
352
		} else if (maxValue >= 1237) {
353
			return 1237;
354
		} else if (maxValue >= 617) {
355
			return 617;
356
		} else if (maxValue >= 307) {
357
			return 307;
358
		} else if (maxValue >= 149) {
359
			return 149;
360
		} else if (maxValue >= 73) {
361
			return 73;
362
		} else if (maxValue >= 37) {
363
			return 37;
364
		} else if (maxValue >= 17) {
365
			return 17;
366
		} else if (maxValue >= 7) {
367
			return 7;
368
		} else {
369
			return maxValue >= 3 ? 3 : 1;
370
		}
371
	}
372
373
	@Override
374
	public boolean isAttackable() {
375
		return false;
376
	}
377
378
	@Override
379
	public SoundSource getSoundSource() {
380
		return SoundSource.AMBIENT;
381
	}
382
383
	@Override
384
	protected InterpolationHandler createInterpolationHandler() {
385
		return LinearInterpolationHandler.create(this);
386
	}
387
388
	@Override
389
	public MoveSimulationType getMoveSimulationType() {
390
		return MoveSimulationType.SERVER_AND_CLIENT;
391
	}
392
}
393

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