130 private const MAX_FORM_RESPONSE_DEPTH = 2;
132 protected float $lastRightClickTime = 0.0;
135 protected ?
Vector3 $lastPlayerAuthInputPosition =
null;
136 protected ?
float $lastPlayerAuthInputYaw =
null;
137 protected ?
float $lastPlayerAuthInputPitch =
null;
138 protected ?
BitSet $lastPlayerAuthInputFlags =
null;
140 public bool $forceMoveSync =
false;
142 protected ?
string $lastRequestedFullSkinId =
null;
144 public function __construct(
150 public function handleText(
TextPacket $packet) :
bool{
151 if($packet->type === TextPacket::TYPE_CHAT){
152 return $this->player->chat($packet->message);
164 private function resolveOnOffInputFlags(
BitSet $inputFlags,
int $startFlag,
int $stopFlag) : ?
bool{
165 $enabled = $inputFlags->get($startFlag);
166 $disabled = $inputFlags->get($stopFlag);
167 if($enabled !== $disabled){
175 $rawPos = $packet->getPosition();
176 $rawYaw = $packet->getYaw();
177 $rawPitch = $packet->getPitch();
178 foreach([$rawPos->x, $rawPos->y, $rawPos->z, $rawYaw, $packet->getHeadYaw(), $rawPitch] as $float){
179 if(is_infinite($float) || is_nan($float)){
180 $this->session->getLogger()->debug(
"Invalid movement received, contains NAN/INF components");
185 if($rawYaw !== $this->lastPlayerAuthInputYaw || $rawPitch !== $this->lastPlayerAuthInputPitch){
186 $this->lastPlayerAuthInputYaw = $rawYaw;
187 $this->lastPlayerAuthInputPitch = $rawPitch;
189 $yaw = fmod($rawYaw, 360);
190 $pitch = fmod($rawPitch, 360);
195 $this->player->setRotation($yaw, $pitch);
198 $hasMoved = $this->lastPlayerAuthInputPosition ===
null || !$this->lastPlayerAuthInputPosition->equals($rawPos);
199 $newPos = $rawPos->subtract(0, 1.62, 0)->round(4);
201 if($this->forceMoveSync && $hasMoved){
202 $curPos = $this->player->getLocation();
204 if($newPos->distanceSquared($curPos) > 1){
205 $this->session->getLogger()->debug(
"Got outdated pre-teleport movement, received " . $newPos .
", expected " . $curPos);
211 $this->forceMoveSync =
false;
214 $inputFlags = $packet->getInputFlags();
215 if($inputFlags !== $this->lastPlayerAuthInputFlags){
216 $this->lastPlayerAuthInputFlags = $inputFlags;
219 if($this->player->isSneaking() === $sneaking){
222 $sprinting = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SPRINTING, PlayerAuthInputFlags::STOP_SPRINTING);
223 $swimming = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SWIMMING, PlayerAuthInputFlags::STOP_SWIMMING);
224 $gliding = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_GLIDING, PlayerAuthInputFlags::STOP_GLIDING);
225 $flying = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_FLYING, PlayerAuthInputFlags::STOP_FLYING);
227 ($sneaking !==
null && !$this->player->toggleSneak($sneaking)) |
228 ($sprinting !==
null && !$this->player->toggleSprint($sprinting)) |
229 ($swimming !==
null && !$this->player->toggleSwim($swimming)) |
230 ($gliding !==
null && !$this->player->toggleGlide($gliding)) |
231 ($flying !==
null && !$this->player->toggleFlight($flying));
232 if((
bool) $mismatch){
233 $this->player->sendData([$this->player]);
237 $this->player->jump();
240 $this->player->missSwing();
244 if(!$this->forceMoveSync && $hasMoved){
245 $this->lastPlayerAuthInputPosition = $rawPos;
247 $this->player->handleMovement($newPos);
250 $packetHandled =
true;
252 $blockActions = $packet->getBlockActions();
253 if($blockActions !==
null){
254 if(count($blockActions) > 100){
257 foreach(Utils::promoteKeys($blockActions) as $k => $blockAction){
258 $actionHandled =
false;
260 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(),
new BlockPosition(0, 0, 0), Facing::DOWN);
262 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
266 $packetHandled =
false;
267 $this->session->getLogger()->debug(
"Unhandled player block action at offset $k in PlayerAuthInputPacket");
272 $useItemTransaction = $packet->getItemInteractionData();
273 if($useItemTransaction !==
null){
274 if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
278 $this->inventoryManager->setCurrentItemStackRequestId($useItemTransaction->getRequestId());
279 $this->inventoryManager->addRawPredictedSlotChanges($useItemTransaction->getTransactionData()->getActions());
280 if(!$this->handleUseItemTransaction($useItemTransaction->getTransactionData())){
281 $packetHandled =
false;
282 $this->session->getLogger()->debug(
"Unhandled transaction in PlayerAuthInputPacket (type " . $useItemTransaction->getTransactionData()->getActionType() .
")");
284 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
286 $this->inventoryManager->setCurrentItemStackRequestId(
null);
289 $itemStackRequest = $packet->getItemStackRequest();
290 if($itemStackRequest !==
null){
291 $result = $this->handleSingleItemStackRequest($itemStackRequest);
295 return $packetHandled;
299 if($packet->actorRuntimeId !== $this->player->getId()){
301 return $packet->actorRuntimeId === ActorEvent::EATING_ITEM;
304 switch($packet->eventId){
305 case ActorEvent::EATING_ITEM:
306 $item = $this->player->getInventory()->getItemInHand();
310 $this->player->broadcastAnimation(
new ConsumingItemAnimation($this->player, $this->player->getInventory()->getItemInHand()));
322 if(count($packet->trData->getActions()) > 50){
325 if(count($packet->requestChangedSlots) > 10){
329 $this->inventoryManager->setCurrentItemStackRequestId($packet->requestId);
330 $this->inventoryManager->addRawPredictedSlotChanges($packet->trData->getActions());
333 $result = $this->handleNormalTransaction($packet->trData, $packet->requestId);
335 $this->session->getLogger()->debug(
"Mismatch transaction received");
336 $this->inventoryManager->requestSyncAll();
339 $result = $this->handleUseItemTransaction($packet->trData);
341 $result = $this->handleUseItemOnEntityTransaction($packet->trData);
343 $result = $this->handleReleaseItemTransaction($packet->trData);
346 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
352 foreach($packet->requestChangedSlots as $containerInfo){
353 foreach($containerInfo->getChangedSlotIndexes() as $netSlot){
355 $inventoryAndSlot = $this->inventoryManager->locateWindowAndSlot($windowId, $slot);
356 if($inventoryAndSlot !==
null){
357 $this->inventoryManager->onSlotChange($inventoryAndSlot[0], $inventoryAndSlot[1]);
362 $this->inventoryManager->setCurrentItemStackRequestId(
null);
366 private function executeInventoryTransaction(
InventoryTransaction $transaction,
int $requestId) :
bool{
367 $this->player->setUsingItem(
false);
369 $this->inventoryManager->setCurrentItemStackRequestId($requestId);
370 $this->inventoryManager->addTransactionPredictedSlotChanges($transaction);
374 $this->inventoryManager->requestSyncAll();
375 $logger = $this->session->getLogger();
376 $logger->debug(
"Invalid inventory transaction $requestId: " . $e->getMessage());
380 $this->session->getLogger()->debug(
"Inventory transaction $requestId cancelled by a plugin");
384 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
385 $this->inventoryManager->setCurrentItemStackRequestId(
null);
391 private function handleNormalTransaction(
NormalTransactionData $data,
int $itemStackRequestId) :
bool{
398 if($actionCount > 2){
399 if($actionCount > 5){
405 $this->session->getLogger()->debug(
"Ignoring normal inventory transaction with $actionCount actions (drop-item should have exactly 2 actions)");
410 $clientItemStack =
null;
411 $droppedCount =
null;
413 foreach($data->
getActions() as $networkInventoryAction){
414 if($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_WORLD && $networkInventoryAction->inventorySlot === NetworkInventoryAction::ACTION_MAGIC_SLOT_DROP_ITEM){
415 $droppedCount = $networkInventoryAction->newItem->getItemStack()->getCount();
416 if($droppedCount <= 0){
419 }elseif($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER && $networkInventoryAction->windowId === ContainerIds::INVENTORY){
421 $sourceSlot = $networkInventoryAction->inventorySlot;
422 $clientItemStack = $networkInventoryAction->oldItem->getItemStack();
424 $this->session->getLogger()->debug(
"Unexpected inventory action type $networkInventoryAction->sourceType in drop item transaction");
428 if($sourceSlot ===
null || $clientItemStack ===
null || $droppedCount ===
null){
429 $this->session->getLogger()->debug(
"Missing information in drop item transaction, need source slot, client item stack and dropped count");
433 $inventory = $this->player->getInventory();
435 if(!$inventory->slotExists($sourceSlot)){
439 $sourceSlotItem = $inventory->getItem($sourceSlot);
440 if($sourceSlotItem->getCount() < $droppedCount){
443 $serverItemStack = $this->session->getTypeConverter()->coreItemStackToNet($sourceSlotItem);
447 $serverItemStack->getId() !== $clientItemStack->getId() ||
448 $serverItemStack->getMeta() !== $clientItemStack->getMeta() ||
449 $serverItemStack->getCount() !== $clientItemStack->getCount() ||
450 $serverItemStack->getBlockRuntimeId() !== $clientItemStack->getBlockRuntimeId()
460 $droppedItem = $sourceSlotItem->pop($droppedCount);
463 $builder->getInventory($inventory)->setItem($sourceSlot, $sourceSlotItem);
467 return $this->executeInventoryTransaction($transaction, $itemStackRequestId);
471 $this->player->selectHotbarSlot($data->getHotbarSlot());
473 switch($data->getActionType()){
474 case UseItemTransactionData::ACTION_CLICK_BLOCK:
476 $clickPos = $data->getClickPosition();
477 $spamBug = ($this->lastRightClickData !==
null &&
478 microtime(
true) - $this->lastRightClickTime < 0.1 &&
479 $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
480 $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
481 $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001
484 $this->lastRightClickData = $data;
485 $this->lastRightClickTime = microtime(
true);
491 self::validateFacing($data->getFace());
493 $blockPos = $data->getBlockPosition();
494 $vBlockPos =
new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
495 $this->player->interactBlock($vBlockPos, $data->getFace(), $clickPos);
500 $this->syncBlocksNearby($vBlockPos, $data->getFace());
502 case UseItemTransactionData::ACTION_BREAK_BLOCK:
503 $blockPos = $data->getBlockPosition();
504 $vBlockPos =
new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
505 if(!$this->player->breakBlock($vBlockPos)){
506 $this->syncBlocksNearby($vBlockPos,
null);
509 case UseItemTransactionData::ACTION_CLICK_AIR:
510 if($this->player->isUsingItem()){
511 if(!$this->player->consumeHeldItem()){
512 $hungerAttr = $this->player->getAttributeMap()->get(Attribute::HUNGER) ??
throw new AssumptionFailedError();
513 $hungerAttr->markSynchronized(
false);
517 $this->player->useHeldItem();
527 private static function validateFacing(
int $facing) :
void{
528 if(!in_array($facing, Facing::ALL,
true)){
536 private function syncBlocksNearby(
Vector3 $blockPos, ?
int $face) :
void{
537 if($blockPos->distanceSquared($this->player->getLocation()) < 10000){
540 $sidePos = $blockPos->
getSide($face);
543 array_push($blocks, ...$sidePos->sidesArray());
545 $blocks[] = $blockPos;
547 foreach($this->player->getWorld()->createBlockUpdatePackets($blocks) as $packet){
548 $this->session->sendDataPacket($packet);
554 $target = $this->player->getWorld()->getEntity($data->getActorRuntimeId());
555 if($target ===
null){
559 $this->player->selectHotbarSlot($data->getHotbarSlot());
561 switch($data->getActionType()){
562 case UseItemOnEntityTransactionData::ACTION_INTERACT:
563 $this->player->interactEntity($target, $data->getClickPosition());
565 case UseItemOnEntityTransactionData::ACTION_ATTACK:
566 $this->player->attackEntity($target);
574 $this->player->selectHotbarSlot($data->getHotbarSlot());
576 if($data->getActionType() === ReleaseItemTransactionData::ACTION_RELEASE){
577 $this->player->releaseHeldItem();
600 $transaction = $executor->generateInventoryTransaction();
601 $result = $this->executeInventoryTransaction($transaction, $request->getRequestId());
604 $this->session->getLogger()->debug(
"ItemStackRequest #" . $request->getRequestId() .
" failed: " . $e->getMessage());
605 $this->session->getLogger()->debug(implode(
"\n", Utils::printableExceptionInfo($e)));
606 $this->inventoryManager->requestSyncAll();
610 return new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $request->getRequestId());
612 return $executor->buildItemStackResponse();
617 if(count($packet->getRequests()) > 80){
621 foreach($packet->getRequests() as $request){
622 $responses[] = $this->handleSingleItemStackRequest($request);
631 if($packet->windowId === ContainerIds::OFFHAND){
634 if($packet->windowId === ContainerIds::INVENTORY){
635 $this->inventoryManager->onClientSelectHotbarSlot($packet->hotbarSlot);
636 if(!$this->player->selectHotbarSlot($packet->hotbarSlot)){
637 $this->inventoryManager->syncSelectedHotbarSlot();
649 if($packet->action === InteractPacket::ACTION_MOUSEOVER){
657 $target = $this->player->getWorld()->getEntity($packet->targetActorRuntimeId);
658 if($target ===
null){
661 if($packet->action === InteractPacket::ACTION_OPEN_INVENTORY && $target === $this->player){
662 $this->inventoryManager->onClientOpenMainInventory();
669 return $this->player->pickBlock(
new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ()), $packet->addUserData);
673 return $this->player->pickEntity($packet->actorUniqueId);
677 return $this->handlePlayerActionFromData($packet->action, $packet->blockPosition, $packet->face);
680 private function handlePlayerActionFromData(
int $action,
BlockPosition $blockPosition,
int $face) :
bool{
681 $pos =
new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
684 case PlayerAction::START_BREAK:
685 self::validateFacing($face);
686 if(!$this->player->attackBlock($pos, $face)){
687 $this->syncBlocksNearby($pos, $face);
692 case PlayerAction::ABORT_BREAK:
693 case PlayerAction::STOP_BREAK:
694 $this->player->stopBreakBlock($pos);
696 case PlayerAction::START_SLEEPING:
699 case PlayerAction::STOP_SLEEPING:
700 $this->player->stopSleep();
702 case PlayerAction::CRACK_BREAK:
703 self::validateFacing($face);
704 $this->player->continueBreakBlock($pos, $face);
706 case PlayerAction::INTERACT_BLOCK:
708 case PlayerAction::CREATIVE_PLAYER_DESTROY_BLOCK:
711 case PlayerAction::START_ITEM_USE_ON:
712 case PlayerAction::STOP_ITEM_USE_ON:
716 $this->session->getLogger()->debug(
"Unhandled/unknown player action type " . $action);
720 $this->player->setUsingItem(
false);
734 $this->inventoryManager->onClientRemoveWindow($packet->windowId);
743 $pos =
new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ());
744 if($pos->distanceSquared($this->player->getLocation()) > 10000){
748 $block = $this->player->getLocation()->getWorld()->getBlock($pos);
749 $nbt = $packet->nbt->getRoot();
753 $frontTextTag = $nbt->getTag(Sign::TAG_FRONT_TEXT);
755 throw new PacketHandlingException(
"Invalid tag type " . get_debug_type($frontTextTag) .
" for tag \"" . Sign::TAG_FRONT_TEXT .
"\" in sign update data");
757 $textBlobTag = $frontTextTag->getTag(Sign::TAG_TEXT_BLOB);
759 throw new PacketHandlingException(
"Invalid tag type " . get_debug_type($textBlobTag) .
" for tag \"" . Sign::TAG_TEXT_BLOB .
"\" in sign update data");
763 $text = SignText::fromBlob($textBlobTag->getValue());
764 }
catch(\InvalidArgumentException $e){
765 throw PacketHandlingException::wrap($e,
"Invalid sign text update");
769 if(!$block->updateText($this->player, $text)){
770 foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
771 $this->session->sendDataPacket($updatePacket);
774 }
catch(\UnexpectedValueException $e){
775 throw PacketHandlingException::wrap($e);
789 $gameMode = $this->session->getTypeConverter()->protocolGameModeToCore($packet->gamemode);
790 if($gameMode !== $this->player->getGamemode()){
792 $this->session->syncGameMode($this->player->getGamemode(),
true);
806 $this->player->setViewDistance($packet->radius);
820 if(str_starts_with($packet->command,
'/')){
821 $this->player->chat($packet->command);
832 if($packet->skin->getFullSkinId() === $this->lastRequestedFullSkinId){
835 $this->session->getLogger()->debug(
"Refused duplicate skin change request");
838 $this->lastRequestedFullSkinId = $packet->skin->getFullSkinId();
840 $this->session->getLogger()->debug(
"Processing skin change request");
842 $skin = $this->session->getTypeConverter()->getSkinAdapter()->fromSkinData($packet->skin);
844 throw PacketHandlingException::wrap($e,
"Invalid skin in PlayerSkinPacket");
846 return $this->player->changeSkin($skin, $packet->newSkinName, $packet->oldSkinName);
856 private function checkBookText(
string $string,
string $fieldName,
int $softLimit,
int $hardLimit,
bool &$cancel) :
string{
857 if(strlen($string) > $hardLimit){
858 throw new PacketHandlingException(sprintf(
"Book %s must be at most %d bytes, but have %d bytes", $fieldName, $hardLimit, strlen($string)));
861 $result = TextFormat::clean($string,
false);
863 if(strlen($result) > $softLimit * 4 || mb_strlen($result,
'UTF-8') > $softLimit){
865 $this->session->getLogger()->debug(
"Cancelled book edit due to $fieldName exceeded soft limit of $softLimit chars");
872 $inventory = $this->player->getInventory();
873 if(!$inventory->slotExists($packet->inventorySlot)){
877 $oldBook = $inventory->getItem($packet->inventorySlot);
882 $newBook = clone $oldBook;
885 switch($packet->type){
886 case BookEditPacket::TYPE_REPLACE_PAGE:
887 $text = self::checkBookText($packet->text,
"page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
888 $newBook->setPageText($packet->pageNumber, $text);
889 $modifiedPages[] = $packet->pageNumber;
891 case BookEditPacket::TYPE_ADD_PAGE:
892 if(!$newBook->pageExists($packet->pageNumber)){
897 $text = self::checkBookText($packet->text,
"page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
898 $newBook->insertPage($packet->pageNumber, $text);
899 $modifiedPages[] = $packet->pageNumber;
901 case BookEditPacket::TYPE_DELETE_PAGE:
902 if(!$newBook->pageExists($packet->pageNumber)){
905 $newBook->deletePage($packet->pageNumber);
906 $modifiedPages[] = $packet->pageNumber;
908 case BookEditPacket::TYPE_SWAP_PAGES:
909 if(!$newBook->pageExists($packet->pageNumber) || !$newBook->pageExists($packet->secondaryPageNumber)){
911 $newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber));
913 $newBook->swapPages($packet->pageNumber, $packet->secondaryPageNumber);
914 $modifiedPages = [$packet->pageNumber, $packet->secondaryPageNumber];
916 case BookEditPacket::TYPE_SIGN_BOOK:
917 $title = self::checkBookText($packet->title,
"title", 16, Limits::INT16_MAX, $cancel);
919 $author = self::checkBookText($packet->author,
"author", 256, Limits::INT16_MAX, $cancel);
921 $newBook = VanillaItems::WRITTEN_BOOK()
922 ->setPages($oldBook->getPages())
925 ->setGeneration(WrittenBook::GENERATION_ORIGINAL);
932 $action = match($packet->type){
933 BookEditPacket::TYPE_REPLACE_PAGE => PlayerEditBookEvent::ACTION_REPLACE_PAGE,
934 BookEditPacket::TYPE_ADD_PAGE => PlayerEditBookEvent::ACTION_ADD_PAGE,
935 BookEditPacket::TYPE_DELETE_PAGE => PlayerEditBookEvent::ACTION_DELETE_PAGE,
936 BookEditPacket::TYPE_SWAP_PAGES => PlayerEditBookEvent::ACTION_SWAP_PAGES,
937 BookEditPacket::TYPE_SIGN_BOOK => PlayerEditBookEvent::ACTION_SIGN_BOOK,
945 $oldPageCount = count($oldBook->getPages());
946 $newPageCount = count($newBook->getPages());
947 if(($newPageCount > $oldPageCount && $newPageCount > 50)){
948 $this->session->getLogger()->debug(
"Cancelled book edit due to adding too many pages (new page count would be $newPageCount)");
952 $event =
new PlayerEditBookEvent($this->player, $oldBook, $newBook, $action, $modifiedPages);
958 if($event->isCancelled()){
962 $this->player->getInventory()->setItem($packet->inventorySlot, $event->getNewBook());
968 if($packet->cancelReason !==
null){
970 return $this->player->onFormSubmit($packet->formId,
null);
971 }elseif($packet->formData !==
null){
973 $responseData = json_decode($packet->formData,
true, self::MAX_FORM_RESPONSE_DEPTH, JSON_THROW_ON_ERROR);
974 }
catch(\JsonException $e){
975 throw PacketHandlingException::wrap($e,
"Failed to decode form response data");
977 return $this->player->onFormSubmit($packet->formId, $responseData);
979 throw new PacketHandlingException(
"Expected either formData or cancelReason to be set in ModalFormResponsePacket");
992 $pos = $packet->blockPosition;
993 $chunkX = $pos->getX() >> Chunk::COORD_BIT_SIZE;
994 $chunkZ = $pos->getZ() >> Chunk::COORD_BIT_SIZE;
995 $world = $this->player->getWorld();
996 if(!$world->isChunkLoaded($chunkX, $chunkZ) || $world->isChunkLocked($chunkX, $chunkZ)){
1000 $lectern = $world->getBlockAt($pos->getX(), $pos->getY(), $pos->getZ());
1001 if($lectern instanceof
Lectern && $this->player->canInteract($lectern->getPosition(), 15)){
1002 if(!$lectern->onPageTurn($packet->page)){
1003 $this->syncBlocksNearby($lectern->getPosition(),
null);
1025 public function handleEmote(
EmotePacket $packet) :
bool{
1026 $this->player->emote($packet->getEmoteId());