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;
100 private int $clientSelectedHotbarSlot = -1;
103 private ObjectSet $containerOpenCallbacks;
105 private ?
int $pendingCloseWindowId =
null;
107 private ?\Closure $pendingOpenWindowCallback =
null;
109 private int $nextItemStackId = 1;
110 private ?
int $currentItemStackRequestId =
null;
112 private bool $fullSyncRequested =
false;
115 private array $enchantingTableOptions = [];
118 private int $nextEnchantingTableOptionId = 100000;
120 public function __construct(
124 $this->containerOpenCallbacks =
new ObjectSet();
125 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
127 $this->add(ContainerIds::INVENTORY, $this->player->getInventory());
128 $this->add(ContainerIds::OFFHAND, $this->player->getOffHandInventory());
129 $this->add(ContainerIds::ARMOR, $this->player->getArmorInventory());
130 $this->addComplex(UIInventorySlotOffset::CURSOR, $this->player->getCursorInventory());
131 $this->addComplex(UIInventorySlotOffset::CRAFTING2X2_INPUT, $this->player->getCraftingGrid());
133 $this->player->getInventory()->getHeldItemIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
136 private function associateIdWithInventory(
int $id,
Inventory $inventory) :
void{
137 $this->networkIdToInventoryMap[$id] = $inventory;
140 private function getNewWindowId() :
int{
141 $this->lastInventoryNetworkId = max(ContainerIds::FIRST, ($this->lastInventoryNetworkId + 1) % ContainerIds::LAST);
142 return $this->lastInventoryNetworkId;
145 private function add(
int $id,
Inventory $inventory) :
void{
146 if(isset($this->inventories[spl_object_id($inventory)])){
147 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
150 $this->associateIdWithInventory($id, $inventory);
153 private function addDynamic(
Inventory $inventory) :
int{
154 $id = $this->getNewWindowId();
155 $this->add($id, $inventory);
163 private function addComplex(array|
int $slotMap,
Inventory $inventory) :
void{
164 if(isset($this->inventories[spl_object_id($inventory)])){
165 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
172 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
173 $this->complexSlotToInventoryMap[$netSlot] = $complexSlotMap;
181 private function addComplexDynamic(array|
int $slotMap,
Inventory $inventory) :
int{
182 $this->addComplex($slotMap, $inventory);
183 $id = $this->getNewWindowId();
184 $this->associateIdWithInventory($id, $inventory);
188 private function remove(
int $id) :
void{
189 $inventory = $this->networkIdToInventoryMap[$id];
190 unset($this->networkIdToInventoryMap[$id]);
191 if($this->getWindowId($inventory) ===
null){
192 unset($this->inventories[spl_object_id($inventory)]);
193 foreach($this->complexSlotToInventoryMap as $netSlot => $entry){
194 if($entry->getInventory() === $inventory){
195 unset($this->complexSlotToInventoryMap[$netSlot]);
201 public function getWindowId(
Inventory $inventory) : ?
int{
202 return ($id = array_search($inventory, $this->networkIdToInventoryMap,
true)) !==
false ? $id :
null;
205 public function getCurrentWindowId() :
int{
206 return $this->lastInventoryNetworkId;
214 $entry = $this->complexSlotToInventoryMap[$netSlotId] ??
null;
218 $inventory = $entry->getInventory();
219 $coreSlotId = $entry->mapNetToCore($netSlotId);
220 return $coreSlotId !==
null && $inventory->
slotExists($coreSlotId) ? [$inventory, $coreSlotId] :
null;
222 $inventory = $this->networkIdToInventoryMap[$windowId] ??
null;
223 if($inventory !==
null && $inventory->
slotExists($netSlotId)){
224 return [$inventory, $netSlotId];
229 private function addPredictedSlotChange(Inventory $inventory,
int $slot, ItemStack $item) : void{
230 $this->inventories[spl_object_id($inventory)]->predictions[$slot] = $item;
233 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
234 $typeConverter = $this->session->getTypeConverter();
235 foreach($tx->getActions() as $action){
236 if($action instanceof SlotChangeAction){
238 $itemStack = $typeConverter->coreItemStackToNet($action->getTargetItem());
239 $this->addPredictedSlotChange($action->getInventory(), $action->getSlot(), $itemStack);
249 foreach($networkInventoryActions as $action){
250 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
256 if(match($action->windowId){
257 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
260 throw new PacketHandlingException(
"Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
262 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
267 [$inventory, $slot] = $info;
268 $this->addPredictedSlotChange($inventory, $slot, $action->newItem->getItemStack());
272 public function setCurrentItemStackRequestId(?
int $id) : void{
273 $this->currentItemStackRequestId = $id;
290 private function openWindowDeferred(\Closure $func) : void{
291 if($this->pendingCloseWindowId !== null){
292 $this->session->getLogger()->debug(
"Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
293 $this->pendingOpenWindowCallback = $func;
303 private function createComplexSlotMapping(Inventory $inventory) : ?array{
306 $inventory instanceof AnvilInventory => UIInventorySlotOffset::ANVIL,
307 $inventory instanceof EnchantInventory => UIInventorySlotOffset::ENCHANTING_TABLE,
308 $inventory instanceof LoomInventory => UIInventorySlotOffset::LOOM,
309 $inventory instanceof StonecutterInventory => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventory::SLOT_INPUT],
310 $inventory instanceof CraftingTableInventory => UIInventorySlotOffset::CRAFTING3X3_INPUT,
311 $inventory instanceof CartographyTableInventory => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
312 $inventory instanceof SmithingTableInventory => UIInventorySlotOffset::SMITHING_TABLE,
317 public function onCurrentWindowChange(Inventory $inventory) : void{
318 $this->onCurrentWindowRemove();
320 $this->openWindowDeferred(
function() use ($inventory) :
void{
321 if(($slotMap = $this->createComplexSlotMapping($inventory)) !==
null){
322 $windowId = $this->addComplexDynamic($slotMap, $inventory);
324 $windowId = $this->addDynamic($inventory);
327 foreach($this->containerOpenCallbacks as $callback){
328 $pks = $callback($windowId, $inventory);
330 foreach($pks as $pk){
331 $this->session->sendDataPacket($pk);
333 $this->syncContents($inventory);
337 throw new \LogicException(
"Unsupported inventory type");
352 $blockPosition = BlockPosition::fromVector3($inv->getHolder());
353 $windowType = match(
true){
356 FurnaceType::FURNACE => WindowTypes::FURNACE,
357 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
358 FurnaceType::SMOKER => WindowTypes::SMOKER,
368 default => WindowTypes::CONTAINER
370 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
375 public function onClientOpenMainInventory() : void{
376 $this->onCurrentWindowRemove();
378 $this->openWindowDeferred(
function() :
void{
379 $windowId = $this->getNewWindowId();
380 $this->associateIdWithInventory($windowId, $this->player->getInventory());
382 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
384 WindowTypes::INVENTORY,
385 $this->player->getId()
390 public function onCurrentWindowRemove() : void{
391 if(isset($this->networkIdToInventoryMap[$this->lastInventoryNetworkId])){
392 $this->
remove($this->lastInventoryNetworkId);
393 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastInventoryNetworkId,
true));
394 if($this->pendingCloseWindowId !==
null){
395 throw new AssumptionFailedError(
"We should not have opened a new window while a window was waiting to be closed");
397 $this->pendingCloseWindowId = $this->lastInventoryNetworkId;
398 $this->enchantingTableOptions = [];
402 public function onClientRemoveWindow(
int $id) : void{
403 if($id === $this->lastInventoryNetworkId){
404 if(isset($this->networkIdToInventoryMap[$id]) && $id !== $this->pendingCloseWindowId){
406 $this->player->removeCurrentWindow();
409 $this->session->getLogger()->debug(
"Attempted to close inventory with network ID $id, but current is $this->lastInventoryNetworkId");
414 $this->session->sendDataPacket(ContainerClosePacket::create($id,
false));
416 if($this->pendingCloseWindowId === $id){
417 $this->pendingCloseWindowId =
null;
418 if($this->pendingOpenWindowCallback !==
null){
419 $this->session->getLogger()->debug(
"Opening deferred window after close ack of window $id");
420 ($this->pendingOpenWindowCallback)();
421 $this->pendingOpenWindowCallback =
null;
433 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
434 if($left->getRawExtraData() === $right->getRawExtraData()){
438 $typeConverter = $this->session->getTypeConverter();
439 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
440 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
442 $leftNbt = $leftExtraData->getNbt();
443 $rightNbt = $rightExtraData->getNbt();
445 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
446 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
447 $leftNbt === $rightNbt ||
448 ($leftNbt !==
null && $rightNbt !==
null && $leftNbt->equals($rightNbt))
452 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
454 $left->getId() === $right->getId() &&
455 $left->getMeta() === $right->getMeta() &&
456 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
457 $left->getCount() === $right->getCount() &&
458 $this->itemStackExtraDataEqual($left, $right);
461 public function onSlotChange(Inventory $inventory,
int $slot) : void{
462 $inventoryEntry = $this->inventories[spl_object_id($inventory)] ?? null;
463 if($inventoryEntry ===
null){
468 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($inventory->getItem($slot));
469 $clientSideItem = $inventoryEntry->predictions[$slot] ??
null;
470 if($clientSideItem ===
null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
472 $this->trackItemStack($inventoryEntry, $slot, $currentItem,
null);
473 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
476 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
479 unset($inventoryEntry->predictions[$slot]);
482 private function sendInventorySlotPackets(
int $windowId,
int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
491 if($itemStackWrapper->getStackId() !== 0){
492 $this->session->sendDataPacket(InventorySlotPacket::create(
495 new ItemStackWrapper(0, ItemStack::null())
499 $this->session->sendDataPacket(InventorySlotPacket::create(
509 private function sendInventoryContentPackets(
int $windowId, array $itemStackWrappers) : void{
518 $this->session->sendDataPacket(InventoryContentPacket::create(
520 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null()))
523 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers));
526 public function syncSlot(Inventory $inventory,
int $slot, ItemStack $itemStack) : void{
527 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
529 throw new \LogicException(
"Cannot sync an untracked inventory");
531 $itemStackInfo = $entry->itemStackInfos[$slot];
532 if($itemStackInfo ===
null){
533 throw new \LogicException(
"Cannot sync an untracked inventory slot");
535 if($entry->complexSlotMap !==
null){
536 $windowId = ContainerIds::UI;
537 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
539 $windowId = $this->getWindowId($inventory) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
543 $itemStackWrapper =
new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
544 if($windowId === ContainerIds::OFFHAND){
550 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
552 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
554 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
557 public function syncContents(Inventory $inventory) : void{
558 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
564 if($entry->complexSlotMap !==
null){
565 $windowId = ContainerIds::UI;
567 $windowId = $this->getWindowId($inventory);
569 if($windowId !==
null){
570 $entry->predictions = [];
571 $entry->pendingSyncs = [];
573 $typeConverter = $this->session->getTypeConverter();
574 foreach($inventory->getContents(
true) as $slot => $item){
575 $itemStack = $typeConverter->coreItemStackToNet($item);
576 $info = $this->trackItemStack($entry, $slot, $itemStack,
null);
577 $contents[] =
new ItemStackWrapper($info->getStackId(), $itemStack);
579 $clearSlotWrapper =
new ItemStackWrapper(0, ItemStack::null());
580 if($entry->complexSlotMap !==
null){
581 foreach($contents as $slotId => $info){
582 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ??
null;
583 if($packetSlot ===
null){
586 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
589 $this->sendInventoryContentPackets($windowId, $contents);
594 public function syncAll() : void{
595 foreach($this->inventories as $entry){
596 $this->syncContents($entry->inventory);
600 public function requestSyncAll() : void{
601 $this->fullSyncRequested = true;
604 public function syncMismatchedPredictedSlotChanges() : void{
605 $typeConverter = $this->session->getTypeConverter();
606 foreach($this->inventories as $entry){
607 $inventory = $entry->inventory;
608 foreach($entry->predictions as $slot => $expectedItem){
609 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] ===
null){
614 $this->session->getLogger()->debug(
"Detected prediction mismatch in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory) .
" slot $slot");
615 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
618 $entry->predictions = [];
622 public function flushPendingUpdates() : void{
623 if($this->fullSyncRequested){
624 $this->fullSyncRequested =
false;
625 $this->session->getLogger()->debug(
"Full inventory sync requested, sending contents of " . count($this->inventories) .
" inventories");
628 foreach($this->inventories as $entry){
629 if(count($entry->pendingSyncs) === 0){
632 $inventory = $entry->inventory;
633 $this->session->getLogger()->debug(
"Syncing slots " . implode(
", ", array_keys($entry->pendingSyncs)) .
" in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
634 foreach($entry->pendingSyncs as $slot => $itemStack){
635 $this->syncSlot($inventory, $slot, $itemStack);
637 $entry->pendingSyncs = [];
642 public function syncData(Inventory $inventory,
int $propertyId,
int $value) : void{
643 $windowId = $this->getWindowId($inventory);
644 if($windowId !==
null){
645 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
649 public function onClientSelectHotbarSlot(
int $slot) : void{
650 $this->clientSelectedHotbarSlot = $slot;
653 public function syncSelectedHotbarSlot() : void{
654 $playerInventory = $this->player->getInventory();
655 $selected = $playerInventory->getHeldItemIndex();
656 if($selected !== $this->clientSelectedHotbarSlot){
657 $inventoryEntry = $this->inventories[spl_object_id($playerInventory)] ??
null;
658 if($inventoryEntry ===
null){
659 throw new AssumptionFailedError(
"Player inventory should always be tracked");
661 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ??
null;
662 if($itemStackInfo ===
null){
663 throw new AssumptionFailedError(
"Untracked player inventory slot $selected");
666 $this->session->sendDataPacket(MobEquipmentPacket::create(
667 $this->player->getId(),
668 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItemInHand())),
671 ContainerIds::INVENTORY
673 $this->clientSelectedHotbarSlot = $selected;
677 public function syncCreative() : void{
678 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->getCache($this->player->getCreativeInventory()));
685 $protocolOptions = [];
687 foreach($options as $index => $option){
688 $optionId = $this->nextEnchantingTableOptionId++;
689 $this->enchantingTableOptions[$optionId] = $index;
691 $protocolEnchantments = array_map(
693 $option->getEnchantments()
697 $protocolOptions[] =
new ProtocolEnchantOption(
698 $option->getRequiredXpLevel(),
699 0, $protocolEnchantments,
702 $option->getDisplayName(),
707 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
710 public function getEnchantingTableOptionIndex(
int $recipeId) : ?int{
711 return $this->enchantingTableOptions[$recipeId] ?? null;
714 private function newItemStackId() : int{
715 return $this->nextItemStackId++;
718 public function getItemStackInfo(Inventory $inventory,
int $slot) : ?ItemStackInfo{
719 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
720 return $entry?->itemStackInfos[$slot] ??
null;
723 private function trackItemStack(InventoryManagerEntry $entry,
int $slotId, ItemStack $itemStack, ?
int $itemStackRequestId) : ItemStackInfo{
725 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
726 return $entry->itemStackInfos[$slotId] = $info;
getContainerOpenCallbacks()
locateWindowAndSlot(int $windowId, int $netSlotId)
static createContainerOpen(int $id, Inventory $inv)
addRawPredictedSlotChanges(array $networkInventoryActions)
syncEnchantingTableOptions(array $options)