PocketMine-MP 5.44.4 git-bc94a0da0c87abe7eb99d229a9ec672b3c405d11
Loading...
Searching...
No Matches
InventoryManager.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\network\mcpe;
25
37use pocketmine\crafting\FurnaceType;
72use function array_fill_keys;
73use function array_keys;
74use function array_map;
75use function array_search;
76use function count;
77use function get_class;
78use function implode;
79use function is_int;
80use function max;
81use function spl_object_id;
82
91 private array $entries = [];
92
97 private array $networkIdToWindowMap = [];
102 private array $complexSlotToWindowMap = [];
103
104 private int $lastWindowNetworkId = ContainerIds::FIRST;
105 private int $currentWindowType = WindowTypes::CONTAINER;
106
107 private int $clientSelectedHotbarSlot = -1;
108
110 private ObjectSet $containerOpenCallbacks;
111
112 private ?int $pendingCloseWindowId = null;
114 private ?\Closure $pendingOpenWindowCallback = null;
115
116 private int $nextItemStackId = 1;
117 private ?int $currentItemStackRequestId = null;
118
119 private bool $fullSyncRequested = false;
120
122 private array $enchantingTableOptions = [];
123 //TODO: this should be based on the total number of crafting recipes - if there are ever 100k recipes, this will
124 //conflict with regular recipes
125 private int $nextEnchantingTableOptionId = 100000;
126
127 public function __construct(
128 private Player $player,
129 private NetworkSession $session
130 ){
131 $this->containerOpenCallbacks = new ObjectSet();
132 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
133
134 foreach($this->player->getPermanentWindows() as $window){
135 match($window->getType()){
136 PlayerInventoryWindow::TYPE_INVENTORY => $this->add(ContainerIds::INVENTORY, $window),
137 PlayerInventoryWindow::TYPE_OFFHAND => $this->add(ContainerIds::OFFHAND, $window),
138 PlayerInventoryWindow::TYPE_ARMOR => $this->add(ContainerIds::ARMOR, $window),
139 PlayerInventoryWindow::TYPE_CURSOR => $this->addComplex(UIInventorySlotOffset::CURSOR, $window),
140 PlayerInventoryWindow::TYPE_CRAFTING => $this->addComplex(UIInventorySlotOffset::CRAFTING2X2_INPUT, $window),
141 default => throw new AssumptionFailedError("Unknown permanent window type " . $window->getType())
142 };
143 }
144
145 $this->player->getHotbar()->getSelectedIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
146 }
147
148 private function associateIdWithInventory(int $id, InventoryWindow $window) : void{
149 $this->networkIdToWindowMap[$id] = $window;
150 }
151
152 private function getNewWindowId() : int{
153 $this->lastWindowNetworkId = max(ContainerIds::FIRST, ($this->lastWindowNetworkId + 1) % ContainerIds::LAST);
154 return $this->lastWindowNetworkId;
155 }
156
157 private function getEntry(Inventory $inventory) : ?InventoryManagerEntry{
158 return $this->entries[spl_object_id($inventory)] ?? null;
159 }
160
161 private function getEntryByWindow(InventoryWindow $window) : ?InventoryManagerEntry{
162 return $this->getEntry($window->getInventory());
163 }
164
165 public function getInventoryWindow(Inventory $inventory) : ?InventoryWindow{
166 return $this->getEntry($inventory)?->window;
167 }
168
169 private function add(int $id, InventoryWindow $window) : void{
170 $k = spl_object_id($window->getInventory());
171 if(isset($this->entries[$k])){
172 throw new \InvalidArgumentException("Inventory " . get_class($window->getInventory()) . " is already tracked (open in two different windows?)");
173 }
174 $this->entries[$k] = new InventoryManagerEntry($window);
175 $window->getInventory()->getListeners()->add($this);
176 $this->associateIdWithInventory($id, $window);
177 }
178
179 private function addDynamic(InventoryWindow $inventory) : int{
180 $id = $this->getNewWindowId();
181 $this->add($id, $inventory);
182 return $id;
183 }
184
189 private function addComplex(array|int $slotMap, InventoryWindow $window) : void{
190 $k = spl_object_id($window->getInventory());
191 if(isset($this->entries[$k])){
192 throw new \InvalidArgumentException("Inventory " . get_class($window) . " is already tracked");
193 }
194 $complexSlotMap = new ComplexWindowMapEntry($window, is_int($slotMap) ? [$slotMap => 0] : $slotMap);
195 $this->entries[$k] = new InventoryManagerEntry(
196 $window,
197 $complexSlotMap
198 );
199 $window->getInventory()->getListeners()->add($this);
200 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
201 $this->complexSlotToWindowMap[$netSlot] = $complexSlotMap;
202 }
203 }
204
209 private function addComplexDynamic(array|int $slotMap, InventoryWindow $inventory) : int{
210 $this->addComplex($slotMap, $inventory);
211 $id = $this->getNewWindowId();
212 $this->associateIdWithInventory($id, $inventory);
213 return $id;
214 }
215
216 private function remove(int $id) : void{
217 $window = $this->networkIdToWindowMap[$id];
218 $inventory = $window->getInventory();
219 unset($this->networkIdToWindowMap[$id]);
220 if($this->getWindowId($window) === null){
221 $inventory->getListeners()->remove($this);
222 unset($this->entries[spl_object_id($inventory)]);
223 foreach($this->complexSlotToWindowMap as $netSlot => $entry){
224 if($entry->getWindow() === $window){
225 unset($this->complexSlotToWindowMap[$netSlot]);
226 }
227 }
228 }
229 }
230
231 public function getWindowId(InventoryWindow $window) : ?int{
232 return ($id = array_search($window, $this->networkIdToWindowMap, true)) !== false ? $id : null;
233 }
234
235 public function getCurrentWindowId() : int{
236 return $this->lastWindowNetworkId;
237 }
238
242 public function locateWindowAndSlot(int $windowId, int $netSlotId) : ?array{
243 if($windowId === ContainerIds::UI){
244 $entry = $this->complexSlotToWindowMap[$netSlotId] ?? null;
245 if($entry === null){
246 return null;
247 }
248 $window = $entry->getWindow();
249 $coreSlotId = $entry->mapNetToCore($netSlotId);
250 return $coreSlotId !== null && $window->getInventory()->slotExists($coreSlotId) ? [$window, $coreSlotId] : null;
251 }
252 $window = $this->networkIdToWindowMap[$windowId] ?? null;
253 if($window !== null && $window->getInventory()->slotExists($netSlotId)){
254 return [$window, $netSlotId];
255 }
256 return null;
257 }
258
259 private function addPredictedSlotChangeInternal(InventoryWindow $window, int $slot, ItemStack $item) : void{
260 //TODO: does this need a null check?
261 $entry = $this->getEntryByWindow($window) ?? throw new AssumptionFailedError("Assume this should never be null");
262 $entry->predictions[$slot] = $item;
263 }
264
265 public function addPredictedSlotChange(InventoryWindow $window, int $slot, Item $item) : void{
266 $typeConverter = $this->session->getTypeConverter();
267 $itemStack = $typeConverter->coreItemStackToNet($item);
268 $this->addPredictedSlotChangeInternal($window, $slot, $itemStack);
269 }
270
271 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
272 foreach($tx->getActions() as $action){
273 if($action instanceof SlotChangeAction){
274 //TODO: ItemStackRequestExecutor can probably build these predictions with much lower overhead
275 $this->addPredictedSlotChange(
276 $action->getInventoryWindow(),
277 $action->getSlot(),
278 $action->getTargetItem()
279 );
280 }
281 }
282 }
283
288 public function addRawPredictedSlotChanges(array $networkInventoryActions) : void{
289 foreach($networkInventoryActions as $action){
290 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
291 continue;
292 }
293 if($action->windowId === null){
294 throw new PacketHandlingException("Window ID should always be set for SOURCE_CONTAINER");
295 }
296
297 //legacy transactions should not modify or predict anything other than these inventories, since these are
298 //the only ones accessible when not in-game (ItemStackRequest is used for everything else)
299 if(match($action->windowId){
300 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
301 default => true
302 }){
303 throw new PacketHandlingException("Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
304 }
305 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
306 if($info === null){
307 continue;
308 }
309
310 [$window, $slot] = $info;
311 $this->addPredictedSlotChangeInternal($window, $slot, $action->newItem->getItemStack());
312 }
313 }
314
315 public function setCurrentItemStackRequestId(?int $id) : void{
316 $this->currentItemStackRequestId = $id;
317 }
318
333 private function openWindowDeferred(\Closure $func) : void{
334 if($this->pendingCloseWindowId !== null){
335 $this->session->getLogger()->debug("Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
336 $this->pendingOpenWindowCallback = $func;
337 }else{
338 $func();
339 }
340 }
341
346 private function createComplexSlotMapping(InventoryWindow $inventory) : ?array{
347 //TODO: make this dynamic so plugins can add mappings for stuff not implemented by PM
348 return match(true){
349 $inventory instanceof AnvilInventoryWindow => UIInventorySlotOffset::ANVIL,
350 $inventory instanceof EnchantingTableInventoryWindow => UIInventorySlotOffset::ENCHANTING_TABLE,
351 $inventory instanceof LoomInventoryWindow => UIInventorySlotOffset::LOOM,
352 $inventory instanceof StonecutterInventoryWindow => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventoryWindow::SLOT_INPUT],
353 $inventory instanceof CraftingTableInventoryWindow => UIInventorySlotOffset::CRAFTING3X3_INPUT,
354 $inventory instanceof CartographyTableInventoryWindow => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
355 $inventory instanceof SmithingTableInventoryWindow => UIInventorySlotOffset::SMITHING_TABLE,
356 default => null,
357 };
358 }
359
360 public function onCurrentWindowChange(InventoryWindow $window) : void{
361 $this->onCurrentWindowRemove();
362
363 $this->openWindowDeferred(function() use ($window) : void{
364 if(($slotMap = $this->createComplexSlotMapping($window)) !== null){
365 $windowId = $this->addComplexDynamic($slotMap, $window);
366 }else{
367 $windowId = $this->addDynamic($window);
368 }
369
370 foreach($this->containerOpenCallbacks as $callback){
371 $pks = $callback($windowId, $window);
372 if($pks !== null){
373 $windowType = null;
374 foreach($pks as $pk){
375 if($pk instanceof ContainerOpenPacket){
376 //workaround useless bullshit in 1.21 - ContainerClose requires a type now for some reason
377 $windowType = $pk->windowType;
378 }
379 $this->session->sendDataPacket($pk);
380 }
381 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
382 $this->syncContents($window);
383 return;
384 }
385 }
386 throw new \LogicException("Unsupported inventory type");
387 });
388 }
389
391 public function getContainerOpenCallbacks() : ObjectSet{ return $this->containerOpenCallbacks; }
392
397 protected static function createContainerOpen(int $id, InventoryWindow $window) : ?array{
398 //TODO: we should be using some kind of tagging system to identify the types. Instanceof is flaky especially
399 //if the class isn't final, not to mention being inflexible.
400 if($window instanceof BlockInventoryWindow){
401 $blockPosition = BlockPosition::fromVector3($window->getHolder());
402 $windowType = match(true){
403 $window instanceof LoomInventoryWindow => WindowTypes::LOOM,
404 $window instanceof FurnaceInventoryWindow => match($window->getFurnaceType()){
405 FurnaceType::FURNACE => WindowTypes::FURNACE,
406 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
407 FurnaceType::SMOKER => WindowTypes::SMOKER,
408 FurnaceType::CAMPFIRE, FurnaceType::SOUL_CAMPFIRE => throw new \LogicException("Campfire inventory cannot be displayed to a player")
409 },
410 $window instanceof EnchantingTableInventoryWindow => WindowTypes::ENCHANTMENT,
411 $window instanceof BrewingStandInventoryWindow => WindowTypes::BREWING_STAND,
412 $window instanceof AnvilInventoryWindow => WindowTypes::ANVIL,
413 $window instanceof HopperInventoryWindow => WindowTypes::HOPPER,
414 $window instanceof CraftingTableInventoryWindow => WindowTypes::WORKBENCH,
415 $window instanceof StonecutterInventoryWindow => WindowTypes::STONECUTTER,
416 $window instanceof CartographyTableInventoryWindow => WindowTypes::CARTOGRAPHY,
417 $window instanceof SmithingTableInventoryWindow => WindowTypes::SMITHING_TABLE,
418 default => WindowTypes::CONTAINER
419 };
420 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
421 }
422 return null;
423 }
424
425 public function onClientOpenMainInventory() : void{
426 $this->onCurrentWindowRemove();
427
428 $this->openWindowDeferred(function() : void{
429 $windowId = $this->getNewWindowId();
430 $window = $this->getInventoryWindow($this->player->getInventory()) ?? throw new AssumptionFailedError("This should never be null");
431 $this->associateIdWithInventory($windowId, $window);
432 $this->currentWindowType = WindowTypes::INVENTORY;
433
434 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
435 $windowId,
436 $this->currentWindowType,
437 $this->player->getId()
438 ));
439 });
440 }
441
442 public function onCurrentWindowRemove() : void{
443 if(isset($this->networkIdToWindowMap[$this->lastWindowNetworkId])){
444 $this->remove($this->lastWindowNetworkId);
445 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastWindowNetworkId, $this->currentWindowType, true));
446 if($this->pendingCloseWindowId !== null){
447 throw new AssumptionFailedError("We should not have opened a new window while a window was waiting to be closed");
448 }
449 $this->pendingCloseWindowId = $this->lastWindowNetworkId;
450 $this->enchantingTableOptions = [];
451 }
452 }
453
454 public function onClientRemoveWindow(int $id) : void{
455 if(Binary::signByte($id) === ContainerIds::NONE){ //TODO: REMOVE signByte() once BedrockProtocol + ext-encoding are implemented
456 //TODO: HACK! Since 1.21.100 (and probably earlier), the client will send -1 to close windows that it can't
457 //view for some reason, e.g. if the chat window was already open. This is pretty awkward, since it means
458 //that we can only assume it refers to the most recently sent window, and if we don't handle it,
459 //InventoryManager will never get the green light to send subsequent windows, which breaks inventory UIs.
460 //Fortunately, we already wait for close acks anyway, so the window ID is technically useless...?
461 $this->session->getLogger()->debug("Client rejected opening of a window, assuming it was $this->lastWindowNetworkId");
462 $id = $this->lastWindowNetworkId;
463 }
464 if($id === $this->lastWindowNetworkId){
465 if(isset($this->networkIdToWindowMap[$id]) && $id !== $this->pendingCloseWindowId){
466 $this->remove($id);
467 $this->player->removeCurrentWindow();
468 }
469 }else{
470 $this->session->getLogger()->debug("Attempted to close inventory with network ID $id, but current is $this->lastWindowNetworkId");
471 }
472
473 //Always send this, even if no window matches. If we told the client to close a window, it will behave as if it
474 //initiated the close and expect an ack.
475 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType, false));
476
477 if($this->pendingCloseWindowId === $id){
478 $this->pendingCloseWindowId = null;
479 if($this->pendingOpenWindowCallback !== null){
480 $this->session->getLogger()->debug("Opening deferred window after close ack of window $id");
481 ($this->pendingOpenWindowCallback)();
482 $this->pendingOpenWindowCallback = null;
483 }
484 }
485 }
486
494 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
495 if($left->getRawExtraData() === $right->getRawExtraData()){
496 return true;
497 }
498
499 $typeConverter = $this->session->getTypeConverter();
500 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
501 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
502
503 $leftNbt = $leftExtraData->getNbt();
504 $rightNbt = $rightExtraData->getNbt();
505 return
506 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
507 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
508 $leftNbt === $rightNbt || //this covers null === null and fast object identity
509 ($leftNbt !== null && $rightNbt !== null && $leftNbt->equals($rightNbt))
510 );
511 }
512
513 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
514 return
515 $left->getId() === $right->getId() &&
516 $left->getMeta() === $right->getMeta() &&
517 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
518 $left->getCount() === $right->getCount() &&
519 $this->itemStackExtraDataEqual($left, $right);
520 }
521
522 public function onSlotChange(Inventory $inventory, int $slot, Item $oldItem) : void{
523 $window = $this->getInventoryWindow($inventory);
524 if($window === null){
525 //this can happen when an inventory changed during InventoryCloseEvent, or when a temporary inventory
526 //is cleared before removal.
527 return;
528 }
529 $this->requestSyncSlot($window, $slot);
530 }
531
532 public function requestSyncSlot(InventoryWindow $window, int $slot) : void{
533 $inventoryEntry = $this->getEntryByWindow($window);
534 if($inventoryEntry === null){
535 //this can happen when an inventory changed during InventoryCloseEvent, or when a temporary inventory
536 //is cleared before removal.
537 return;
538 }
539
540 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($window->getInventory()->getItem($slot));
541 $clientSideItem = $inventoryEntry->predictions[$slot] ?? null;
542 if($clientSideItem === null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
543 //no prediction or incorrect - do not associate this with the currently active itemstack request
544 $this->trackItemStack($inventoryEntry, $slot, $currentItem, null);
545 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
546 }else{
547 //correctly predicted - associate the change with the currently active itemstack request
548 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
549 }
550
551 unset($inventoryEntry->predictions[$slot]);
552 }
553
554 private function sendInventorySlotPackets(int $windowId, int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
555 /*
556 * TODO: HACK!
557 * As of 1.20.12, the client ignores change of itemstackID in some cases when the old item == the new item.
558 * Notably, this happens with armor, offhand and enchanting tables, but not with main inventory.
559 * While we could track the items previously sent to the client, that's a waste of memory and would
560 * cost performance. Instead, clear the slot(s) first, then send the new item(s).
561 * The network cost of doing this is fortunately minimal, as an air itemstack is only 1 byte.
562 */
563 if($itemStackWrapper->getStackId() !== 0){
564 $this->session->sendDataPacket(InventorySlotPacket::create(
565 $windowId,
566 $netSlot,
567 null,
568 null,
569 new ItemStackWrapper(0, ItemStack::null())
570 ));
571 }
572 //now send the real contents
573 $this->session->sendDataPacket(InventorySlotPacket::create(
574 $windowId,
575 $netSlot,
576 null,
577 null,
578 $itemStackWrapper
579 ));
580 }
581
585 private function sendInventoryContentPackets(int $windowId, array $itemStackWrappers) : void{
586 /*
587 * TODO: HACK!
588 * As of 1.20.12, the client ignores change of itemstackID in some cases when the old item == the new item.
589 * Notably, this happens with armor, offhand and enchanting tables, but not with main inventory.
590 * While we could track the items previously sent to the client, that's a waste of memory and would
591 * cost performance. Instead, clear the slot(s) first, then send the new item(s).
592 * The network cost of doing this is fortunately minimal, as an air itemstack is only 1 byte.
593 */
594 $this->session->sendDataPacket(InventoryContentPacket::create(
595 $windowId,
596 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null())),
597 new FullContainerName(0, null),
598 new ItemStackWrapper(0, ItemStack::null())
599 ));
600 //now send the real contents
601 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers, new FullContainerName(0, null), new ItemStackWrapper(0, ItemStack::null())));
602 }
603
604 private function syncSlot(InventoryWindow $window, int $slot, ItemStack $itemStack) : void{
605 $entry = $this->getEntryByWindow($window) ?? throw new \LogicException("Cannot sync an untracked inventory");
606 $itemStackInfo = $entry->itemStackInfos[$slot];
607 if($itemStackInfo === null){
608 throw new \LogicException("Cannot sync an untracked inventory slot");
609 }
610 if($entry->complexSlotMap !== null){
611 $windowId = ContainerIds::UI;
612 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ?? throw new AssumptionFailedError("We already have an ItemStackInfo, so this should not be null");
613 }else{
614 $windowId = $this->getWindowId($window) ?? throw new AssumptionFailedError("We already have an ItemStackInfo, so this should not be null");
615 $netSlot = $slot;
616 }
617
618 $itemStackWrapper = new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
619 if($windowId === ContainerIds::OFFHAND){
620 //TODO: HACK!
621 //The client may sometimes ignore the InventorySlotPacket for the offhand slot.
622 //This can cause a lot of problems (totems, arrows, and more...).
623 //The workaround is to send an InventoryContentPacket instead
624 //BDS (Bedrock Dedicated Server) also seems to work this way.
625 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
626 }else{
627 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
628 }
629 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
630 }
631
632 public function onContentChange(Inventory $inventory, array $oldContents) : void{
633 //this can be null when an inventory changed during InventoryCloseEvent, or when a temporary inventory
634 //is cleared before removal.
635 $window = $this->getInventoryWindow($inventory);
636 if($window !== null){
637 $this->syncContents($window);
638 }
639 }
640
641 private function syncContents(InventoryWindow $window) : void{
642 $entry = $this->getEntryByWindow($window);
643 if($entry === null){
644 //this can happen when an inventory changed during InventoryCloseEvent, or when a temporary inventory
645 //is cleared before removal.
646 return;
647 }
648 if($entry->complexSlotMap !== null){
649 $windowId = ContainerIds::UI;
650 }else{
651 $windowId = $this->getWindowId($window);
652 }
653 if($windowId !== null){
654 $entry->predictions = [];
655 $entry->pendingSyncs = [];
656 $contents = [];
657 $typeConverter = $this->session->getTypeConverter();
658 foreach($window->getInventory()->getContents(true) as $slot => $item){
659 $itemStack = $typeConverter->coreItemStackToNet($item);
660 $info = $this->trackItemStack($entry, $slot, $itemStack, null);
661 $contents[] = new ItemStackWrapper($info->getStackId(), $itemStack);
662 }
663 if($entry->complexSlotMap !== null){
664 foreach($contents as $slotId => $info){
665 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ?? null;
666 if($packetSlot === null){
667 continue;
668 }
669 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
670 }
671 }else{
672 $this->sendInventoryContentPackets($windowId, $contents);
673 }
674 }
675 }
676
677 public function syncAll() : void{
678 foreach($this->entries as $entry){
679 $this->syncContents($entry->window);
680 }
681 }
682
683 public function requestSyncAll() : void{
684 $this->fullSyncRequested = true;
685 }
686
687 public function syncMismatchedPredictedSlotChanges() : void{
688 $typeConverter = $this->session->getTypeConverter();
689 foreach($this->entries as $entry){
690 $inventory = $entry->window->getInventory();
691 foreach($entry->predictions as $slot => $expectedItem){
692 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] === null){
693 continue; //TODO: size desync ???
694 }
695
696 //any prediction that still exists at this point is a slot that was predicted to change but didn't
697 $this->session->getLogger()->debug("Detected prediction mismatch in inventory " . get_class($inventory) . "#" . spl_object_id($inventory) . " slot $slot");
698 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
699 }
700
701 $entry->predictions = [];
702 }
703 }
704
705 public function flushPendingUpdates() : void{
706 if($this->fullSyncRequested){
707 $this->fullSyncRequested = false;
708 $this->session->getLogger()->debug("Full inventory sync requested, sending contents of " . count($this->entries) . " inventories");
709 $this->syncAll();
710 }else{
711 foreach($this->entries as $entry){
712 if(count($entry->pendingSyncs) === 0){
713 continue;
714 }
715 $inventory = $entry->window;
716 $this->session->getLogger()->debug("Syncing slots " . implode(", ", array_keys($entry->pendingSyncs)) . " in inventory " . get_class($inventory) . "#" . spl_object_id($inventory));
717 foreach($entry->pendingSyncs as $slot => $itemStack){
718 $this->syncSlot($inventory, $slot, $itemStack);
719 }
720 $entry->pendingSyncs = [];
721 }
722 }
723 }
724
725 public function syncData(Inventory $inventory, int $propertyId, int $value) : void{
726 //TODO: the handling of this data has always kinda sucked. Probably ought to route it through InventoryWindow
727 //somehow, but I'm not sure exactly how that should look.
728 $window = $this->getInventoryWindow($inventory);
729 if($window === null){
730 return;
731 }
732 $windowId = $this->getWindowId($window);
733 if($windowId !== null){
734 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
735 }
736 }
737
738 public function onClientSelectHotbarSlot(int $slot) : void{
739 $this->clientSelectedHotbarSlot = $slot;
740 }
741
742 public function syncSelectedHotbarSlot() : void{
743 $playerInventory = $this->player->getInventory();
744 $selected = $this->player->getHotbar()->getSelectedIndex();
745 if($selected !== $this->clientSelectedHotbarSlot){
746 $inventoryEntry = $this->getEntry($playerInventory) ?? throw new AssumptionFailedError("Player inventory should always be tracked");
747 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ?? null;
748 if($itemStackInfo === null){
749 throw new AssumptionFailedError("Untracked player inventory slot $selected");
750 }
751
752 $this->session->sendDataPacket(MobEquipmentPacket::create(
753 $this->player->getId(),
754 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItem($selected))),
755 $selected,
756 $selected,
757 ContainerIds::INVENTORY
758 ));
759 $this->clientSelectedHotbarSlot = $selected;
760 }
761 }
762
763 public function syncCreative() : void{
764 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->buildPacket($this->player->getCreativeInventory(), $this->session));
765 }
766
771 public function syncEnchantingTableOptions(array $options) : void{
772 $protocolOptions = [];
773
774 foreach($options as $index => $option){
775 $optionId = $this->nextEnchantingTableOptionId++;
776 $this->enchantingTableOptions[$optionId] = $index;
777
778 $protocolEnchantments = array_map(
779 fn(EnchantmentInstance $e) => new Enchant(EnchantmentIdMap::getInstance()->toId($e->getType()), $e->getLevel()),
780 $option->getEnchantments()
781 );
782 // We don't pay attention to the $slotFlags, $heldActivatedEnchantments and $selfActivatedEnchantments
783 // as everything works fine without them (perhaps these values are used somehow in the BDS).
784 $protocolOptions[] = new ProtocolEnchantOption(
785 $option->getRequiredXpLevel(),
786 0, $protocolEnchantments,
787 [],
788 [],
789 $option->getDisplayName(),
790 $optionId
791 );
792 }
793
794 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
795 }
796
797 public function getEnchantingTableOptionIndex(int $recipeId) : ?int{
798 return $this->enchantingTableOptions[$recipeId] ?? null;
799 }
800
801 private function newItemStackId() : int{
802 return $this->nextItemStackId++;
803 }
804
805 public function getItemStackInfo(InventoryWindow $window, int $slot) : ?ItemStackInfo{
806 return $this->getEntryByWindow($window)?->itemStackInfos[$slot] ?? null;
807 }
808
809 private function trackItemStack(InventoryManagerEntry $entry, int $slotId, ItemStack $itemStack, ?int $itemStackRequestId) : ItemStackInfo{
810 //TODO: ItemStack->isNull() would be nice to have here
811 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
812 return $entry->itemStackInfos[$slotId] = $info;
813 }
814}
static createContainerOpen(int $id, InventoryWindow $window)
locateWindowAndSlot(int $windowId, int $netSlotId)
onContentChange(Inventory $inventory, array $oldContents)
addRawPredictedSlotChanges(array $networkInventoryActions)