22declare(strict_types=1);
24namespace pocketmine\network\mcpe;
37use pocketmine\crafting\FurnaceType;
66use
function array_fill_keys;
67use
function array_keys;
68use
function array_map;
69use
function array_search;
71use
function get_class;
75use
function spl_object_id;
85 private array $inventories = [];
91 private array $networkIdToInventoryMap = [];
96 private array $complexSlotToInventoryMap = [];
98 private int $lastInventoryNetworkId = ContainerIds::FIRST;
99 private int $currentWindowType = WindowTypes::CONTAINER;
101 private int $clientSelectedHotbarSlot = -1;
104 private ObjectSet $containerOpenCallbacks;
106 private ?
int $pendingCloseWindowId =
null;
108 private ?\Closure $pendingOpenWindowCallback =
null;
110 private int $nextItemStackId = 1;
111 private ?
int $currentItemStackRequestId =
null;
113 private bool $fullSyncRequested =
false;
116 private array $enchantingTableOptions = [];
119 private int $nextEnchantingTableOptionId = 100000;
121 public function __construct(
125 $this->containerOpenCallbacks =
new ObjectSet();
126 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
128 $this->add(ContainerIds::INVENTORY, $this->player->getInventory());
129 $this->add(ContainerIds::OFFHAND, $this->player->getOffHandInventory());
130 $this->add(ContainerIds::ARMOR, $this->player->getArmorInventory());
131 $this->addComplex(UIInventorySlotOffset::CURSOR, $this->player->getCursorInventory());
132 $this->addComplex(UIInventorySlotOffset::CRAFTING2X2_INPUT, $this->player->getCraftingGrid());
134 $this->player->getInventory()->getHeldItemIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
137 private function associateIdWithInventory(
int $id,
Inventory $inventory) :
void{
138 $this->networkIdToInventoryMap[$id] = $inventory;
141 private function getNewWindowId() :
int{
142 $this->lastInventoryNetworkId = max(ContainerIds::FIRST, ($this->lastInventoryNetworkId + 1) % ContainerIds::LAST);
143 return $this->lastInventoryNetworkId;
146 private function add(
int $id,
Inventory $inventory) :
void{
147 if(isset($this->inventories[spl_object_id($inventory)])){
148 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
151 $this->associateIdWithInventory($id, $inventory);
154 private function addDynamic(
Inventory $inventory) :
int{
155 $id = $this->getNewWindowId();
156 $this->add($id, $inventory);
164 private function addComplex(array|
int $slotMap,
Inventory $inventory) :
void{
165 if(isset($this->inventories[spl_object_id($inventory)])){
166 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
173 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
174 $this->complexSlotToInventoryMap[$netSlot] = $complexSlotMap;
182 private function addComplexDynamic(array|
int $slotMap,
Inventory $inventory) :
int{
183 $this->addComplex($slotMap, $inventory);
184 $id = $this->getNewWindowId();
185 $this->associateIdWithInventory($id, $inventory);
189 private function remove(
int $id) :
void{
190 $inventory = $this->networkIdToInventoryMap[$id];
191 unset($this->networkIdToInventoryMap[$id]);
192 if($this->getWindowId($inventory) ===
null){
193 unset($this->inventories[spl_object_id($inventory)]);
194 foreach($this->complexSlotToInventoryMap as $netSlot => $entry){
195 if($entry->getInventory() === $inventory){
196 unset($this->complexSlotToInventoryMap[$netSlot]);
202 public function getWindowId(
Inventory $inventory) : ?
int{
203 return ($id = array_search($inventory, $this->networkIdToInventoryMap,
true)) !==
false ? $id :
null;
206 public function getCurrentWindowId() :
int{
207 return $this->lastInventoryNetworkId;
215 $entry = $this->complexSlotToInventoryMap[$netSlotId] ??
null;
219 $inventory = $entry->getInventory();
220 $coreSlotId = $entry->mapNetToCore($netSlotId);
221 return $coreSlotId !==
null && $inventory->
slotExists($coreSlotId) ? [$inventory, $coreSlotId] :
null;
223 $inventory = $this->networkIdToInventoryMap[$windowId] ??
null;
224 if($inventory !==
null && $inventory->
slotExists($netSlotId)){
225 return [$inventory, $netSlotId];
230 private function addPredictedSlotChange(Inventory $inventory,
int $slot, ItemStack $item) : void{
231 $this->inventories[spl_object_id($inventory)]->predictions[$slot] = $item;
234 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
235 $typeConverter = $this->session->getTypeConverter();
236 foreach($tx->getActions() as $action){
237 if($action instanceof SlotChangeAction){
239 $itemStack = $typeConverter->coreItemStackToNet($action->getTargetItem());
240 $this->addPredictedSlotChange($action->getInventory(), $action->getSlot(), $itemStack);
250 foreach($networkInventoryActions as $action){
251 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
257 if(match($action->windowId){
258 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
261 throw new PacketHandlingException(
"Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
263 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
268 [$inventory, $slot] = $info;
269 $this->addPredictedSlotChange($inventory, $slot, $action->newItem->getItemStack());
273 public function setCurrentItemStackRequestId(?
int $id) : void{
274 $this->currentItemStackRequestId = $id;
291 private function openWindowDeferred(\Closure $func) : void{
292 if($this->pendingCloseWindowId !== null){
293 $this->session->getLogger()->debug(
"Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
294 $this->pendingOpenWindowCallback = $func;
304 private function createComplexSlotMapping(Inventory $inventory) : ?array{
307 $inventory instanceof AnvilInventory => UIInventorySlotOffset::ANVIL,
308 $inventory instanceof EnchantInventory => UIInventorySlotOffset::ENCHANTING_TABLE,
309 $inventory instanceof LoomInventory => UIInventorySlotOffset::LOOM,
310 $inventory instanceof StonecutterInventory => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventory::SLOT_INPUT],
311 $inventory instanceof CraftingTableInventory => UIInventorySlotOffset::CRAFTING3X3_INPUT,
312 $inventory instanceof CartographyTableInventory => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
313 $inventory instanceof SmithingTableInventory => UIInventorySlotOffset::SMITHING_TABLE,
318 public function onCurrentWindowChange(Inventory $inventory) : void{
319 $this->onCurrentWindowRemove();
321 $this->openWindowDeferred(
function() use ($inventory) :
void{
322 if(($slotMap = $this->createComplexSlotMapping($inventory)) !==
null){
323 $windowId = $this->addComplexDynamic($slotMap, $inventory);
325 $windowId = $this->addDynamic($inventory);
328 foreach($this->containerOpenCallbacks as $callback){
329 $pks = $callback($windowId, $inventory);
332 foreach($pks as $pk){
333 if($pk instanceof ContainerOpenPacket){
335 $windowType = $pk->windowType;
337 $this->session->sendDataPacket($pk);
339 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
340 $this->syncContents($inventory);
344 throw new \LogicException(
"Unsupported inventory type");
359 $blockPosition = BlockPosition::fromVector3($inv->getHolder());
360 $windowType = match(
true){
363 FurnaceType::FURNACE => WindowTypes::FURNACE,
364 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
365 FurnaceType::SMOKER => WindowTypes::SMOKER,
375 default => WindowTypes::CONTAINER
377 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
382 public function onClientOpenMainInventory() : void{
383 $this->onCurrentWindowRemove();
385 $this->openWindowDeferred(
function() :
void{
386 $windowId = $this->getNewWindowId();
387 $this->associateIdWithInventory($windowId, $this->player->getInventory());
388 $this->currentWindowType = WindowTypes::INVENTORY;
390 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
392 $this->currentWindowType,
393 $this->player->getId()
398 public function onCurrentWindowRemove() : void{
399 if(isset($this->networkIdToInventoryMap[$this->lastInventoryNetworkId])){
400 $this->
remove($this->lastInventoryNetworkId);
401 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastInventoryNetworkId, $this->currentWindowType,
true));
402 if($this->pendingCloseWindowId !==
null){
403 throw new AssumptionFailedError(
"We should not have opened a new window while a window was waiting to be closed");
405 $this->pendingCloseWindowId = $this->lastInventoryNetworkId;
406 $this->enchantingTableOptions = [];
410 public function onClientRemoveWindow(
int $id) : void{
411 if($id === $this->lastInventoryNetworkId){
412 if(isset($this->networkIdToInventoryMap[$id]) && $id !== $this->pendingCloseWindowId){
414 $this->player->removeCurrentWindow();
417 $this->session->getLogger()->debug(
"Attempted to close inventory with network ID $id, but current is $this->lastInventoryNetworkId");
422 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType,
false));
424 if($this->pendingCloseWindowId === $id){
425 $this->pendingCloseWindowId =
null;
426 if($this->pendingOpenWindowCallback !==
null){
427 $this->session->getLogger()->debug(
"Opening deferred window after close ack of window $id");
428 ($this->pendingOpenWindowCallback)();
429 $this->pendingOpenWindowCallback =
null;
441 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
442 if($left->getRawExtraData() === $right->getRawExtraData()){
446 $typeConverter = $this->session->getTypeConverter();
447 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
448 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
450 $leftNbt = $leftExtraData->getNbt();
451 $rightNbt = $rightExtraData->getNbt();
453 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
454 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
455 $leftNbt === $rightNbt ||
456 ($leftNbt !==
null && $rightNbt !==
null && $leftNbt->equals($rightNbt))
460 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
462 $left->getId() === $right->getId() &&
463 $left->getMeta() === $right->getMeta() &&
464 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
465 $left->getCount() === $right->getCount() &&
466 $this->itemStackExtraDataEqual($left, $right);
469 public function onSlotChange(Inventory $inventory,
int $slot) : void{
470 $inventoryEntry = $this->inventories[spl_object_id($inventory)] ?? null;
471 if($inventoryEntry ===
null){
476 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($inventory->getItem($slot));
477 $clientSideItem = $inventoryEntry->predictions[$slot] ??
null;
478 if($clientSideItem ===
null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
480 $this->trackItemStack($inventoryEntry, $slot, $currentItem,
null);
481 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
484 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
487 unset($inventoryEntry->predictions[$slot]);
490 private function sendInventorySlotPackets(
int $windowId,
int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
499 if($itemStackWrapper->getStackId() !== 0){
500 $this->session->sendDataPacket(InventorySlotPacket::create(
503 new ItemStackWrapper(0, ItemStack::null())
507 $this->session->sendDataPacket(InventorySlotPacket::create(
517 private function sendInventoryContentPackets(
int $windowId, array $itemStackWrappers) : void{
526 $this->session->sendDataPacket(InventoryContentPacket::create(
528 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null()))
531 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers));
534 public function syncSlot(Inventory $inventory,
int $slot, ItemStack $itemStack) : void{
535 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
537 throw new \LogicException(
"Cannot sync an untracked inventory");
539 $itemStackInfo = $entry->itemStackInfos[$slot];
540 if($itemStackInfo ===
null){
541 throw new \LogicException(
"Cannot sync an untracked inventory slot");
543 if($entry->complexSlotMap !==
null){
544 $windowId = ContainerIds::UI;
545 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
547 $windowId = $this->getWindowId($inventory) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
551 $itemStackWrapper =
new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
552 if($windowId === ContainerIds::OFFHAND){
558 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
560 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
562 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
565 public function syncContents(Inventory $inventory) : void{
566 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
572 if($entry->complexSlotMap !==
null){
573 $windowId = ContainerIds::UI;
575 $windowId = $this->getWindowId($inventory);
577 if($windowId !==
null){
578 $entry->predictions = [];
579 $entry->pendingSyncs = [];
581 $typeConverter = $this->session->getTypeConverter();
582 foreach($inventory->getContents(
true) as $slot => $item){
583 $itemStack = $typeConverter->coreItemStackToNet($item);
584 $info = $this->trackItemStack($entry, $slot, $itemStack,
null);
585 $contents[] =
new ItemStackWrapper($info->getStackId(), $itemStack);
587 $clearSlotWrapper =
new ItemStackWrapper(0, ItemStack::null());
588 if($entry->complexSlotMap !==
null){
589 foreach($contents as $slotId => $info){
590 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ??
null;
591 if($packetSlot ===
null){
594 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
597 $this->sendInventoryContentPackets($windowId, $contents);
602 public function syncAll() : void{
603 foreach($this->inventories as $entry){
604 $this->syncContents($entry->inventory);
608 public function requestSyncAll() : void{
609 $this->fullSyncRequested = true;
612 public function syncMismatchedPredictedSlotChanges() : void{
613 $typeConverter = $this->session->getTypeConverter();
614 foreach($this->inventories as $entry){
615 $inventory = $entry->inventory;
616 foreach($entry->predictions as $slot => $expectedItem){
617 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] ===
null){
622 $this->session->getLogger()->debug(
"Detected prediction mismatch in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory) .
" slot $slot");
623 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
626 $entry->predictions = [];
630 public function flushPendingUpdates() : void{
631 if($this->fullSyncRequested){
632 $this->fullSyncRequested =
false;
633 $this->session->getLogger()->debug(
"Full inventory sync requested, sending contents of " . count($this->inventories) .
" inventories");
636 foreach($this->inventories as $entry){
637 if(count($entry->pendingSyncs) === 0){
640 $inventory = $entry->inventory;
641 $this->session->getLogger()->debug(
"Syncing slots " . implode(
", ", array_keys($entry->pendingSyncs)) .
" in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
642 foreach($entry->pendingSyncs as $slot => $itemStack){
643 $this->syncSlot($inventory, $slot, $itemStack);
645 $entry->pendingSyncs = [];
650 public function syncData(Inventory $inventory,
int $propertyId,
int $value) : void{
651 $windowId = $this->getWindowId($inventory);
652 if($windowId !==
null){
653 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
657 public function onClientSelectHotbarSlot(
int $slot) : void{
658 $this->clientSelectedHotbarSlot = $slot;
661 public function syncSelectedHotbarSlot() : void{
662 $playerInventory = $this->player->getInventory();
663 $selected = $playerInventory->getHeldItemIndex();
664 if($selected !== $this->clientSelectedHotbarSlot){
665 $inventoryEntry = $this->inventories[spl_object_id($playerInventory)] ??
null;
666 if($inventoryEntry ===
null){
667 throw new AssumptionFailedError(
"Player inventory should always be tracked");
669 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ??
null;
670 if($itemStackInfo ===
null){
671 throw new AssumptionFailedError(
"Untracked player inventory slot $selected");
674 $this->session->sendDataPacket(MobEquipmentPacket::create(
675 $this->player->getId(),
676 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItemInHand())),
679 ContainerIds::INVENTORY
681 $this->clientSelectedHotbarSlot = $selected;
685 public function syncCreative() : void{
686 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->getCache($this->player->getCreativeInventory()));
693 $protocolOptions = [];
695 foreach($options as $index => $option){
696 $optionId = $this->nextEnchantingTableOptionId++;
697 $this->enchantingTableOptions[$optionId] = $index;
699 $protocolEnchantments = array_map(
701 $option->getEnchantments()
705 $protocolOptions[] =
new ProtocolEnchantOption(
706 $option->getRequiredXpLevel(),
707 0, $protocolEnchantments,
710 $option->getDisplayName(),
715 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
718 public function getEnchantingTableOptionIndex(
int $recipeId) : ?int{
719 return $this->enchantingTableOptions[$recipeId] ?? null;
722 private function newItemStackId() : int{
723 return $this->nextItemStackId++;
726 public function getItemStackInfo(Inventory $inventory,
int $slot) : ?ItemStackInfo{
727 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
728 return $entry?->itemStackInfos[$slot] ??
null;
731 private function trackItemStack(InventoryManagerEntry $entry,
int $slotId, ItemStack $itemStack, ?
int $itemStackRequestId) : ItemStackInfo{
733 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
734 return $entry->itemStackInfos[$slotId] = $info;
getContainerOpenCallbacks()
locateWindowAndSlot(int $windowId, int $netSlotId)
static createContainerOpen(int $id, Inventory $inv)
addRawPredictedSlotChanges(array $networkInventoryActions)
syncEnchantingTableOptions(array $options)