131 private const MAX_FORM_RESPONSE_DEPTH = 2;
133 protected float $lastRightClickTime = 0.0;
136 protected ?
Vector3 $lastPlayerAuthInputPosition =
null;
137 protected ?
float $lastPlayerAuthInputYaw =
null;
138 protected ?
float $lastPlayerAuthInputPitch =
null;
139 protected ?
BitSet $lastPlayerAuthInputFlags =
null;
141 public bool $forceMoveSync =
false;
143 protected ?
string $lastRequestedFullSkinId =
null;
145 public function __construct(
151 public function handleText(
TextPacket $packet) :
bool{
152 if($packet->type === TextPacket::TYPE_CHAT){
153 return $this->player->chat($packet->message);
165 private function resolveOnOffInputFlags(
BitSet $inputFlags,
int $startFlag,
int $stopFlag) : ?
bool{
166 $enabled = $inputFlags->get($startFlag);
167 $disabled = $inputFlags->get($stopFlag);
168 if($enabled !== $disabled){
176 $rawPos = $packet->getPosition();
177 $rawYaw = $packet->getYaw();
178 $rawPitch = $packet->getPitch();
179 foreach([$rawPos->x, $rawPos->y, $rawPos->z, $rawYaw, $packet->getHeadYaw(), $rawPitch] as $float){
180 if(is_infinite($float) || is_nan($float)){
181 $this->session->getLogger()->debug(
"Invalid movement received, contains NAN/INF components");
186 if($rawYaw !== $this->lastPlayerAuthInputYaw || $rawPitch !== $this->lastPlayerAuthInputPitch){
187 $this->lastPlayerAuthInputYaw = $rawYaw;
188 $this->lastPlayerAuthInputPitch = $rawPitch;
190 $yaw = fmod($rawYaw, 360);
191 $pitch = fmod($rawPitch, 360);
196 $this->player->setRotation($yaw, $pitch);
199 $hasMoved = $this->lastPlayerAuthInputPosition ===
null || !$this->lastPlayerAuthInputPosition->equals($rawPos);
200 $newPos = $rawPos->subtract(0, 1.62, 0)->round(4);
202 if($this->forceMoveSync && $hasMoved){
203 $curPos = $this->player->getLocation();
205 if($newPos->distanceSquared($curPos) > 1){
206 $this->session->getLogger()->debug(
"Got outdated pre-teleport movement, received " . $newPos .
", expected " . $curPos);
212 $this->forceMoveSync =
false;
215 $inputFlags = $packet->getInputFlags();
216 if($inputFlags !== $this->lastPlayerAuthInputFlags){
217 $this->lastPlayerAuthInputFlags = $inputFlags;
220 if($this->player->isSneaking() === $sneaking){
223 $sprinting = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SPRINTING, PlayerAuthInputFlags::STOP_SPRINTING);
224 $swimming = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SWIMMING, PlayerAuthInputFlags::STOP_SWIMMING);
225 $gliding = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_GLIDING, PlayerAuthInputFlags::STOP_GLIDING);
226 $flying = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_FLYING, PlayerAuthInputFlags::STOP_FLYING);
228 ($sneaking !==
null && !$this->player->toggleSneak($sneaking)) |
229 ($sprinting !==
null && !$this->player->toggleSprint($sprinting)) |
230 ($swimming !==
null && !$this->player->toggleSwim($swimming)) |
231 ($gliding !==
null && !$this->player->toggleGlide($gliding)) |
232 ($flying !==
null && !$this->player->toggleFlight($flying));
233 if((
bool) $mismatch){
234 $this->player->sendData([$this->player]);
238 $this->player->jump();
241 $this->player->missSwing();
245 if(!$this->forceMoveSync && $hasMoved){
246 $this->lastPlayerAuthInputPosition = $rawPos;
248 $this->player->handleMovement($newPos);
251 $packetHandled =
true;
253 $blockActions = $packet->getBlockActions();
254 if($blockActions !==
null){
255 if(count($blockActions) > 100){
258 foreach(Utils::promoteKeys($blockActions) as $k => $blockAction){
259 $actionHandled =
false;
261 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(),
new BlockPosition(0, 0, 0), Facing::DOWN);
263 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
267 $packetHandled =
false;
268 $this->session->getLogger()->debug(
"Unhandled player block action at offset $k in PlayerAuthInputPacket");
273 $useItemTransaction = $packet->getItemInteractionData();
274 if($useItemTransaction !==
null){
275 if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
279 $this->inventoryManager->setCurrentItemStackRequestId($useItemTransaction->getRequestId());
280 $this->inventoryManager->addRawPredictedSlotChanges($useItemTransaction->getTransactionData()->getActions());
281 if(!$this->handleUseItemTransaction($useItemTransaction->getTransactionData())){
282 $packetHandled =
false;
283 $this->session->getLogger()->debug(
"Unhandled transaction in PlayerAuthInputPacket (type " . $useItemTransaction->getTransactionData()->getActionType() .
")");
285 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
287 $this->inventoryManager->setCurrentItemStackRequestId(
null);
290 $itemStackRequest = $packet->getItemStackRequest();
291 if($itemStackRequest !==
null){
292 $result = $this->handleSingleItemStackRequest($itemStackRequest);
296 return $packetHandled;
304 if($packet->actorRuntimeId !== $this->player->getId()){
306 return $packet->actorRuntimeId === ActorEvent::EATING_ITEM;
309 switch($packet->eventId){
310 case ActorEvent::EATING_ITEM:
311 $item = $this->player->getInventory()->getItemInHand();
315 $this->player->broadcastAnimation(
new ConsumingItemAnimation($this->player, $this->player->getInventory()->getItemInHand()));
327 if(count($packet->trData->getActions()) > 50){
330 if(count($packet->requestChangedSlots) > 10){
334 $this->inventoryManager->setCurrentItemStackRequestId($packet->requestId);
335 $this->inventoryManager->addRawPredictedSlotChanges($packet->trData->getActions());
338 $result = $this->handleNormalTransaction($packet->trData, $packet->requestId);
340 $this->session->getLogger()->debug(
"Mismatch transaction received");
341 $this->inventoryManager->requestSyncAll();
344 $result = $this->handleUseItemTransaction($packet->trData);
346 $result = $this->handleUseItemOnEntityTransaction($packet->trData);
348 $result = $this->handleReleaseItemTransaction($packet->trData);
351 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
357 foreach($packet->requestChangedSlots as $containerInfo){
358 foreach($containerInfo->getChangedSlotIndexes() as $netSlot){
360 $inventoryAndSlot = $this->inventoryManager->locateWindowAndSlot($windowId, $slot);
361 if($inventoryAndSlot !==
null){
362 $this->inventoryManager->onSlotChange($inventoryAndSlot[0], $inventoryAndSlot[1]);
367 $this->inventoryManager->setCurrentItemStackRequestId(
null);
371 private function executeInventoryTransaction(
InventoryTransaction $transaction,
int $requestId) :
bool{
372 $this->player->setUsingItem(
false);
374 $this->inventoryManager->setCurrentItemStackRequestId($requestId);
375 $this->inventoryManager->addTransactionPredictedSlotChanges($transaction);
379 $this->inventoryManager->requestSyncAll();
380 $logger = $this->session->getLogger();
381 $logger->debug(
"Invalid inventory transaction $requestId: " . $e->getMessage());
385 $this->session->getLogger()->debug(
"Inventory transaction $requestId cancelled by a plugin");
389 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
390 $this->inventoryManager->setCurrentItemStackRequestId(
null);
396 private function handleNormalTransaction(
NormalTransactionData $data,
int $itemStackRequestId) :
bool{
403 if($actionCount > 2){
404 if($actionCount > 5){
410 $this->session->getLogger()->debug(
"Ignoring normal inventory transaction with $actionCount actions (drop-item should have exactly 2 actions)");
415 $clientItemStack =
null;
416 $droppedCount =
null;
418 foreach($data->
getActions() as $networkInventoryAction){
419 if($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_WORLD && $networkInventoryAction->inventorySlot == NetworkInventoryAction::ACTION_MAGIC_SLOT_DROP_ITEM){
420 $droppedCount = $networkInventoryAction->newItem->getItemStack()->getCount();
421 if($droppedCount <= 0){
424 }elseif($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER && $networkInventoryAction->windowId === ContainerIds::INVENTORY){
426 $sourceSlot = $networkInventoryAction->inventorySlot;
427 $clientItemStack = $networkInventoryAction->oldItem->getItemStack();
429 $this->session->getLogger()->debug(
"Unexpected inventory action type $networkInventoryAction->sourceType in drop item transaction");
433 if($sourceSlot ===
null || $clientItemStack ===
null || $droppedCount ===
null){
434 $this->session->getLogger()->debug(
"Missing information in drop item transaction, need source slot, client item stack and dropped count");
438 $inventory = $this->player->getInventory();
440 if(!$inventory->slotExists($sourceSlot)){
444 $sourceSlotItem = $inventory->getItem($sourceSlot);
445 if($sourceSlotItem->getCount() < $droppedCount){
448 $serverItemStack = $this->session->getTypeConverter()->coreItemStackToNet($sourceSlotItem);
452 $serverItemStack->getId() !== $clientItemStack->getId() ||
453 $serverItemStack->getMeta() !== $clientItemStack->getMeta() ||
454 $serverItemStack->getCount() !== $clientItemStack->getCount() ||
455 $serverItemStack->getBlockRuntimeId() !== $clientItemStack->getBlockRuntimeId()
465 $droppedItem = $sourceSlotItem->pop($droppedCount);
468 $builder->getInventory($inventory)->setItem($sourceSlot, $sourceSlotItem);
472 return $this->executeInventoryTransaction($transaction, $itemStackRequestId);
476 $this->player->selectHotbarSlot($data->getHotbarSlot());
478 switch($data->getActionType()){
479 case UseItemTransactionData::ACTION_CLICK_BLOCK:
481 $clickPos = $data->getClickPosition();
482 $spamBug = ($this->lastRightClickData !==
null &&
483 microtime(
true) - $this->lastRightClickTime < 0.1 &&
484 $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
485 $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
486 $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001
489 $this->lastRightClickData = $data;
490 $this->lastRightClickTime = microtime(
true);
496 self::validateFacing($data->getFace());
498 $blockPos = $data->getBlockPosition();
499 $vBlockPos =
new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
500 $this->player->interactBlock($vBlockPos, $data->getFace(), $clickPos);
505 $this->syncBlocksNearby($vBlockPos, $data->getFace());
507 case UseItemTransactionData::ACTION_BREAK_BLOCK:
508 $blockPos = $data->getBlockPosition();
509 $vBlockPos =
new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
510 if(!$this->player->breakBlock($vBlockPos)){
511 $this->syncBlocksNearby($vBlockPos,
null);
514 case UseItemTransactionData::ACTION_CLICK_AIR:
515 if($this->player->isUsingItem()){
516 if(!$this->player->consumeHeldItem()){
517 $hungerAttr = $this->player->getAttributeMap()->get(Attribute::HUNGER) ??
throw new AssumptionFailedError();
518 $hungerAttr->markSynchronized(
false);
522 $this->player->useHeldItem();
532 private static function validateFacing(
int $facing) :
void{
533 if(!in_array($facing, Facing::ALL,
true)){
541 private function syncBlocksNearby(
Vector3 $blockPos, ?
int $face) :
void{
542 if($blockPos->distanceSquared($this->player->getLocation()) < 10000){
545 $sidePos = $blockPos->
getSide($face);
548 array_push($blocks, ...$sidePos->sidesArray());
550 $blocks[] = $blockPos;
552 foreach($this->player->getWorld()->createBlockUpdatePackets($blocks) as $packet){
553 $this->session->sendDataPacket($packet);
559 $target = $this->player->getWorld()->getEntity($data->getActorRuntimeId());
560 if($target ===
null){
564 $this->player->selectHotbarSlot($data->getHotbarSlot());
566 switch($data->getActionType()){
567 case UseItemOnEntityTransactionData::ACTION_INTERACT:
568 $this->player->interactEntity($target, $data->getClickPosition());
570 case UseItemOnEntityTransactionData::ACTION_ATTACK:
571 $this->player->attackEntity($target);
579 $this->player->selectHotbarSlot($data->getHotbarSlot());
581 if($data->getActionType() == ReleaseItemTransactionData::ACTION_RELEASE){
582 $this->player->releaseHeldItem();
605 $transaction = $executor->generateInventoryTransaction();
606 $result = $this->executeInventoryTransaction($transaction, $request->getRequestId());
609 $this->session->getLogger()->debug(
"ItemStackRequest #" . $request->getRequestId() .
" failed: " . $e->getMessage());
610 $this->session->getLogger()->debug(implode(
"\n", Utils::printableExceptionInfo($e)));
611 $this->inventoryManager->requestSyncAll();
615 return new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $request->getRequestId());
617 return $executor->buildItemStackResponse();
622 if(count($packet->getRequests()) > 80){
626 foreach($packet->getRequests() as $request){
627 $responses[] = $this->handleSingleItemStackRequest($request);
636 if($packet->windowId === ContainerIds::OFFHAND){
639 if($packet->windowId === ContainerIds::INVENTORY){
640 $this->inventoryManager->onClientSelectHotbarSlot($packet->hotbarSlot);
641 if(!$this->player->selectHotbarSlot($packet->hotbarSlot)){
642 $this->inventoryManager->syncSelectedHotbarSlot();
654 if($packet->action === InteractPacket::ACTION_MOUSEOVER){
662 $target = $this->player->getWorld()->getEntity($packet->targetActorRuntimeId);
663 if($target ===
null){
666 if($packet->action === InteractPacket::ACTION_OPEN_INVENTORY && $target === $this->player){
667 $this->inventoryManager->onClientOpenMainInventory();
674 return $this->player->pickBlock(
new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ()), $packet->addUserData);
678 return $this->player->pickEntity($packet->actorUniqueId);
682 return $this->handlePlayerActionFromData($packet->action, $packet->blockPosition, $packet->face);
685 private function handlePlayerActionFromData(
int $action,
BlockPosition $blockPosition,
int $face) :
bool{
686 $pos =
new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
689 case PlayerAction::START_BREAK:
690 self::validateFacing($face);
691 if(!$this->player->attackBlock($pos, $face)){
692 $this->syncBlocksNearby($pos, $face);
697 case PlayerAction::ABORT_BREAK:
698 case PlayerAction::STOP_BREAK:
699 $this->player->stopBreakBlock($pos);
701 case PlayerAction::START_SLEEPING:
704 case PlayerAction::STOP_SLEEPING:
705 $this->player->stopSleep();
707 case PlayerAction::CRACK_BREAK:
708 self::validateFacing($face);
709 $this->player->continueBreakBlock($pos, $face);
711 case PlayerAction::INTERACT_BLOCK:
713 case PlayerAction::CREATIVE_PLAYER_DESTROY_BLOCK:
716 case PlayerAction::START_ITEM_USE_ON:
717 case PlayerAction::STOP_ITEM_USE_ON:
721 $this->session->getLogger()->debug(
"Unhandled/unknown player action type " . $action);
725 $this->player->setUsingItem(
false);
739 $this->inventoryManager->onClientRemoveWindow($packet->windowId);
748 $pos =
new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ());
749 if($pos->distanceSquared($this->player->getLocation()) > 10000){
753 $block = $this->player->getLocation()->getWorld()->getBlock($pos);
754 $nbt = $packet->nbt->getRoot();
758 $frontTextTag = $nbt->getTag(Sign::TAG_FRONT_TEXT);
760 throw new PacketHandlingException(
"Invalid tag type " . get_debug_type($frontTextTag) .
" for tag \"" . Sign::TAG_FRONT_TEXT .
"\" in sign update data");
762 $textBlobTag = $frontTextTag->getTag(Sign::TAG_TEXT_BLOB);
764 throw new PacketHandlingException(
"Invalid tag type " . get_debug_type($textBlobTag) .
" for tag \"" . Sign::TAG_TEXT_BLOB .
"\" in sign update data");
768 $text = SignText::fromBlob($textBlobTag->getValue());
769 }
catch(\InvalidArgumentException $e){
770 throw PacketHandlingException::wrap($e,
"Invalid sign text update");
774 if(!$block->updateText($this->player, $text)){
775 foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
776 $this->session->sendDataPacket($updatePacket);
779 }
catch(\UnexpectedValueException $e){
780 throw PacketHandlingException::wrap($e);
794 $gameMode = $this->session->getTypeConverter()->protocolGameModeToCore($packet->gamemode);
795 if($gameMode !== $this->player->getGamemode()){
797 $this->session->syncGameMode($this->player->getGamemode(),
true);
811 $this->player->setViewDistance($packet->radius);
825 if(str_starts_with($packet->command,
'/')){
826 $this->player->chat($packet->command);
837 if($packet->skin->getFullSkinId() === $this->lastRequestedFullSkinId){
840 $this->session->getLogger()->debug(
"Refused duplicate skin change request");
843 $this->lastRequestedFullSkinId = $packet->skin->getFullSkinId();
845 $this->session->getLogger()->debug(
"Processing skin change request");
847 $skin = $this->session->getTypeConverter()->getSkinAdapter()->fromSkinData($packet->skin);
849 throw PacketHandlingException::wrap($e,
"Invalid skin in PlayerSkinPacket");
851 return $this->player->changeSkin($skin, $packet->newSkinName, $packet->oldSkinName);
861 private function checkBookText(
string $string,
string $fieldName,
int $softLimit,
int $hardLimit,
bool &$cancel) :
string{
862 if(strlen($string) > $hardLimit){
863 throw new PacketHandlingException(sprintf(
"Book %s must be at most %d bytes, but have %d bytes", $fieldName, $hardLimit, strlen($string)));
866 $result = TextFormat::clean($string,
false);
868 if(strlen($result) > $softLimit * 4 || mb_strlen($result,
'UTF-8') > $softLimit){
870 $this->session->getLogger()->debug(
"Cancelled book edit due to $fieldName exceeded soft limit of $softLimit chars");
877 $inventory = $this->player->getInventory();
878 if(!$inventory->slotExists($packet->inventorySlot)){
882 $oldBook = $inventory->getItem($packet->inventorySlot);
887 $newBook = clone $oldBook;
890 switch($packet->type){
891 case BookEditPacket::TYPE_REPLACE_PAGE:
892 $text = self::checkBookText($packet->text,
"page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
893 $newBook->setPageText($packet->pageNumber, $text);
894 $modifiedPages[] = $packet->pageNumber;
896 case BookEditPacket::TYPE_ADD_PAGE:
897 if(!$newBook->pageExists($packet->pageNumber)){
902 $text = self::checkBookText($packet->text,
"page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
903 $newBook->insertPage($packet->pageNumber, $text);
904 $modifiedPages[] = $packet->pageNumber;
906 case BookEditPacket::TYPE_DELETE_PAGE:
907 if(!$newBook->pageExists($packet->pageNumber)){
910 $newBook->deletePage($packet->pageNumber);
911 $modifiedPages[] = $packet->pageNumber;
913 case BookEditPacket::TYPE_SWAP_PAGES:
914 if(!$newBook->pageExists($packet->pageNumber) || !$newBook->pageExists($packet->secondaryPageNumber)){
916 $newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber));
918 $newBook->swapPages($packet->pageNumber, $packet->secondaryPageNumber);
919 $modifiedPages = [$packet->pageNumber, $packet->secondaryPageNumber];
921 case BookEditPacket::TYPE_SIGN_BOOK:
922 $title = self::checkBookText($packet->title,
"title", 16, Limits::INT16_MAX, $cancel);
924 $author = self::checkBookText($packet->author,
"author", 256, Limits::INT16_MAX, $cancel);
926 $newBook = VanillaItems::WRITTEN_BOOK()
927 ->setPages($oldBook->getPages())
930 ->setGeneration(WrittenBook::GENERATION_ORIGINAL);
937 $action = match($packet->type){
938 BookEditPacket::TYPE_REPLACE_PAGE => PlayerEditBookEvent::ACTION_REPLACE_PAGE,
939 BookEditPacket::TYPE_ADD_PAGE => PlayerEditBookEvent::ACTION_ADD_PAGE,
940 BookEditPacket::TYPE_DELETE_PAGE => PlayerEditBookEvent::ACTION_DELETE_PAGE,
941 BookEditPacket::TYPE_SWAP_PAGES => PlayerEditBookEvent::ACTION_SWAP_PAGES,
942 BookEditPacket::TYPE_SIGN_BOOK => PlayerEditBookEvent::ACTION_SIGN_BOOK,
950 $oldPageCount = count($oldBook->getPages());
951 $newPageCount = count($newBook->getPages());
952 if(($newPageCount > $oldPageCount && $newPageCount > 50)){
953 $this->session->getLogger()->debug(
"Cancelled book edit due to adding too many pages (new page count would be $newPageCount)");
957 $event =
new PlayerEditBookEvent($this->player, $oldBook, $newBook, $action, $modifiedPages);
963 if($event->isCancelled()){
967 $this->player->getInventory()->setItem($packet->inventorySlot, $event->getNewBook());
973 if($packet->cancelReason !==
null){
975 return $this->player->onFormSubmit($packet->formId,
null);
976 }elseif($packet->formData !==
null){
978 $responseData = json_decode($packet->formData,
true, self::MAX_FORM_RESPONSE_DEPTH, JSON_THROW_ON_ERROR);
979 }
catch(\JsonException $e){
980 throw PacketHandlingException::wrap($e,
"Failed to decode form response data");
982 return $this->player->onFormSubmit($packet->formId, $responseData);
984 throw new PacketHandlingException(
"Expected either formData or cancelReason to be set in ModalFormResponsePacket");
997 $pos = $packet->blockPosition;
998 $chunkX = $pos->getX() >> Chunk::COORD_BIT_SIZE;
999 $chunkZ = $pos->getZ() >> Chunk::COORD_BIT_SIZE;
1000 $world = $this->player->getWorld();
1001 if(!$world->isChunkLoaded($chunkX, $chunkZ) || $world->isChunkLocked($chunkX, $chunkZ)){
1005 $lectern = $world->getBlockAt($pos->getX(), $pos->getY(), $pos->getZ());
1006 if($lectern instanceof
Lectern && $this->player->canInteract($lectern->getPosition(), 15)){
1007 if(!$lectern->onPageTurn($packet->page)){
1008 $this->syncBlocksNearby($lectern->getPosition(),
null);
1030 public function handleEmote(
EmotePacket $packet) :
bool{
1031 $this->player->emote($packet->getEmoteId());