Inventory .java

net.minecraft.world.entity.player.Inventory (class, 530 lines): members: findSlotMatchingCraftingIngredient, createInventoryUpdatePacket, getSelectionSize.

net.minecraft.world.entity.playerclass530 linescommon14.6 KB

Implements

API Surface (43)

int getSelectedSlot()
void setSelectedSlot(final int selected)
ItemStack getSelectedItem()
ItemStack setSelectedItem(final ItemStack itemStack)
int getSelectionSize()
NonNullList<ItemStack> getNonEquipmentItems()
int getFreeSlot()
void addAndPickItem(final ItemStack itemStack)
void pickSlot(final int slot)
boolean isHotbarSlot(final int slot)
int findSlotMatchingItem(final ItemStack itemStack)
boolean isUsableForCrafting(final ItemStack item)
int findSlotMatchingCraftingIngredient(final Holder<Item> item, final ItemStack existingItem)
int getSuitableHotbarSlot()
int clearOrCountMatchingItems(final Predicate<ItemStack> predicate, final boolean countingOnly, final int amountToRemove, final Container craftSlots)
int getSlotWithRemainingSpace(final ItemStack newItemStack)
void tick()
boolean add(final ItemStack itemStack)
boolean add(int slot, final ItemStack itemStack)
void placeItemBackInInventory(final ItemStack itemStack, final Prediction prediction)
void placeItemBackInInventory(final ItemStack itemStack, final boolean shouldSendSetSlotPacket, final Prediction prediction)
ClientboundSetPlayerInventoryPacket createInventoryUpdatePacket(final int slot)
ItemStack removeItem(final int slot, final int count)
void removeItem(final ItemStack itemStack)
ItemStack removeItemNoUpdate(final int slot)
void setItem(final int slot, final ItemStack itemStack)
void save(final ValueOutput.TypedOutputList<ItemStackWithSlot> output)
void load(final ValueInput.TypedInputList<ItemStackWithSlot> input)
int getContainerSize()
boolean isEmpty()
ItemStack getItem(final int slot)
Component getName()
void dropAll()
void setChanged()
int getTimesChanged()
boolean stillValid(final Player player)
boolean contains(final ItemStack searchStack)
boolean contains(final TagKey<Item> tag)
boolean contains(final Predicate<ItemStack> predicate)
void replaceWith(final Inventory other)
void clearContent()
void fillStackedContents(final StackedItemContents contents)
ItemStack removeFromSelected(final boolean all)

Fields & Constants (14)

POP_TIME_DURATION
INVENTORY_SIZE
SELECTION_SIZE
SLOT_OFFHAND
SLOT_BODY_ARMOR
SLOT_SADDLE
NOT_FOUND_INDEX
EQUIPMENT_SLOT_MAPPING
DEFAULT_NAME
items
selected
player
equipment
timesChanged

String literals (7)

"container.inventory"
"Invalid selected slot"
"Adding item to inventory"
"Item being added"
"Item ID"
"Item data"
"Item name"

Full Source

Inventory.java530 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.player;
2
3
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
4
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
5
import java.util.Map;
6
import java.util.function.Predicate;
7
import net.minecraft.CrashReport;
8
import net.minecraft.CrashReportCategory;
9
import net.minecraft.ReportedException;
10
import net.minecraft.core.Holder;
11
import net.minecraft.core.NonNullList;
12
import net.minecraft.core.component.DataComponents;
13
import net.minecraft.network.chat.Component;
14
import net.minecraft.network.protocol.game.ClientboundSetPlayerInventoryPacket;
15
import net.minecraft.server.level.ServerPlayer;
16
import net.minecraft.tags.TagKey;
17
import net.minecraft.util.Prediction;
18
import net.minecraft.world.Container;
19
import net.minecraft.world.ContainerHelper;
20
import net.minecraft.world.ItemStackWithSlot;
21
import net.minecraft.world.Nameable;
22
import net.minecraft.world.entity.EntityEquipment;
23
import net.minecraft.world.entity.EquipmentSlot;
24
import net.minecraft.world.entity.item.ItemEntity;
25
import net.minecraft.world.item.Item;
26
import net.minecraft.world.item.ItemStack;
27
import net.minecraft.world.level.storage.ValueInput;
28
import net.minecraft.world.level.storage.ValueOutput;
29
30
public class Inventory implements Container, Nameable {
31
	public static final int POP_TIME_DURATION = 5;
32
	public static final int INVENTORY_SIZE = 36;
33
	public static final int SELECTION_SIZE = 9;
34
	public static final int SLOT_OFFHAND = 40;
35
	public static final int SLOT_BODY_ARMOR = 41;
36
	public static final int SLOT_SADDLE = 42;
37
	public static final int NOT_FOUND_INDEX = -1;
38
	public static final Int2ObjectMap<EquipmentSlot> EQUIPMENT_SLOT_MAPPING = new Int2ObjectArrayMap<>(
39
		Map.of(
40
			EquipmentSlot.FEET.getIndex(36),
41
			EquipmentSlot.FEET,
42
			EquipmentSlot.LEGS.getIndex(36),
43
			EquipmentSlot.LEGS,
44
			EquipmentSlot.CHEST.getIndex(36),
45
			EquipmentSlot.CHEST,
46
			EquipmentSlot.HEAD.getIndex(36),
47
			EquipmentSlot.HEAD,
48
			40,
49
			EquipmentSlot.OFFHAND,
50
			41,
51
			EquipmentSlot.BODY,
52
			42,
53
			EquipmentSlot.SADDLE
54
		)
55
	);
56
	private static final Component DEFAULT_NAME = Component.translatable("container.inventory");
57
	private final NonNullList<ItemStack> items = NonNullList.withSize(36, ItemStack.EMPTY);
58
	private int selected;
59
	public final Player player;
60
	private final EntityEquipment equipment;
61
	private int timesChanged;
62
63
	public Inventory(final Player player, final EntityEquipment equipment) {
64
		this.player = player;
65
		this.equipment = equipment;
66
	}
67
68
	public int getSelectedSlot() {
69
		return this.selected;
70
	}
71
72
	public void setSelectedSlot(final int selected) {
73
		if (!isHotbarSlot(selected)) {
74
			throw new IllegalArgumentException("Invalid selected slot");
75
		}
76
77
		this.selected = selected;
78
	}
79
80
	public ItemStack getSelectedItem() {
81
		return this.items.get(this.selected);
82
	}
83
84
	public ItemStack setSelectedItem(final ItemStack itemStack) {
85
		return this.items.set(this.selected, itemStack);
86
	}
87
88
	public static int getSelectionSize() {
89
		return 9;
90
	}
91
92
	public NonNullList<ItemStack> getNonEquipmentItems() {
93
		return this.items;
94
	}
95
96
	private boolean hasRemainingSpaceForItem(final ItemStack slotItemStack, final ItemStack newItemStack) {
97
		return !slotItemStack.isEmpty()
98
			&& ItemStack.isSameItemSameComponents(slotItemStack, newItemStack)
99
			&& slotItemStack.isStackable()
100
			&& slotItemStack.getCount() < this.getMaxStackSize(slotItemStack);
101
	}
102
103
	public int getFreeSlot() {
104
		for (int i = 0; i < this.items.size(); i++) {
105
			if (this.items.get(i).isEmpty()) {
106
				return i;
107
			}
108
		}
109
110
		return -1;
111
	}
112
113
	public void addAndPickItem(final ItemStack itemStack) {
114
		this.setSelectedSlot(this.getSuitableHotbarSlot());
115
		if (!this.items.get(this.selected).isEmpty()) {
116
			int freeSlot = this.getFreeSlot();
117
			if (freeSlot != -1) {
118
				this.items.set(freeSlot, this.items.get(this.selected));
119
			}
120
		}
121
122
		this.items.set(this.selected, itemStack);
123
	}
124
125
	public void pickSlot(final int slot) {
126
		this.setSelectedSlot(this.getSuitableHotbarSlot());
127
		ItemStack tmp = this.items.get(this.selected);
128
		this.items.set(this.selected, this.items.get(slot));
129
		this.items.set(slot, tmp);
130
	}
131
132
	public static boolean isHotbarSlot(final int slot) {
133
		return slot >= 0 && slot < 9;
134
	}
135
136
	public int findSlotMatchingItem(final ItemStack itemStack) {
137
		for (int i = 0; i < this.items.size(); i++) {
138
			if (!this.items.get(i).isEmpty() && ItemStack.isSameItemSameComponents(itemStack, this.items.get(i))) {
139
				return i;
140
			}
141
		}
142
143
		return -1;
144
	}
145
146
	public static boolean isUsableForCrafting(final ItemStack item) {
147
		return !item.isDamaged() && !item.isEnchanted() && !item.has(DataComponents.CUSTOM_NAME);
148
	}
149
150
	public int findSlotMatchingCraftingIngredient(final Holder<Item> item, final ItemStack existingItem) {
151
		for (int i = 0; i < this.items.size(); i++) {
152
			ItemStack inventoryItemStack = this.items.get(i);
153
			if (!inventoryItemStack.isEmpty()
154
				&& inventoryItemStack.is(item)
155
				&& isUsableForCrafting(inventoryItemStack)
156
				&& (existingItem.isEmpty() || ItemStack.isSameItemSameComponents(existingItem, inventoryItemStack))) {
157
				return i;
158
			}
159
		}
160
161
		return -1;
162
	}
163
164
	public int getSuitableHotbarSlot() {
165
		for (int slot = 0; slot < 9; slot++) {
166
			int index = (this.selected + slot) % 9;
167
			if (this.items.get(index).isEmpty()) {
168
				return index;
169
			}
170
		}
171
172
		for (int slot = 0; slot < 9; slot++) {
173
			int index = (this.selected + slot) % 9;
174
			if (!this.items.get(index).isEnchanted()) {
175
				return index;
176
			}
177
		}
178
179
		return this.selected;
180
	}
181
182
	public int clearOrCountMatchingItems(final Predicate<ItemStack> predicate, final boolean countingOnly, final int amountToRemove, final Container craftSlots) {
183
		int count = 0;
184
		count += ContainerHelper.clearOrCountMatchingItems(this, predicate, amountToRemove - count, countingOnly);
185
		count += ContainerHelper.clearOrCountMatchingItems(craftSlots, predicate, amountToRemove - count, countingOnly);
186
		ItemStack carried = this.player.containerMenu.getCarried();
187
		count += ContainerHelper.clearOrCountMatchingItems(carried, predicate, amountToRemove - count, countingOnly);
188
		if (!countingOnly && carried.isEmpty()) {
189
			this.player.containerMenu.setCarried(ItemStack.EMPTY);
190
		}
191
192
		return count;
193
	}
194
195
	private int addResource(final ItemStack itemStack) {
196
		int slot = this.getSlotWithRemainingSpace(itemStack);
197
		if (slot == -1) {
198
			slot = this.getFreeSlot();
199
		}
200
201
		return slot == -1 ? itemStack.getCount() : this.addResource(slot, itemStack);
202
	}
203
204
	private int addResource(final int slot, final ItemStack itemStack) {
205
		int count = itemStack.getCount();
206
		ItemStack itemStackInSlot = this.getItem(slot);
207
		if (itemStackInSlot.isEmpty()) {
208
			itemStackInSlot = itemStack.copyWithCount(0);
209
			this.setItem(slot, itemStackInSlot);
210
		}
211
212
		int maxToAdd = this.getMaxStackSize(itemStackInSlot) - itemStackInSlot.getCount();
213
		int toAdd = Math.min(count, maxToAdd);
214
		if (toAdd == 0) {
215
			return count;
216
		}
217
218
		count -= toAdd;
219
		itemStackInSlot.grow(toAdd);
220
		itemStackInSlot.setPopTime(5);
221
		return count;
222
	}
223
224
	public int getSlotWithRemainingSpace(final ItemStack newItemStack) {
225
		if (this.hasRemainingSpaceForItem(this.getItem(this.selected), newItemStack)) {
226
			return this.selected;
227
		}
228
229
		if (this.hasRemainingSpaceForItem(this.getItem(40), newItemStack)) {
230
			return 40;
231
		}
232
233
		for (int i = 0; i < this.items.size(); i++) {
234
			if (this.hasRemainingSpaceForItem(this.items.get(i), newItemStack)) {
235
				return i;
236
			}
237
		}
238
239
		return -1;
240
	}
241
242
	public void tick() {
243
		for (int i = 0; i < this.items.size(); i++) {
244
			ItemStack itemStack = this.getItem(i);
245
			if (!itemStack.isEmpty()) {
246
				itemStack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null);
247
			}
248
		}
249
	}
250
251
	public boolean add(final ItemStack itemStack) {
252
		return this.add(-1, itemStack);
253
	}
254
255
	public boolean add(int slot, final ItemStack itemStack) {
256
		if (itemStack.isEmpty()) {
257
			return false;
258
		}
259
260
		try {
261
			if (itemStack.isDamaged()) {
262
				if (slot == -1) {
263
					slot = this.getFreeSlot();
264
				}
265
266
				if (slot >= 0) {
267
					this.items.set(slot, itemStack.copyAndClear());
268
					this.items.get(slot).setPopTime(5);
269
					return true;
270
				} else if (this.player.hasInfiniteMaterials()) {
271
					itemStack.setCount(0);
272
					return true;
273
				} else {
274
					return false;
275
				}
276
			} else {
277
				int lastSize;
278
				do {
279
					lastSize = itemStack.getCount();
280
					if (slot == -1) {
281
						itemStack.setCount(this.addResource(itemStack));
282
					} else {
283
						itemStack.setCount(this.addResource(slot, itemStack));
284
					}
285
				} while (!itemStack.isEmpty() && itemStack.getCount() < lastSize);
286
287
				if (itemStack.getCount() == lastSize && this.player.hasInfiniteMaterials()) {
288
					itemStack.setCount(0);
289
					return true;
290
				} else {
291
					return itemStack.getCount() < lastSize;
292
				}
293
			}
294
		} catch (Throwable t) {
295
			CrashReport report = CrashReport.forThrowable(t, "Adding item to inventory");
296
			CrashReportCategory category = report.addCategory("Item being added");
297
			category.setDetail("Item ID", Item.getId(itemStack.getItem()));
298
			category.setDetail("Item data", itemStack.getDamageValue());
299
			category.setDetail("Item name", () -> itemStack.getHoverName().getString());
300
			throw new ReportedException(report);
301
		}
302
	}
303
304
	public void placeItemBackInInventory(final ItemStack itemStack, final Prediction prediction) {
305
		this.placeItemBackInInventory(itemStack, true, prediction);
306
	}
307
308
	public void placeItemBackInInventory(final ItemStack itemStack, final boolean shouldSendSetSlotPacket, final Prediction prediction) {
309
		while (!itemStack.isEmpty()) {
310
			int slot = this.getSlotWithRemainingSpace(itemStack);
311
			if (slot == -1) {
312
				slot = this.getFreeSlot();
313
			}
314
315
			if (slot == -1) {
316
				this.player.drop(itemStack, false, prediction);
317
				break;
318
			}
319
320
			int slotHasSpaceFor = itemStack.getMaxStackSize() - this.getItem(slot).getCount();
321
			if (this.add(slot, itemStack.split(slotHasSpaceFor)) && shouldSendSetSlotPacket && this.player instanceof ServerPlayer serverPlayer) {
322
				serverPlayer.connection.send(this.createInventoryUpdatePacket(slot));
323
			}
324
		}
325
	}
326
327
	public ClientboundSetPlayerInventoryPacket createInventoryUpdatePacket(final int slot) {
328
		return new ClientboundSetPlayerInventoryPacket(slot, this.getItem(slot).copy());
329
	}
330
331
	@Override
332
	public ItemStack removeItem(final int slot, final int count) {
333
		if (slot < this.items.size()) {
334
			return ContainerHelper.removeItem(this.items, slot, count);
335
		}
336
337
		EquipmentSlot equipmentSlot = EQUIPMENT_SLOT_MAPPING.get(slot);
338
		if (equipmentSlot != null) {
339
			ItemStack itemStack = this.equipment.get(equipmentSlot);
340
			if (!itemStack.isEmpty()) {
341
				return itemStack.split(count);
342
			}
343
		}
344
345
		return ItemStack.EMPTY;
346
	}
347
348
	public void removeItem(final ItemStack itemStack) {
349
		for (int slot = 0; slot < this.items.size(); slot++) {
350
			if (this.items.get(slot) == itemStack) {
351
				this.items.set(slot, ItemStack.EMPTY);
352
				return;
353
			}
354
		}
355
356
		for (EquipmentSlot equipmentSlot : EQUIPMENT_SLOT_MAPPING.values()) {
357
			ItemStack stackInSlot = this.equipment.get(equipmentSlot);
358
			if (stackInSlot == itemStack) {
359
				this.equipment.set(equipmentSlot, ItemStack.EMPTY);
360
				return;
361
			}
362
		}
363
	}
364
365
	@Override
366
	public ItemStack removeItemNoUpdate(final int slot) {
367
		if (slot < this.items.size()) {
368
			ItemStack itemStack = this.items.get(slot);
369
			this.items.set(slot, ItemStack.EMPTY);
370
			return itemStack;
371
		} else {
372
			EquipmentSlot equipmentSlot = EQUIPMENT_SLOT_MAPPING.get(slot);
373
			return equipmentSlot != null ? this.equipment.set(equipmentSlot, ItemStack.EMPTY) : ItemStack.EMPTY;
374
		}
375
	}
376
377
	@Override
378
	public void setItem(final int slot, final ItemStack itemStack) {
379
		if (slot < this.items.size()) {
380
			this.items.set(slot, itemStack);
381
		}
382
383
		EquipmentSlot equipmentSlot = EQUIPMENT_SLOT_MAPPING.get(slot);
384
		if (equipmentSlot != null) {
385
			this.equipment.set(equipmentSlot, itemStack);
386
		}
387
	}
388
389
	public void save(final ValueOutput.TypedOutputList<ItemStackWithSlot> output) {
390
		for (int i = 0; i < this.items.size(); i++) {
391
			ItemStack item = this.items.get(i);
392
			if (!item.isEmpty()) {
393
				output.add(new ItemStackWithSlot(i, item));
394
			}
395
		}
396
	}
397
398
	public void load(final ValueInput.TypedInputList<ItemStackWithSlot> input) {
399
		this.items.clear();
400
401
		for (ItemStackWithSlot item : input) {
402
			if (item.isValidInContainer(this.items.size())) {
403
				this.setItem(item.slot(), item.stack());
404
			}
405
		}
406
	}
407
408
	@Override
409
	public int getContainerSize() {
410
		return this.items.size() + EQUIPMENT_SLOT_MAPPING.size();
411
	}
412
413
	@Override
414
	public boolean isEmpty() {
415
		for (ItemStack itemStack : this.items) {
416
			if (!itemStack.isEmpty()) {
417
				return false;
418
			}
419
		}
420
421
		for (EquipmentSlot slot : EQUIPMENT_SLOT_MAPPING.values()) {
422
			if (!this.equipment.get(slot).isEmpty()) {
423
				return false;
424
			}
425
		}
426
427
		return true;
428
	}
429
430
	@Override
431
	public ItemStack getItem(final int slot) {
432
		if (slot < this.items.size()) {
433
			return this.items.get(slot);
434
		}
435
436
		EquipmentSlot equipmentSlot = EQUIPMENT_SLOT_MAPPING.get(slot);
437
		return equipmentSlot != null ? this.equipment.get(equipmentSlot) : ItemStack.EMPTY;
438
	}
439
440
	@Override
441
	public Component getName() {
442
		return DEFAULT_NAME;
443
	}
444
445
	public void dropAll() {
446
		for (int i = 0; i < this.items.size(); i++) {
447
			ItemStack itemStack = this.items.get(i);
448
			if (!itemStack.isEmpty()) {
449
				ItemEntity drop = this.player.createItemStackToDrop(itemStack, true, false);
450
				if (drop != null) {
451
					this.player.level().addFreshEntity(drop);
452
				}
453
454
				this.items.set(i, ItemStack.EMPTY);
455
			}
456
		}
457
458
		this.equipment.dropAll(this.player);
459
	}
460
461
	@Override
462
	public void setChanged() {
463
		this.timesChanged++;
464
	}
465
466
	public int getTimesChanged() {
467
		return this.timesChanged;
468
	}
469
470
	@Override
471
	public boolean stillValid(final Player player) {
472
		return true;
473
	}
474
475
	public boolean contains(final ItemStack searchStack) {
476
		for (ItemStack itemStack : this) {
477
			if (!itemStack.isEmpty() && ItemStack.isSameItemSameComponents(itemStack, searchStack)) {
478
				return true;
479
			}
480
		}
481
482
		return false;
483
	}
484
485
	public boolean contains(final TagKey<Item> tag) {
486
		for (ItemStack itemStack : this) {
487
			if (!itemStack.isEmpty() && itemStack.is(tag)) {
488
				return true;
489
			}
490
		}
491
492
		return false;
493
	}
494
495
	public boolean contains(final Predicate<ItemStack> predicate) {
496
		for (ItemStack stack : this) {
497
			if (predicate.test(stack)) {
498
				return true;
499
			}
500
		}
501
502
		return false;
503
	}
504
505
	public void replaceWith(final Inventory other) {
506
		for (int i = 0; i < this.getContainerSize(); i++) {
507
			this.setItem(i, other.getItem(i));
508
		}
509
510
		this.setSelectedSlot(other.getSelectedSlot());
511
	}
512
513
	@Override
514
	public void clearContent() {
515
		this.items.clear();
516
		this.equipment.clear();
517
	}
518
519
	public void fillStackedContents(final StackedItemContents contents) {
520
		for (ItemStack itemStack : this.items) {
521
			contents.accountSimpleStack(itemStack);
522
		}
523
	}
524
525
	public ItemStack removeFromSelected(final boolean all) {
526
		ItemStack selectedItem = this.getSelectedItem();
527
		return selectedItem.isEmpty() ? ItemStack.EMPTY : this.removeItem(this.selected, all ? selectedItem.getCount() : 1);
528
	}
529
}
530

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