FallingBlockEntity .java

net.minecraft.world.entity.item.FallingBlockEntity (class, 371 lines): members: forceTickAfterTeleportToDuplicate, DEFAULT_FALL_DAMAGE_PER_DISTANCE, fall.

net.minecraft.world.entity.itemclass371 linescommonextends Entity14.4 KB

API Surface (23)

FallingBlockEntity fall(final Level level, final BlockPos pos, final BlockState state)
boolean isAttackable()
boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage)
void setStartPos(final BlockPos pos)
BlockPos getStartPos()
Entity.MovementEmission getMovementEmission()
void defineSynchedData(final SynchedEntityData.Builder entityData)
boolean isPickable()
double getDefaultGravity()
void tick()
void callOnBrokenAfterFall(final Block block, final BlockPos pos)
boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource)
void addAdditionalSaveData(final ValueOutput output)
void readAdditionalSaveData(final ValueInput input)
void setHurtsEntities(final float damagePerDistance, final int damageMax)
void disableDrop()
boolean displayFireAnimation()
void fillCrashReportCategory(final CrashReportCategory category)
BlockState getBlockState()
Component getTypeName()
Packet<ClientGamePacketListener> getAddEntityPacket(final ServerEntity serverEntity)
void recreateFromPacket(final ClientboundAddEntityPacket packet)
MoveSimulationType getMoveSimulationType()

Fields & Constants (17)

LOGGER
DEFAULT_BLOCK_STATE
DEFAULT_TIME
DEFAULT_FALL_DAMAGE_PER_DISTANCE
DEFAULT_MAX_FALL_DAMAGE
DEFAULT_DROP_ITEM
DEFAULT_CANCEL_DROP
DATA_START_POS
blockState
time
dropItem
cancelDrop
hurtEntities
fallDamageMax
fallDamagePerDistance
blockData
forceTickAfterTeleportToDuplicate

String literals (11)

"Failed to load block entity from falling block"
"BlockState"
"Time"
"DropItem"
"HurtEntities"
"FallHurtAmount"
"FallHurtMax"
"TileEntityData"
"CancelDrop"
"Immitating BlockState"
"entity.minecraft.falling_block_type"

Code Graph: Dependencies (52)

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

Full Source

FallingBlockEntity.java371 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.item;
2
3
import com.mojang.logging.LogUtils;
4
import java.util.function.Predicate;
5
import net.minecraft.CrashReportCategory;
6
import net.minecraft.core.BlockPos;
7
import net.minecraft.core.Direction;
8
import net.minecraft.core.RegistryAccess;
9
import net.minecraft.nbt.CompoundTag;
10
import net.minecraft.network.chat.Component;
11
import net.minecraft.network.protocol.Packet;
12
import net.minecraft.network.protocol.game.ClientGamePacketListener;
13
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
14
import net.minecraft.network.protocol.game.ClientboundAddTransientBlockPacket;
15
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
16
import net.minecraft.network.syncher.EntityDataAccessor;
17
import net.minecraft.network.syncher.EntityDataSerializers;
18
import net.minecraft.network.syncher.SynchedEntityData;
19
import net.minecraft.resources.ResourceKey;
20
import net.minecraft.server.level.ServerEntity;
21
import net.minecraft.server.level.ServerLevel;
22
import net.minecraft.tags.BlockTags;
23
import net.minecraft.tags.FluidTags;
24
import net.minecraft.util.Mth;
25
import net.minecraft.util.ProblemReporter;
26
import net.minecraft.world.damagesource.DamageSource;
27
import net.minecraft.world.entity.Entity;
28
import net.minecraft.world.entity.EntitySelector;
29
import net.minecraft.world.entity.EntityType;
30
import net.minecraft.world.entity.EntityTypes;
31
import net.minecraft.world.entity.MoveSimulationType;
32
import net.minecraft.world.entity.MoverType;
33
import net.minecraft.world.item.ItemStack;
34
import net.minecraft.world.item.context.DirectionalPlaceContext;
35
import net.minecraft.world.level.ClipContext;
36
import net.minecraft.world.level.Level;
37
import net.minecraft.world.level.block.AnvilBlock;
38
import net.minecraft.world.level.block.Block;
39
import net.minecraft.world.level.block.Blocks;
40
import net.minecraft.world.level.block.ConcretePowderBlock;
41
import net.minecraft.world.level.block.Fallable;
42
import net.minecraft.world.level.block.FallingBlock;
43
import net.minecraft.world.level.block.entity.BlockEntity;
44
import net.minecraft.world.level.block.state.BlockState;
45
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
46
import net.minecraft.world.level.gamerules.GameRules;
47
import net.minecraft.world.level.material.Fluids;
48
import net.minecraft.world.level.portal.TeleportTransition;
49
import net.minecraft.world.level.storage.TagValueInput;
50
import net.minecraft.world.level.storage.TagValueOutput;
51
import net.minecraft.world.level.storage.ValueInput;
52
import net.minecraft.world.level.storage.ValueOutput;
53
import net.minecraft.world.phys.BlockHitResult;
54
import net.minecraft.world.phys.HitResult;
55
import net.minecraft.world.phys.Vec3;
56
import org.jspecify.annotations.Nullable;
57
import org.slf4j.Logger;
58
59
public class FallingBlockEntity extends Entity {
60
	private static final Logger LOGGER = LogUtils.getLogger();
61
	private static final BlockState DEFAULT_BLOCK_STATE = Blocks.SAND.defaultBlockState();
62
	private static final int DEFAULT_TIME = 0;
63
	private static final float DEFAULT_FALL_DAMAGE_PER_DISTANCE = 0.0F;
64
	private static final int DEFAULT_MAX_FALL_DAMAGE = 40;
65
	private static final boolean DEFAULT_DROP_ITEM = true;
66
	private static final boolean DEFAULT_CANCEL_DROP = false;
67
	private BlockState blockState = DEFAULT_BLOCK_STATE;
68
	public int time = 0;
69
	public boolean dropItem = true;
70
	private boolean cancelDrop = false;
71
	private boolean hurtEntities;
72
	private int fallDamageMax = 40;
73
	private float fallDamagePerDistance = 0.0F;
74
	public @Nullable CompoundTag blockData;
75
	public boolean forceTickAfterTeleportToDuplicate;
76
	protected static final EntityDataAccessor<BlockPos> DATA_START_POS = SynchedEntityData.defineId(FallingBlockEntity.class, EntityDataSerializers.BLOCK_POS);
77
78
	public FallingBlockEntity(final EntityType<? extends FallingBlockEntity> type, final Level level) {
79
		super(type, level);
80
	}
81
82
	private FallingBlockEntity(final Level level, final double x, final double y, final double z, final BlockState blockState) {
83
		this(EntityTypes.FALLING_BLOCK, level);
84
		this.blockState = blockState;
85
		this.blocksBuilding = true;
86
		this.setPos(x, y, z);
87
		this.setDeltaMovement(Vec3.ZERO);
88
		this.xo = x;
89
		this.yo = y;
90
		this.zo = z;
91
		this.setStartPos(this.blockPosition());
92
	}
93
94
	public static FallingBlockEntity fall(final Level level, final BlockPos pos, final BlockState state) {
95
		FallingBlockEntity entity = new FallingBlockEntity(
96
			level,
97
			pos.getX() + 0.5,
98
			pos.getY(),
99
			pos.getZ() + 0.5,
100
			state.hasProperty(BlockStateProperties.WATERLOGGED) ? state.setValue(BlockStateProperties.WATERLOGGED, false) : state
101
		);
102
		level.setBlockAndUpdate(pos, state.getFluidState().createLegacyBlock());
103
		level.addFreshEntity(entity);
104
		return entity;
105
	}
106
107
	@Override
108
	public boolean isAttackable() {
109
		return false;
110
	}
111
112
	@Override
113
	public final boolean hurtServer(final ServerLevel level, final DamageSource source, final float damage) {
114
		if (!this.isInvulnerableToBase(source)) {
115
			this.markHurt();
116
		}
117
118
		return false;
119
	}
120
121
	public void setStartPos(final BlockPos pos) {
122
		this.entityData.set(DATA_START_POS, pos);
123
	}
124
125
	public BlockPos getStartPos() {
126
		return this.entityData.get(DATA_START_POS);
127
	}
128
129
	@Override
130
	protected Entity.MovementEmission getMovementEmission() {
131
		return Entity.MovementEmission.NONE;
132
	}
133
134
	@Override
135
	protected void defineSynchedData(final SynchedEntityData.Builder entityData) {
136
		entityData.define(DATA_START_POS, BlockPos.ZERO);
137
	}
138
139
	@Override
140
	public boolean isPickable() {
141
		return !this.isRemoved();
142
	}
143
144
	@Override
145
	protected double getDefaultGravity() {
146
		return 0.04;
147
	}
148
149
	@Override
150
	public void tick() {
151
		if (this.blockState.isAir()) {
152
			this.discard();
153
		} else {
154
			Block block = this.blockState.getBlock();
155
			this.time++;
156
			this.applyGravity();
157
			this.move(MoverType.SELF, this.getDeltaMovement());
158
			this.applyEffectsFromBlocks();
159
			this.handlePortal();
160
			if (this.level() instanceof ServerLevel serverLevel && (this.isAlive() || this.forceTickAfterTeleportToDuplicate)) {
161
				BlockPos pos = this.blockPosition();
162
				boolean isConcrete = this.blockState.getBlock() instanceof ConcretePowderBlock;
163
				boolean isStuckInWater = isConcrete && this.level().getFluidState(pos).is(FluidTags.WATER);
164
				double moveVec = this.getDeltaMovement().lengthSqr();
165
				if (isConcrete && moveVec > 1.0) {
166
					BlockHitResult clip = this.level()
167
						.clip(new ClipContext(new Vec3(this.xo, this.yo, this.zo), this.position(), ClipContext.Block.COLLIDER, ClipContext.Fluid.SOURCE_ONLY, this));
168
					if (clip.getType() != HitResult.Type.MISS && this.level().getFluidState(clip.getBlockPos()).is(FluidTags.WATER)) {
169
						pos = clip.getBlockPos();
170
						isStuckInWater = true;
171
					}
172
				}
173
174
				if (!this.onGround() && !isStuckInWater) {
175
					if (this.time > 100 && (pos.getY() <= this.level().getMinY() || pos.getY() > this.level().getMaxY()) || this.time > 600) {
176
						if (this.dropItem && serverLevel.getGameRules().get(GameRules.ENTITY_DROPS)) {
177
							this.spawnAtLocation(serverLevel, block);
178
						}
179
180
						this.discard();
181
					}
182
				} else {
183
					BlockState currentState = this.level().getBlockState(pos);
184
					this.setDeltaMovement(this.getDeltaMovement().multiply(0.7, -0.5, 0.7));
185
					if (!currentState.is(Blocks.MOVING_PISTON)) {
186
						if (!this.cancelDrop) {
187
							boolean mayReplace = currentState.canBeReplaced(new DirectionalPlaceContext(this.level(), pos, Direction.DOWN, ItemStack.EMPTY, Direction.UP));
188
							boolean wouldContinueFalling = FallingBlock.isFree(this.level().getBlockState(pos.below())) && (!isConcrete || !isStuckInWater);
189
							boolean wouldSurvive = this.blockState.canSurvive(this.level(), pos) && !wouldContinueFalling;
190
							if (mayReplace && wouldSurvive) {
191
								if (this.blockState.hasProperty(BlockStateProperties.WATERLOGGED) && this.level().getFluidState(pos).is(Fluids.WATER)) {
192
									this.blockState = this.blockState.setValue(BlockStateProperties.WATERLOGGED, true);
193
								}
194
195
								if (this.level().setBlockAndUpdate(pos, this.blockState)) {
196
									serverLevel.getChunkSource().chunkMap.sendToTrackingPlayers(this, new ClientboundBlockUpdatePacket(pos, this.level().getBlockState(pos)));
197
									serverLevel.getChunkSource().chunkMap.sendToTrackingPlayers(this, new ClientboundAddTransientBlockPacket(pos, this.level().getBlockState(pos)));
198
									this.discard();
199
									if (block instanceof Fallable fallable) {
200
										fallable.onLand(this.level(), pos, this.blockState, currentState, this);
201
									}
202
203
									if (this.blockData != null && this.blockState.hasBlockEntity()) {
204
										BlockEntity blockEntity = this.level().getBlockEntity(pos);
205
										if (blockEntity != null) {
206
											try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(blockEntity.problemPath(), LOGGER)) {
207
												RegistryAccess registryAccess = this.level().registryAccess();
208
												TagValueOutput output = TagValueOutput.createWithContext(reporter, registryAccess);
209
												blockEntity.saveWithoutMetadata(output);
210
												CompoundTag merged = output.buildResult();
211
												this.blockData.forEach((name, tag) -> merged.put(name, tag.copy()));
212
												blockEntity.loadWithComponents(TagValueInput.create(reporter, registryAccess, merged));
213
											} catch (Exception e) {
214
												LOGGER.error("Failed to load block entity from falling block", e);
215
											}
216
217
											blockEntity.setChanged();
218
										}
219
									}
220
								} else if (this.dropItem && serverLevel.getGameRules().get(GameRules.ENTITY_DROPS)) {
221
									this.discard();
222
									this.callOnBrokenAfterFall(block, pos);
223
									this.spawnAtLocation(serverLevel, block);
224
								}
225
							} else {
226
								this.discard();
227
								if (this.dropItem && serverLevel.getGameRules().get(GameRules.ENTITY_DROPS)) {
228
									this.callOnBrokenAfterFall(block, pos);
229
									this.spawnAtLocation(serverLevel, block);
230
								}
231
							}
232
						} else {
233
							this.discard();
234
							this.callOnBrokenAfterFall(block, pos);
235
						}
236
					}
237
				}
238
			}
239
240
			this.setDeltaMovement(this.getDeltaMovement().scale(this.getAirDrag()));
241
			this.setRequiresPrecisePosition(this.horizontalCollision || this.verticalCollision);
242
		}
243
	}
244
245
	public void callOnBrokenAfterFall(final Block block, final BlockPos pos) {
246
		if (block instanceof Fallable fallable) {
247
			fallable.onBrokenAfterFall(this.level(), pos, this);
248
		}
249
	}
250
251
	@Override
252
	public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) {
253
		if (!this.hurtEntities) {
254
			return false;
255
		}
256
257
		int fallDistanceInt = Mth.ceil(fallDistance - 1.0);
258
		if (fallDistanceInt < 0) {
259
			return false;
260
		}
261
262
		Predicate<Entity> entitySelector = EntitySelector.NO_CREATIVE_OR_SPECTATOR.and(EntitySelector.LIVING_ENTITY_STILL_ALIVE);
263
		DamageSource actualDamageSource = this.blockState.getBlock() instanceof Fallable fallable
264
			? fallable.getFallDamageSource(this)
265
			: this.damageSources().fallingBlock(this);
266
		float damage = Math.min(Mth.floor(fallDistanceInt * this.fallDamagePerDistance), this.fallDamageMax);
267
		this.level().getEntities(this, this.getBoundingBox(), entitySelector).forEach(entity -> entity.hurt(actualDamageSource, damage));
268
		boolean isAnvil = this.blockState.is(BlockTags.ANVIL);
269
		if (isAnvil && damage > 0.0F && this.random.nextFloat() < 0.05F + fallDistanceInt * 0.05F) {
270
			BlockState newBlockState = AnvilBlock.damage(this.blockState);
271
			if (newBlockState == null) {
272
				this.cancelDrop = true;
273
			} else {
274
				this.blockState = newBlockState;
275
			}
276
		}
277
278
		return false;
279
	}
280
281
	@Override
282
	protected void addAdditionalSaveData(final ValueOutput output) {
283
		output.store("BlockState", BlockState.CODEC, this.blockState);
284
		output.putInt("Time", this.time);
285
		output.putBoolean("DropItem", this.dropItem);
286
		output.putBoolean("HurtEntities", this.hurtEntities);
287
		output.putFloat("FallHurtAmount", this.fallDamagePerDistance);
288
		output.putInt("FallHurtMax", this.fallDamageMax);
289
		if (this.blockData != null) {
290
			output.store("TileEntityData", CompoundTag.CODEC, this.blockData);
291
		}
292
293
		output.putBoolean("CancelDrop", this.cancelDrop);
294
	}
295
296
	@Override
297
	protected void readAdditionalSaveData(final ValueInput input) {
298
		this.blockState = input.read("BlockState", BlockState.CODEC).orElse(DEFAULT_BLOCK_STATE);
299
		this.time = input.getIntOr("Time", 0);
300
		boolean defaultHurtEntities = this.blockState.is(BlockTags.ANVIL);
301
		this.hurtEntities = input.getBooleanOr("HurtEntities", defaultHurtEntities);
302
		this.fallDamagePerDistance = input.getFloatOr("FallHurtAmount", 0.0F);
303
		this.fallDamageMax = input.getIntOr("FallHurtMax", 40);
304
		this.dropItem = input.getBooleanOr("DropItem", true);
305
		this.blockData = input.read("TileEntityData", CompoundTag.CODEC).orElse(null);
306
		this.cancelDrop = input.getBooleanOr("CancelDrop", false);
307
	}
308
309
	public void setHurtsEntities(final float damagePerDistance, final int damageMax) {
310
		this.hurtEntities = true;
311
		this.fallDamagePerDistance = damagePerDistance;
312
		this.fallDamageMax = damageMax;
313
	}
314
315
	public void disableDrop() {
316
		this.cancelDrop = true;
317
	}
318
319
	@Override
320
	public boolean displayFireAnimation() {
321
		return false;
322
	}
323
324
	@Override
325
	public void fillCrashReportCategory(final CrashReportCategory category) {
326
		super.fillCrashReportCategory(category);
327
		category.setDetail("Immitating BlockState", this.blockState.toString());
328
	}
329
330
	public BlockState getBlockState() {
331
		return this.blockState;
332
	}
333
334
	@Override
335
	protected Component getTypeName() {
336
		return Component.translatable("entity.minecraft.falling_block_type", this.blockState.getBlock().getName());
337
	}
338
339
	@Override
340
	public Packet<ClientGamePacketListener> getAddEntityPacket(final ServerEntity serverEntity) {
341
		return new ClientboundAddEntityPacket(this, serverEntity, Block.getId(this.getBlockState()));
342
	}
343
344
	@Override
345
	public void recreateFromPacket(final ClientboundAddEntityPacket packet) {
346
		super.recreateFromPacket(packet);
347
		this.blockState = Block.stateById(packet.getData());
348
		this.blocksBuilding = true;
349
		double x = packet.getX();
350
		double y = packet.getY();
351
		double z = packet.getZ();
352
		this.setPos(x, y, z);
353
		this.setStartPos(this.blockPosition());
354
	}
355
356
	@Override
357
	public @Nullable Entity teleport(final TeleportTransition transition) {
358
		ResourceKey<Level> newDimension = transition.newLevel().dimension();
359
		ResourceKey<Level> oldDimension = this.level().dimension();
360
		boolean fromOrToEnd = (oldDimension == Level.END || newDimension == Level.END) && oldDimension != newDimension;
361
		Entity newEntity = super.teleport(transition);
362
		this.forceTickAfterTeleportToDuplicate = newEntity != null && fromOrToEnd;
363
		return newEntity;
364
	}
365
366
	@Override
367
	public MoveSimulationType getMoveSimulationType() {
368
		return MoveSimulationType.SERVER_AND_CLIENT;
369
	}
370
}
371

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