HopperBlockEntity .java

net.minecraft.world.level.block.entity.HopperBlockEntity (class, 457 lines): members: HOPPER_CONTAINER_SIZE, getItemsAtAndAbove, NO_COOLDOWN_TIME, addItem.

net.minecraft.world.level.block.entityclass457 linescommonextends RandomizableContainerBlockEntity14.4 KB

Implements

API Surface (20)

void loadAdditional(final ValueInput input)
void saveAdditional(final ValueOutput output)
int getContainerSize()
ItemStack removeItem(final int slot, final int count)
void setItem(final int slot, final ItemStack itemStack)
void setBlockState(final BlockState blockState)
Component getDefaultName()
void pushItemsTick(final Level level, final BlockPos pos, final BlockState state, final HopperBlockEntity entity)
boolean suckInItems(final Level level, final Hopper hopper)
boolean addItem(final Container container, final ItemEntity entity)
ItemStack addItem(final @Nullable Container from, final Container container, ItemStack itemStack, final @Nullable Direction direction)
List<ItemEntity> getItemsAtAndAbove(final Level level, final Hopper hopper)
double getLevelX()
double getLevelY()
double getLevelZ()
boolean isGridAligned()
NonNullList<ItemStack> getItems()
void setItems(final NonNullList<ItemStack> items)
void entityInside(final Level level, final BlockPos pos, final BlockState blockState, final Entity entity, final HopperBlockEntity hopper)
AbstractContainerMenu createMenu(final int containerId, final Inventory inventory)

Fields & Constants (12)

MOVE_ITEM_SPEED
HOPPER_CONTAINER_SIZE
CACHED_SLOTS
NO_COOLDOWN_TIME
DEFAULT_NAME
items
cooldownTime
tickedGameTime
facing
entity
slot
y

String literals (2)

"container.hopper"
"TransferCooldown"

Full Source

HopperBlockEntity.java457 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.block.entity;
2
3
import java.util.List;
4
import java.util.function.BooleanSupplier;
5
import net.minecraft.core.BlockPos;
6
import net.minecraft.core.Direction;
7
import net.minecraft.core.NonNullList;
8
import net.minecraft.network.chat.Component;
9
import net.minecraft.tags.BlockTags;
10
import net.minecraft.world.Container;
11
import net.minecraft.world.ContainerHelper;
12
import net.minecraft.world.WorldlyContainer;
13
import net.minecraft.world.WorldlyContainerHolder;
14
import net.minecraft.world.entity.Entity;
15
import net.minecraft.world.entity.EntitySelector;
16
import net.minecraft.world.entity.item.ItemEntity;
17
import net.minecraft.world.entity.player.Inventory;
18
import net.minecraft.world.inventory.AbstractContainerMenu;
19
import net.minecraft.world.inventory.HopperMenu;
20
import net.minecraft.world.item.ItemStack;
21
import net.minecraft.world.level.Level;
22
import net.minecraft.world.level.block.Block;
23
import net.minecraft.world.level.block.ChestBlock;
24
import net.minecraft.world.level.block.HopperBlock;
25
import net.minecraft.world.level.block.state.BlockState;
26
import net.minecraft.world.level.storage.ValueInput;
27
import net.minecraft.world.level.storage.ValueOutput;
28
import net.minecraft.world.phys.AABB;
29
import org.jspecify.annotations.Nullable;
30
31
public class HopperBlockEntity extends RandomizableContainerBlockEntity implements Hopper {
32
	public static final int MOVE_ITEM_SPEED = 8;
33
	public static final int HOPPER_CONTAINER_SIZE = 5;
34
	private static final int[][] CACHED_SLOTS = new int[54][];
35
	private static final int NO_COOLDOWN_TIME = -1;
36
	private static final Component DEFAULT_NAME = Component.translatable("container.hopper");
37
	private NonNullList<ItemStack> items = NonNullList.withSize(5, ItemStack.EMPTY);
38
	private int cooldownTime = -1;
39
	private long tickedGameTime;
40
	private Direction facing;
41
42
	public HopperBlockEntity(final BlockPos worldPosition, final BlockState blockState) {
43
		super(BlockEntityTypes.HOPPER, worldPosition, blockState);
44
		this.facing = blockState.getValue(HopperBlock.FACING);
45
	}
46
47
	@Override
48
	protected void loadAdditional(final ValueInput input) {
49
		super.loadAdditional(input);
50
		this.items = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY);
51
		if (!this.tryLoadLootTable(input)) {
52
			ContainerHelper.loadAllItems(input, this.items);
53
		}
54
55
		this.cooldownTime = input.getIntOr("TransferCooldown", -1);
56
	}
57
58
	@Override
59
	protected void saveAdditional(final ValueOutput output) {
60
		super.saveAdditional(output);
61
		if (!this.trySaveLootTable(output)) {
62
			ContainerHelper.saveAllItems(output, this.items);
63
		}
64
65
		output.putInt("TransferCooldown", this.cooldownTime);
66
	}
67
68
	@Override
69
	public int getContainerSize() {
70
		return this.items.size();
71
	}
72
73
	@Override
74
	public ItemStack removeItem(final int slot, final int count) {
75
		this.unpackLootTable(null);
76
		return ContainerHelper.removeItem(this.getItems(), slot, count);
77
	}
78
79
	@Override
80
	public void setItem(final int slot, final ItemStack itemStack) {
81
		this.unpackLootTable(null);
82
		this.getItems().set(slot, itemStack);
83
		itemStack.limitSize(this.getMaxStackSize(itemStack));
84
	}
85
86
	@Override
87
	public void setBlockState(final BlockState blockState) {
88
		super.setBlockState(blockState);
89
		this.facing = blockState.getValue(HopperBlock.FACING);
90
	}
91
92
	@Override
93
	protected Component getDefaultName() {
94
		return DEFAULT_NAME;
95
	}
96
97
	public static void pushItemsTick(final Level level, final BlockPos pos, final BlockState state, final HopperBlockEntity entity) {
98
		entity.cooldownTime--;
99
		entity.tickedGameTime = level.getGameTime();
100
		if (!entity.isOnCooldown()) {
101
			entity.setCooldown(0);
102
			tryMoveItems(level, pos, state, entity, () -> suckInItems(level, entity));
103
		}
104
	}
105
106
	private static boolean tryMoveItems(
107
		final Level level, final BlockPos pos, final BlockState state, final HopperBlockEntity entity, final BooleanSupplier action
108
	) {
109
		if (level.isClientSide()) {
110
			return false;
111
		}
112
113
		if (!entity.isOnCooldown() && state.getValue(HopperBlock.ENABLED)) {
114
			boolean changed = false;
115
			if (!entity.isEmpty()) {
116
				changed = ejectItems(level, pos, entity);
117
			}
118
119
			if (!entity.inventoryFull()) {
120
				changed |= action.getAsBoolean();
121
			}
122
123
			if (changed) {
124
				entity.setCooldown(8);
125
				setChanged(level, pos, state);
126
				return true;
127
			}
128
		}
129
130
		return false;
131
	}
132
133
	private boolean inventoryFull() {
134
		for (ItemStack itemStack : this.items) {
135
			if (itemStack.isEmpty() || itemStack.getCount() != itemStack.getMaxStackSize()) {
136
				return false;
137
			}
138
		}
139
140
		return true;
141
	}
142
143
	private static boolean ejectItems(final Level level, final BlockPos blockPos, final HopperBlockEntity self) {
144
		Container container = getAttachedContainer(level, blockPos, self);
145
		if (container == null) {
146
			return false;
147
		}
148
149
		Direction direction = self.facing.getOpposite();
150
		if (isFullContainer(container, direction)) {
151
			return false;
152
		}
153
154
		for (int slot = 0; slot < self.getContainerSize(); slot++) {
155
			ItemStack itemStack = self.getItem(slot);
156
			if (!itemStack.isEmpty()) {
157
				int originalCount = itemStack.getCount();
158
				ItemStack result = addItem(self, container, self.removeItem(slot, 1), direction);
159
				if (result.isEmpty()) {
160
					container.setChanged();
161
					return true;
162
				}
163
164
				itemStack.setCount(originalCount);
165
				if (originalCount == 1) {
166
					self.setItem(slot, itemStack);
167
				}
168
			}
169
		}
170
171
		return false;
172
	}
173
174
	private static int[] getSlots(final Container container, final Direction direction) {
175
		if (container instanceof WorldlyContainer worldlyContainer) {
176
			return worldlyContainer.getSlotsForFace(direction);
177
		} else {
178
			int containerSize = container.getContainerSize();
179
			if (containerSize < CACHED_SLOTS.length) {
180
				int[] cachedSlots = CACHED_SLOTS[containerSize];
181
				if (cachedSlots != null) {
182
					return cachedSlots;
183
				}
184
185
				int[] slots = createFlatSlots(containerSize);
186
				CACHED_SLOTS[containerSize] = slots;
187
				return slots;
188
			} else {
189
				return createFlatSlots(containerSize);
190
			}
191
		}
192
	}
193
194
	private static int[] createFlatSlots(final int containerSize) {
195
		int[] slots = new int[containerSize];
196
		int i = 0;
197
198
		while (i < slots.length) {
199
			slots[i] = i++;
200
		}
201
202
		return slots;
203
	}
204
205
	private static boolean isFullContainer(final Container container, final Direction direction) {
206
		int[] slots = getSlots(container, direction);
207
208
		for (int slot : slots) {
209
			ItemStack itemStack = container.getItem(slot);
210
			if (itemStack.getCount() < itemStack.getMaxStackSize()) {
211
				return false;
212
			}
213
		}
214
215
		return true;
216
	}
217
218
	public static boolean suckInItems(final Level level, final Hopper hopper) {
219
		BlockPos blockPos = BlockPos.containing(hopper.getLevelX(), hopper.getLevelY() + 1.0, hopper.getLevelZ());
220
		BlockState blockState = level.getBlockState(blockPos);
221
		Container container = getSourceContainer(level, hopper, blockPos, blockState);
222
		if (container != null) {
223
			Direction direction = Direction.DOWN;
224
225
			for (int slot : getSlots(container, direction)) {
226
				if (tryTakeInItemFromSlot(hopper, container, slot, direction)) {
227
					return true;
228
				}
229
			}
230
231
			return false;
232
		} else {
233
			boolean isBlocked = hopper.isGridAligned() && blockState.isCollisionShapeFullBlock(level, blockPos) && !blockState.is(BlockTags.DOES_NOT_BLOCK_HOPPERS);
234
			if (!isBlocked) {
235
				for (ItemEntity entity : getItemsAtAndAbove(level, hopper)) {
236
					if (addItem(hopper, entity)) {
237
						return true;
238
					}
239
				}
240
			}
241
242
			return false;
243
		}
244
	}
245
246
	private static boolean tryTakeInItemFromSlot(final Hopper hopper, final Container container, final int slot, final Direction direction) {
247
		ItemStack itemStack = container.getItem(slot);
248
		if (!itemStack.isEmpty() && canTakeItemFromContainer(hopper, container, itemStack, slot, direction)) {
249
			int originalCount = itemStack.getCount();
250
			ItemStack result = addItem(container, hopper, container.removeItem(slot, 1), null);
251
			if (result.isEmpty()) {
252
				container.setChanged();
253
				return true;
254
			}
255
256
			itemStack.setCount(originalCount);
257
			if (originalCount == 1) {
258
				container.setItem(slot, itemStack);
259
			}
260
		}
261
262
		return false;
263
	}
264
265
	public static boolean addItem(final Container container, final ItemEntity entity) {
266
		boolean changed = false;
267
		ItemStack copy = entity.getItem().copy();
268
		ItemStack result = addItem(null, container, copy, null);
269
		if (result.isEmpty()) {
270
			changed = true;
271
			entity.setItem(ItemStack.EMPTY);
272
			entity.discard();
273
		} else {
274
			entity.setItem(result);
275
		}
276
277
		return changed;
278
	}
279
280
	public static ItemStack addItem(final @Nullable Container from, final Container container, ItemStack itemStack, final @Nullable Direction direction) {
281
		if (container instanceof WorldlyContainer worldly && direction != null) {
282
			int[] slots = worldly.getSlotsForFace(direction);
283
284
			for (int i = 0; i < slots.length && !itemStack.isEmpty(); i++) {
285
				itemStack = tryMoveInItem(from, container, itemStack, slots[i], direction);
286
			}
287
		} else {
288
			int size = container.getContainerSize();
289
290
			for (int i = 0; i < size && !itemStack.isEmpty(); i++) {
291
				itemStack = tryMoveInItem(from, container, itemStack, i, direction);
292
			}
293
		}
294
295
		return itemStack;
296
	}
297
298
	private static boolean canPlaceItemInContainer(final Container container, final ItemStack itemStack, final int slot, final @Nullable Direction direction) {
299
		return !container.canPlaceItem(slot, itemStack)
300
			? false
301
			: !(container instanceof WorldlyContainer worldly && !worldly.canPlaceItemThroughFace(slot, itemStack, direction));
302
	}
303
304
	private static boolean canTakeItemFromContainer(
305
		final Container into, final Container from, final ItemStack itemStack, final int slot, final Direction direction
306
	) {
307
		return !from.canTakeItem(into, slot, itemStack)
308
			? false
309
			: !(from instanceof WorldlyContainer worldly && !worldly.canTakeItemThroughFace(slot, itemStack, direction));
310
	}
311
312
	private static ItemStack tryMoveInItem(
313
		final @Nullable Container from, final Container container, ItemStack itemStack, final int slot, final @Nullable Direction direction
314
	) {
315
		ItemStack current = container.getItem(slot);
316
		if (canPlaceItemInContainer(container, itemStack, slot, direction)) {
317
			boolean success = false;
318
			boolean wasEmpty = container.isEmpty();
319
			if (current.isEmpty()) {
320
				container.setItem(slot, itemStack);
321
				itemStack = ItemStack.EMPTY;
322
				success = true;
323
			} else if (canMergeItems(current, itemStack)) {
324
				int space = itemStack.getMaxStackSize() - current.getCount();
325
				int count = Math.min(itemStack.getCount(), space);
326
				itemStack.shrink(count);
327
				current.grow(count);
328
				success = count > 0;
329
			}
330
331
			if (success) {
332
				if (wasEmpty && container instanceof HopperBlockEntity hopperBlockEntity && !hopperBlockEntity.isOnCustomCooldown()) {
333
					int skipTickCount = 0;
334
					if (from instanceof HopperBlockEntity fromHopper && hopperBlockEntity.tickedGameTime >= fromHopper.tickedGameTime) {
335
						skipTickCount = 1;
336
					}
337
338
					hopperBlockEntity.setCooldown(8 - skipTickCount);
339
				}
340
341
				container.setChanged();
342
			}
343
		}
344
345
		return itemStack;
346
	}
347
348
	private static @Nullable Container getAttachedContainer(final Level level, final BlockPos blockPos, final HopperBlockEntity self) {
349
		return getContainerAt(level, blockPos.relative(self.facing));
350
	}
351
352
	private static @Nullable Container getSourceContainer(final Level level, final Hopper hopper, final BlockPos pos, final BlockState state) {
353
		return getContainerAt(level, pos, state, hopper.getLevelX(), hopper.getLevelY() + 1.0, hopper.getLevelZ());
354
	}
355
356
	public static List<ItemEntity> getItemsAtAndAbove(final Level level, final Hopper hopper) {
357
		AABB aabb = hopper.getSuckAabb().move(hopper.getLevelX() - 0.5, hopper.getLevelY() - 0.5, hopper.getLevelZ() - 0.5);
358
		return level.getEntitiesOfClass(ItemEntity.class, aabb, EntitySelector.ENTITY_STILL_ALIVE);
359
	}
360
361
	public static @Nullable Container getContainerAt(final Level level, final BlockPos pos) {
362
		return getContainerAt(level, pos, level.getBlockState(pos), pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
363
	}
364
365
	private static @Nullable Container getContainerAt(
366
		final Level level, final BlockPos pos, final BlockState state, final double x, final double y, final double z
367
	) {
368
		Container result = getBlockContainer(level, pos, state);
369
		if (result == null) {
370
			result = getEntityContainer(level, x, y, z);
371
		}
372
373
		return result;
374
	}
375
376
	private static @Nullable Container getBlockContainer(final Level level, final BlockPos pos, final BlockState state) {
377
		Block block = state.getBlock();
378
		if (block instanceof WorldlyContainerHolder worldlyContainerHolder) {
379
			return worldlyContainerHolder.getContainer(state, level, pos);
380
		} else if (state.hasBlockEntity() && level.getBlockEntity(pos) instanceof Container container) {
381
			if (container instanceof ChestBlockEntity && block instanceof ChestBlock chestBlock) {
382
				container = ChestBlock.getContainer(chestBlock, state, level, pos, true);
383
			}
384
385
			return container;
386
		} else {
387
			return null;
388
		}
389
	}
390
391
	private static @Nullable Container getEntityContainer(final Level level, final double x, final double y, final double z) {
392
		List<Entity> entities = level.getEntities(
393
			(Entity)null, new AABB(x - 0.5, y - 0.5, z - 0.5, x + 0.5, y + 0.5, z + 0.5), EntitySelector.CONTAINER_ENTITY_SELECTOR
394
		);
395
		return !entities.isEmpty() ? (Container)entities.get(level.getRandom().nextInt(entities.size())) : null;
396
	}
397
398
	private static boolean canMergeItems(final ItemStack a, final ItemStack b) {
399
		return a.getCount() <= a.getMaxStackSize() && ItemStack.isSameItemSameComponents(a, b);
400
	}
401
402
	@Override
403
	public double getLevelX() {
404
		return this.worldPosition.getX() + 0.5;
405
	}
406
407
	@Override
408
	public double getLevelY() {
409
		return this.worldPosition.getY() + 0.5;
410
	}
411
412
	@Override
413
	public double getLevelZ() {
414
		return this.worldPosition.getZ() + 0.5;
415
	}
416
417
	@Override
418
	public boolean isGridAligned() {
419
		return true;
420
	}
421
422
	private void setCooldown(final int time) {
423
		this.cooldownTime = time;
424
	}
425
426
	private boolean isOnCooldown() {
427
		return this.cooldownTime > 0;
428
	}
429
430
	private boolean isOnCustomCooldown() {
431
		return this.cooldownTime > 8;
432
	}
433
434
	@Override
435
	protected NonNullList<ItemStack> getItems() {
436
		return this.items;
437
	}
438
439
	@Override
440
	protected void setItems(final NonNullList<ItemStack> items) {
441
		this.items = items;
442
	}
443
444
	public static void entityInside(final Level level, final BlockPos pos, final BlockState blockState, final Entity entity, final HopperBlockEntity hopper) {
445
		if (entity instanceof ItemEntity itemEntity
446
			&& !itemEntity.getItem().isEmpty()
447
			&& entity.getBoundingBox().move(-pos.getX(), -pos.getY(), -pos.getZ()).intersects(hopper.getSuckAabb())) {
448
			tryMoveItems(level, pos, blockState, hopper, () -> addItem(hopper, itemEntity));
449
		}
450
	}
451
452
	@Override
453
	protected AbstractContainerMenu createMenu(final int containerId, final Inventory inventory) {
454
		return new HopperMenu(containerId, inventory, this);
455
	}
456
}
457

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