PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
InGamePacketHandler.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\handler;
25
109use function array_push;
110use function count;
111use function fmod;
112use function get_debug_type;
113use function implode;
114use function in_array;
115use function is_infinite;
116use function is_nan;
117use function json_decode;
118use function max;
119use function mb_strlen;
120use function microtime;
121use function sprintf;
122use function str_starts_with;
123use function strlen;
124use const JSON_THROW_ON_ERROR;
125
130 private const MAX_FORM_RESPONSE_DEPTH = 2; //modal/simple will be 1, custom forms 2 - they will never contain anything other than string|int|float|bool|null
131
132 protected float $lastRightClickTime = 0.0;
133 protected ?UseItemTransactionData $lastRightClickData = null;
134
135 protected ?Vector3 $lastPlayerAuthInputPosition = null;
136 protected ?float $lastPlayerAuthInputYaw = null;
137 protected ?float $lastPlayerAuthInputPitch = null;
138 protected ?int $lastPlayerAuthInputFlags = null;
139
140 public bool $forceMoveSync = false;
141
142 protected ?string $lastRequestedFullSkinId = null;
143
144 public function __construct(
145 private Player $player,
146 private NetworkSession $session,
147 private InventoryManager $inventoryManager
148 ){}
149
150 public function handleText(TextPacket $packet) : bool{
151 if($packet->type === TextPacket::TYPE_CHAT){
152 return $this->player->chat($packet->message);
153 }
154
155 return false;
156 }
157
158 public function handleMovePlayer(MovePlayerPacket $packet) : bool{
159 //The client sends this every time it lands on the ground, even when using PlayerAuthInputPacket.
160 //Silence the debug spam that this causes.
161 return true;
162 }
163
164 private function resolveOnOffInputFlags(int $inputFlags, int $startFlag, int $stopFlag) : ?bool{
165 $enabled = ($inputFlags & (1 << $startFlag)) !== 0;
166 $disabled = ($inputFlags & (1 << $stopFlag)) !== 0;
167 if($enabled !== $disabled){
168 return $enabled;
169 }
170 //neither flag was set, or both were set
171 return null;
172 }
173
174 public function handlePlayerAuthInput(PlayerAuthInputPacket $packet) : bool{
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");
181 return false;
182 }
183 }
184
185 if($rawYaw !== $this->lastPlayerAuthInputYaw || $rawPitch !== $this->lastPlayerAuthInputPitch){
186 $this->lastPlayerAuthInputYaw = $rawYaw;
187 $this->lastPlayerAuthInputPitch = $rawPitch;
188
189 $yaw = fmod($rawYaw, 360);
190 $pitch = fmod($rawPitch, 360);
191 if($yaw < 0){
192 $yaw += 360;
193 }
194
195 $this->player->setRotation($yaw, $pitch);
196 }
197
198 $hasMoved = $this->lastPlayerAuthInputPosition === null || !$this->lastPlayerAuthInputPosition->equals($rawPos);
199 $newPos = $rawPos->subtract(0, 1.62, 0)->round(4);
200
201 if($this->forceMoveSync && $hasMoved){
202 $curPos = $this->player->getLocation();
203
204 if($newPos->distanceSquared($curPos) > 1){ //Tolerate up to 1 block to avoid problems with client-sided physics when spawning in blocks
205 $this->session->getLogger()->debug("Got outdated pre-teleport movement, received " . $newPos . ", expected " . $curPos);
206 //Still getting movements from before teleport, ignore them
207 return true;
208 }
209
210 // Once we get a movement within a reasonable distance, treat it as a teleport ACK and remove position lock
211 $this->forceMoveSync = false;
212 }
213
214 $inputFlags = $packet->getInputFlags();
215 if($inputFlags !== $this->lastPlayerAuthInputFlags){
216 $this->lastPlayerAuthInputFlags = $inputFlags;
217
218 $sneaking = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SNEAKING, PlayerAuthInputFlags::STOP_SNEAKING);
219 $sprinting = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SPRINTING, PlayerAuthInputFlags::STOP_SPRINTING);
220 $swimming = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_SWIMMING, PlayerAuthInputFlags::STOP_SWIMMING);
221 $gliding = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_GLIDING, PlayerAuthInputFlags::STOP_GLIDING);
222 $flying = $this->resolveOnOffInputFlags($inputFlags, PlayerAuthInputFlags::START_FLYING, PlayerAuthInputFlags::STOP_FLYING);
223 $mismatch =
224 ($sneaking !== null && !$this->player->toggleSneak($sneaking)) |
225 ($sprinting !== null && !$this->player->toggleSprint($sprinting)) |
226 ($swimming !== null && !$this->player->toggleSwim($swimming)) |
227 ($gliding !== null && !$this->player->toggleGlide($gliding)) |
228 ($flying !== null && !$this->player->toggleFlight($flying));
229 if((bool) $mismatch){
230 $this->player->sendData([$this->player]);
231 }
232
233 if($packet->hasFlag(PlayerAuthInputFlags::START_JUMPING)){
234 $this->player->jump();
235 }
236 if($packet->hasFlag(PlayerAuthInputFlags::MISSED_SWING)){
237 $this->player->missSwing();
238 }
239 }
240
241 if(!$this->forceMoveSync && $hasMoved){
242 $this->lastPlayerAuthInputPosition = $rawPos;
243 //TODO: this packet has WAYYYYY more useful information that we're not using
244 $this->player->handleMovement($newPos);
245 }
246
247 $packetHandled = true;
248
249 $blockActions = $packet->getBlockActions();
250 if($blockActions !== null){
251 if(count($blockActions) > 100){
252 throw new PacketHandlingException("Too many block actions in PlayerAuthInputPacket");
253 }
254 foreach($blockActions as $k => $blockAction){
255 $actionHandled = false;
256 if($blockAction instanceof PlayerBlockActionStopBreak){
257 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), new BlockPosition(0, 0, 0), Facing::DOWN);
258 }elseif($blockAction instanceof PlayerBlockActionWithBlockInfo){
259 $actionHandled = $this->handlePlayerActionFromData($blockAction->getActionType(), $blockAction->getBlockPosition(), $blockAction->getFace());
260 }
261
262 if(!$actionHandled){
263 $packetHandled = false;
264 $this->session->getLogger()->debug("Unhandled player block action at offset $k in PlayerAuthInputPacket");
265 }
266 }
267 }
268
269 $useItemTransaction = $packet->getItemInteractionData();
270 if($useItemTransaction !== null){
271 if(count($useItemTransaction->getTransactionData()->getActions()) > 100){
272 throw new PacketHandlingException("Too many actions in item use transaction");
273 }
274
275 $this->inventoryManager->setCurrentItemStackRequestId($useItemTransaction->getRequestId());
276 $this->inventoryManager->addRawPredictedSlotChanges($useItemTransaction->getTransactionData()->getActions());
277 if(!$this->handleUseItemTransaction($useItemTransaction->getTransactionData())){
278 $packetHandled = false;
279 $this->session->getLogger()->debug("Unhandled transaction in PlayerAuthInputPacket (type " . $useItemTransaction->getTransactionData()->getActionType() . ")");
280 }else{
281 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
282 }
283 $this->inventoryManager->setCurrentItemStackRequestId(null);
284 }
285
286 $itemStackRequest = $packet->getItemStackRequest();
287 if($itemStackRequest !== null){
288 $result = $this->handleSingleItemStackRequest($itemStackRequest);
289 $this->session->sendDataPacket(ItemStackResponsePacket::create([$result]));
290 }
291
292 return $packetHandled;
293 }
294
295 public function handleLevelSoundEventPacketV1(LevelSoundEventPacketV1 $packet) : bool{
296 return true; //useless leftover from 1.8
297 }
298
299 public function handleActorEvent(ActorEventPacket $packet) : bool{
300 if($packet->actorRuntimeId !== $this->player->getId()){
301 //TODO HACK: EATING_ITEM is sent back to the server when the server sends it for other players (1.14 bug, maybe earlier)
302 return $packet->actorRuntimeId === ActorEvent::EATING_ITEM;
303 }
304
305 switch($packet->eventId){
306 case ActorEvent::EATING_ITEM: //TODO: ignore this and handle it server-side
307 $item = $this->player->getInventory()->getItemInHand();
308 if($item->isNull()){
309 return false;
310 }
311 $this->player->broadcastAnimation(new ConsumingItemAnimation($this->player, $this->player->getInventory()->getItemInHand()));
312 break;
313 default:
314 return false;
315 }
316
317 return true;
318 }
319
320 public function handleInventoryTransaction(InventoryTransactionPacket $packet) : bool{
321 $result = true;
322
323 if(count($packet->trData->getActions()) > 50){
324 throw new PacketHandlingException("Too many actions in inventory transaction");
325 }
326 if(count($packet->requestChangedSlots) > 10){
327 throw new PacketHandlingException("Too many slot sync requests in inventory transaction");
328 }
329
330 $this->inventoryManager->setCurrentItemStackRequestId($packet->requestId);
331 $this->inventoryManager->addRawPredictedSlotChanges($packet->trData->getActions());
332
333 if($packet->trData instanceof NormalTransactionData){
334 $result = $this->handleNormalTransaction($packet->trData, $packet->requestId);
335 }elseif($packet->trData instanceof MismatchTransactionData){
336 $this->session->getLogger()->debug("Mismatch transaction received");
337 $this->inventoryManager->requestSyncAll();
338 $result = true;
339 }elseif($packet->trData instanceof UseItemTransactionData){
340 $result = $this->handleUseItemTransaction($packet->trData);
341 }elseif($packet->trData instanceof UseItemOnEntityTransactionData){
342 $result = $this->handleUseItemOnEntityTransaction($packet->trData);
343 }elseif($packet->trData instanceof ReleaseItemTransactionData){
344 $result = $this->handleReleaseItemTransaction($packet->trData);
345 }
346
347 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
348
349 //requestChangedSlots asks the server to always send out the contents of the specified slots, even if they
350 //haven't changed. Handling these is necessary to ensure the client inventory stays in sync if the server
351 //rejects the transaction. The most common example of this is equipping armor by right-click, which doesn't send
352 //a legacy prediction action for the destination armor slot.
353 foreach($packet->requestChangedSlots as $containerInfo){
354 foreach($containerInfo->getChangedSlotIndexes() as $netSlot){
355 [$windowId, $slot] = ItemStackContainerIdTranslator::translate($containerInfo->getContainerId(), $this->inventoryManager->getCurrentWindowId(), $netSlot);
356 $inventoryAndSlot = $this->inventoryManager->locateWindowAndSlot($windowId, $slot);
357 if($inventoryAndSlot !== null){ //trigger the normal slot sync logic
358 $this->inventoryManager->onSlotChange($inventoryAndSlot[0], $inventoryAndSlot[1]);
359 }
360 }
361 }
362
363 $this->inventoryManager->setCurrentItemStackRequestId(null);
364 return $result;
365 }
366
367 private function executeInventoryTransaction(InventoryTransaction $transaction, int $requestId) : bool{
368 $this->player->setUsingItem(false);
369
370 $this->inventoryManager->setCurrentItemStackRequestId($requestId);
371 $this->inventoryManager->addTransactionPredictedSlotChanges($transaction);
372 try{
373 $transaction->execute();
375 $this->inventoryManager->requestSyncAll();
376 $logger = $this->session->getLogger();
377 $logger->debug("Invalid inventory transaction $requestId: " . $e->getMessage());
378
379 return false;
381 $this->session->getLogger()->debug("Inventory transaction $requestId cancelled by a plugin");
382
383 return false;
384 }finally{
385 $this->inventoryManager->syncMismatchedPredictedSlotChanges();
386 $this->inventoryManager->setCurrentItemStackRequestId(null);
387 }
388
389 return true;
390 }
391
392 private function handleNormalTransaction(NormalTransactionData $data, int $itemStackRequestId) : bool{
393 //When the ItemStackRequest system is used, this transaction type is used for dropping items by pressing Q.
394 //I don't know why they don't just use ItemStackRequest for that too, which already supports dropping items by
395 //clicking them outside an open inventory menu, but for now it is what it is.
396 //Fortunately, this means we can be much stricter about the validation criteria.
397
398 $actionCount = count($data->getActions());
399 if($actionCount > 2){
400 if($actionCount > 5){
401 throw new PacketHandlingException("Too many actions ($actionCount) in normal inventory transaction");
402 }
403
404 //Due to a bug in the game, this transaction type is still sent when a player edits a book. We don't need
405 //these transactions for editing books, since we have BookEditPacket, so we can just ignore them.
406 $this->session->getLogger()->debug("Ignoring normal inventory transaction with $actionCount actions (drop-item should have exactly 2 actions)");
407 return false;
408 }
409
410 $sourceSlot = null;
411 $clientItemStack = null;
412 $droppedCount = null;
413
414 foreach($data->getActions() as $networkInventoryAction){
415 if($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_WORLD && $networkInventoryAction->inventorySlot == NetworkInventoryAction::ACTION_MAGIC_SLOT_DROP_ITEM){
416 $droppedCount = $networkInventoryAction->newItem->getItemStack()->getCount();
417 if($droppedCount <= 0){
418 throw new PacketHandlingException("Expected positive count for dropped item");
419 }
420 }elseif($networkInventoryAction->sourceType === NetworkInventoryAction::SOURCE_CONTAINER && $networkInventoryAction->windowId === ContainerIds::INVENTORY){
421 //mobile players can drop an item from a non-selected hotbar slot
422 $sourceSlot = $networkInventoryAction->inventorySlot;
423 $clientItemStack = $networkInventoryAction->oldItem->getItemStack();
424 }else{
425 $this->session->getLogger()->debug("Unexpected inventory action type $networkInventoryAction->sourceType in drop item transaction");
426 return false;
427 }
428 }
429 if($sourceSlot === null || $clientItemStack === null || $droppedCount === null){
430 $this->session->getLogger()->debug("Missing information in drop item transaction, need source slot, client item stack and dropped count");
431 return false;
432 }
433
434 $inventory = $this->player->getInventory();
435
436 if(!$inventory->slotExists($sourceSlot)){
437 return false; //TODO: size desync??
438 }
439
440 $sourceSlotItem = $inventory->getItem($sourceSlot);
441 if($sourceSlotItem->getCount() < $droppedCount){
442 return false;
443 }
444 $serverItemStack = $this->session->getTypeConverter()->coreItemStackToNet($sourceSlotItem);
445 //Sadly we don't have itemstack IDs here, so we have to compare the basic item properties to ensure that we're
446 //dropping the item the client expects (inventory might be out of sync with the client).
447 if(
448 $serverItemStack->getId() !== $clientItemStack->getId() ||
449 $serverItemStack->getMeta() !== $clientItemStack->getMeta() ||
450 $serverItemStack->getCount() !== $clientItemStack->getCount() ||
451 $serverItemStack->getBlockRuntimeId() !== $clientItemStack->getBlockRuntimeId()
452 //Raw extraData may not match because of TAG_Compound key ordering differences, and decoding it to compare
453 //is costly. Assume that we're in sync if id+meta+count+runtimeId match.
454 //NB: Make sure $clientItemStack isn't used to create the dropped item, as that would allow the client
455 //to change the item NBT since we're not validating it.
456 ){
457 return false;
458 }
459
460 //this modifies $sourceSlotItem
461 $droppedItem = $sourceSlotItem->pop($droppedCount);
462
463 $builder = new TransactionBuilder();
464 $builder->getInventory($inventory)->setItem($sourceSlot, $sourceSlotItem);
465 $builder->addAction(new DropItemAction($droppedItem));
466
467 $transaction = new InventoryTransaction($this->player, $builder->generateActions());
468 return $this->executeInventoryTransaction($transaction, $itemStackRequestId);
469 }
470
471 private function handleUseItemTransaction(UseItemTransactionData $data) : bool{
472 $this->player->selectHotbarSlot($data->getHotbarSlot());
473
474 switch($data->getActionType()){
475 case UseItemTransactionData::ACTION_CLICK_BLOCK:
476 //TODO: start hack for client spam bug
477 $clickPos = $data->getClickPosition();
478 $spamBug = ($this->lastRightClickData !== null &&
479 microtime(true) - $this->lastRightClickTime < 0.1 && //100ms
480 $this->lastRightClickData->getPlayerPosition()->distanceSquared($data->getPlayerPosition()) < 0.00001 &&
481 $this->lastRightClickData->getBlockPosition()->equals($data->getBlockPosition()) &&
482 $this->lastRightClickData->getClickPosition()->distanceSquared($clickPos) < 0.00001 //signature spam bug has 0 distance, but allow some error
483 );
484 //get rid of continued spam if the player clicks and holds right-click
485 $this->lastRightClickData = $data;
486 $this->lastRightClickTime = microtime(true);
487 if($spamBug){
488 return true;
489 }
490 //TODO: end hack for client spam bug
491
492 self::validateFacing($data->getFace());
493
494 $blockPos = $data->getBlockPosition();
495 $vBlockPos = new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
496 $this->player->interactBlock($vBlockPos, $data->getFace(), $clickPos);
497 //always sync this in case plugins caused a different result than the client expected
498 //we *could* try to enhance detection of plugin-altered behaviour, but this would require propagating
499 //more information up the stack. For now I think this is good enough.
500 //if only the client would tell us what blocks it thinks changed...
501 $this->syncBlocksNearby($vBlockPos, $data->getFace());
502 return true;
503 case UseItemTransactionData::ACTION_BREAK_BLOCK:
504 $blockPos = $data->getBlockPosition();
505 $vBlockPos = new Vector3($blockPos->getX(), $blockPos->getY(), $blockPos->getZ());
506 if(!$this->player->breakBlock($vBlockPos)){
507 $this->syncBlocksNearby($vBlockPos, null);
508 }
509 return true;
510 case UseItemTransactionData::ACTION_CLICK_AIR:
511 if($this->player->isUsingItem()){
512 if(!$this->player->consumeHeldItem()){
513 $hungerAttr = $this->player->getAttributeMap()->get(Attribute::HUNGER) ?? throw new AssumptionFailedError();
514 $hungerAttr->markSynchronized(false);
515 }
516 return true;
517 }
518 $this->player->useHeldItem();
519 return true;
520 }
521
522 return false;
523 }
524
528 private static function validateFacing(int $facing) : void{
529 if(!in_array($facing, Facing::ALL, true)){
530 throw new PacketHandlingException("Invalid facing value $facing");
531 }
532 }
533
537 private function syncBlocksNearby(Vector3 $blockPos, ?int $face) : void{
538 if($blockPos->distanceSquared($this->player->getLocation()) < 10000){
539 $blocks = $blockPos->sidesArray();
540 if($face !== null){
541 $sidePos = $blockPos->getSide($face);
542
544 array_push($blocks, ...$sidePos->sidesArray()); //getAllSides() on each of these will include $blockPos and $sidePos because they are next to each other
545 }else{
546 $blocks[] = $blockPos;
547 }
548 foreach($this->player->getWorld()->createBlockUpdatePackets($blocks) as $packet){
549 $this->session->sendDataPacket($packet);
550 }
551 }
552 }
553
554 private function handleUseItemOnEntityTransaction(UseItemOnEntityTransactionData $data) : bool{
555 $target = $this->player->getWorld()->getEntity($data->getActorRuntimeId());
556 if($target === null){
557 return false;
558 }
559
560 $this->player->selectHotbarSlot($data->getHotbarSlot());
561
562 switch($data->getActionType()){
563 case UseItemOnEntityTransactionData::ACTION_INTERACT:
564 $this->player->interactEntity($target, $data->getClickPosition());
565 return true;
566 case UseItemOnEntityTransactionData::ACTION_ATTACK:
567 $this->player->attackEntity($target);
568 return true;
569 }
570
571 return false;
572 }
573
574 private function handleReleaseItemTransaction(ReleaseItemTransactionData $data) : bool{
575 $this->player->selectHotbarSlot($data->getHotbarSlot());
576
577 if($data->getActionType() == ReleaseItemTransactionData::ACTION_RELEASE){
578 $this->player->releaseHeldItem();
579 return true;
580 }
581
582 return false;
583 }
584
585 private function handleSingleItemStackRequest(ItemStackRequest $request) : ItemStackResponse{
586 if(count($request->getActions()) > 60){
587 //recipe book auto crafting can affect all slots of the inventory when consuming inputs or producing outputs
588 //this means there could be as many as 50 CraftingConsumeInput actions or Place (taking the result) actions
589 //in a single request (there are certain ways items can be arranged which will result in the same stack
590 //being taken from multiple times, but this is behaviour with a calculable limit)
591 //this means there SHOULD be AT MOST 53 actions in a single request, but 60 is a nice round number.
592 //n64Stacks = ?
593 //n1Stacks = 45 - n64Stacks
594 //nItemsRequiredFor1Craft = 9
595 //nResults = floor((n1Stacks + (n64Stacks * 64)) / nItemsRequiredFor1Craft)
596 //nTakeActionsTotal = floor(64 / nResults) + max(1, 64 % nResults) + ((nResults * nItemsRequiredFor1Craft) - (n64Stacks * 64))
597 throw new PacketHandlingException("Too many actions in ItemStackRequest");
598 }
599 $executor = new ItemStackRequestExecutor($this->player, $this->inventoryManager, $request);
600 try{
601 $transaction = $executor->generateInventoryTransaction();
602 $result = $this->executeInventoryTransaction($transaction, $request->getRequestId());
604 $result = false;
605 $this->session->getLogger()->debug("ItemStackRequest #" . $request->getRequestId() . " failed: " . $e->getMessage());
606 $this->session->getLogger()->debug(implode("\n", Utils::printableExceptionInfo($e)));
607 $this->inventoryManager->requestSyncAll();
608 }
609
610 if(!$result){
611 return new ItemStackResponse(ItemStackResponse::RESULT_ERROR, $request->getRequestId());
612 }
613 return $executor->buildItemStackResponse();
614 }
615
616 public function handleItemStackRequest(ItemStackRequestPacket $packet) : bool{
617 $responses = [];
618 if(count($packet->getRequests()) > 80){
619 //TODO: we can probably lower this limit, but this will do for now
620 throw new PacketHandlingException("Too many requests in ItemStackRequestPacket");
621 }
622 foreach($packet->getRequests() as $request){
623 $responses[] = $this->handleSingleItemStackRequest($request);
624 }
625
626 $this->session->sendDataPacket(ItemStackResponsePacket::create($responses));
627
628 return true;
629 }
630
631 public function handleMobEquipment(MobEquipmentPacket $packet) : bool{
632 if($packet->windowId === ContainerIds::OFFHAND){
633 return true; //this happens when we put an item into the offhand
634 }
635 if($packet->windowId === ContainerIds::INVENTORY){
636 $this->inventoryManager->onClientSelectHotbarSlot($packet->hotbarSlot);
637 if(!$this->player->selectHotbarSlot($packet->hotbarSlot)){
638 $this->inventoryManager->syncSelectedHotbarSlot();
639 }
640 return true;
641 }
642 return false;
643 }
644
645 public function handleMobArmorEquipment(MobArmorEquipmentPacket $packet) : bool{
646 return true; //Not used
647 }
648
649 public function handleInteract(InteractPacket $packet) : bool{
650 if($packet->action === InteractPacket::ACTION_MOUSEOVER){
651 //TODO HACK: silence useless spam (MCPE 1.8)
652 //due to some messy Mojang hacks, it sends this when changing the held item now, which causes us to think
653 //the inventory was closed when it wasn't.
654 //this is also sent whenever entity metadata updates, which can get really spammy.
655 //TODO: implement handling for this where it matters
656 return true;
657 }
658 $target = $this->player->getWorld()->getEntity($packet->targetActorRuntimeId);
659 if($target === null){
660 return false;
661 }
662 if($packet->action === InteractPacket::ACTION_OPEN_INVENTORY && $target === $this->player){
663 $this->inventoryManager->onClientOpenMainInventory();
664 return true;
665 }
666 return false; //TODO
667 }
668
669 public function handleBlockPickRequest(BlockPickRequestPacket $packet) : bool{
670 return $this->player->pickBlock(new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ()), $packet->addUserData);
671 }
672
673 public function handleActorPickRequest(ActorPickRequestPacket $packet) : bool{
674 return $this->player->pickEntity($packet->actorUniqueId);
675 }
676
677 public function handlePlayerAction(PlayerActionPacket $packet) : bool{
678 return $this->handlePlayerActionFromData($packet->action, $packet->blockPosition, $packet->face);
679 }
680
681 private function handlePlayerActionFromData(int $action, BlockPosition $blockPosition, int $face) : bool{
682 $pos = new Vector3($blockPosition->getX(), $blockPosition->getY(), $blockPosition->getZ());
683
684 switch($action){
685 case PlayerAction::START_BREAK:
686 self::validateFacing($face);
687 if(!$this->player->attackBlock($pos, $face)){
688 $this->syncBlocksNearby($pos, $face);
689 }
690
691 break;
692
693 case PlayerAction::ABORT_BREAK:
694 case PlayerAction::STOP_BREAK:
695 $this->player->stopBreakBlock($pos);
696 break;
697 case PlayerAction::START_SLEEPING:
698 //unused
699 break;
700 case PlayerAction::STOP_SLEEPING:
701 $this->player->stopSleep();
702 break;
703 case PlayerAction::CRACK_BREAK:
704 self::validateFacing($face);
705 $this->player->continueBreakBlock($pos, $face);
706 break;
707 case PlayerAction::INTERACT_BLOCK: //TODO: ignored (for now)
708 break;
709 case PlayerAction::CREATIVE_PLAYER_DESTROY_BLOCK:
710 //TODO: do we need to handle this?
711 break;
712 case PlayerAction::START_ITEM_USE_ON:
713 case PlayerAction::STOP_ITEM_USE_ON:
714 //TODO: this has no obvious use and seems only used for analytics in vanilla - ignore it
715 break;
716 default:
717 $this->session->getLogger()->debug("Unhandled/unknown player action type " . $action);
718 return false;
719 }
720
721 $this->player->setUsingItem(false);
722
723 return true;
724 }
725
726 public function handleSetActorMotion(SetActorMotionPacket $packet) : bool{
727 return true; //Not used: This packet is (erroneously) sent to the server when the client is riding a vehicle.
728 }
729
730 public function handleAnimate(AnimatePacket $packet) : bool{
731 return true; //Not used
732 }
733
734 public function handleContainerClose(ContainerClosePacket $packet) : bool{
735 $this->inventoryManager->onClientRemoveWindow($packet->windowId);
736 return true;
737 }
738
739 public function handlePlayerHotbar(PlayerHotbarPacket $packet) : bool{
740 return true; //this packet is useless
741 }
742
743 public function handleBlockActorData(BlockActorDataPacket $packet) : bool{
744 $pos = new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ());
745 if($pos->distanceSquared($this->player->getLocation()) > 10000){
746 return false;
747 }
748
749 $block = $this->player->getLocation()->getWorld()->getBlock($pos);
750 $nbt = $packet->nbt->getRoot();
751 if(!($nbt instanceof CompoundTag)) throw new AssumptionFailedError("PHPStan should ensure this is a CompoundTag"); //for phpstorm's benefit
752
753 if($block instanceof BaseSign){
754 $frontTextTag = $nbt->getTag(Sign::TAG_FRONT_TEXT);
755 if(!$frontTextTag instanceof CompoundTag){
756 throw new PacketHandlingException("Invalid tag type " . get_debug_type($frontTextTag) . " for tag \"" . Sign::TAG_FRONT_TEXT . "\" in sign update data");
757 }
758 $textBlobTag = $frontTextTag->getTag(Sign::TAG_TEXT_BLOB);
759 if(!$textBlobTag instanceof StringTag){
760 throw new PacketHandlingException("Invalid tag type " . get_debug_type($textBlobTag) . " for tag \"" . Sign::TAG_TEXT_BLOB . "\" in sign update data");
761 }
762
763 try{
764 $text = SignText::fromBlob($textBlobTag->getValue());
765 }catch(\InvalidArgumentException $e){
766 throw PacketHandlingException::wrap($e, "Invalid sign text update");
767 }
768
769 try{
770 if(!$block->updateText($this->player, $text)){
771 foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
772 $this->session->sendDataPacket($updatePacket);
773 }
774 }
775 }catch(\UnexpectedValueException $e){
776 throw PacketHandlingException::wrap($e);
777 }
778
779 return true;
780 }
781
782 return false;
783 }
784
785 public function handlePlayerInput(PlayerInputPacket $packet) : bool{
786 return false; //TODO
787 }
788
789 public function handleSetPlayerGameType(SetPlayerGameTypePacket $packet) : bool{
790 $gameMode = $this->session->getTypeConverter()->protocolGameModeToCore($packet->gamemode);
791 if($gameMode !== $this->player->getGamemode()){
792 //Set this back to default. TODO: handle this properly
793 $this->session->syncGameMode($this->player->getGamemode(), true);
794 }
795 return true;
796 }
797
798 public function handleSpawnExperienceOrb(SpawnExperienceOrbPacket $packet) : bool{
799 return false; //TODO
800 }
801
802 public function handleMapInfoRequest(MapInfoRequestPacket $packet) : bool{
803 return false; //TODO
804 }
805
806 public function handleRequestChunkRadius(RequestChunkRadiusPacket $packet) : bool{
807 $this->player->setViewDistance($packet->radius);
808
809 return true;
810 }
811
812 public function handleBossEvent(BossEventPacket $packet) : bool{
813 return false; //TODO
814 }
815
816 public function handleShowCredits(ShowCreditsPacket $packet) : bool{
817 return false; //TODO: handle resume
818 }
819
820 public function handleCommandRequest(CommandRequestPacket $packet) : bool{
821 if(str_starts_with($packet->command, '/')){
822 $this->player->chat($packet->command);
823 return true;
824 }
825 return false;
826 }
827
828 public function handleCommandBlockUpdate(CommandBlockUpdatePacket $packet) : bool{
829 return false; //TODO
830 }
831
832 public function handlePlayerSkin(PlayerSkinPacket $packet) : bool{
833 if($packet->skin->getFullSkinId() === $this->lastRequestedFullSkinId){
834 //TODO: HACK! In 1.19.60, the client sends its skin back to us if we sent it a skin different from the one
835 //it's using. We need to prevent this from causing a feedback loop.
836 $this->session->getLogger()->debug("Refused duplicate skin change request");
837 return true;
838 }
839 $this->lastRequestedFullSkinId = $packet->skin->getFullSkinId();
840
841 $this->session->getLogger()->debug("Processing skin change request");
842 try{
843 $skin = $this->session->getTypeConverter()->getSkinAdapter()->fromSkinData($packet->skin);
844 }catch(InvalidSkinException $e){
845 throw PacketHandlingException::wrap($e, "Invalid skin in PlayerSkinPacket");
846 }
847 return $this->player->changeSkin($skin, $packet->newSkinName, $packet->oldSkinName);
848 }
849
850 public function handleSubClientLogin(SubClientLoginPacket $packet) : bool{
851 return false; //TODO
852 }
853
857 private function checkBookText(string $string, string $fieldName, int $softLimit, int $hardLimit, bool &$cancel) : string{
858 if(strlen($string) > $hardLimit){
859 throw new PacketHandlingException(sprintf("Book %s must be at most %d bytes, but have %d bytes", $fieldName, $hardLimit, strlen($string)));
860 }
861
862 $result = TextFormat::clean($string, false);
863 //strlen() is O(1), mb_strlen() is O(n)
864 if(strlen($result) > $softLimit * 4 || mb_strlen($result, 'UTF-8') > $softLimit){
865 $cancel = true;
866 $this->session->getLogger()->debug("Cancelled book edit due to $fieldName exceeded soft limit of $softLimit chars");
867 }
868
869 return $result;
870 }
871
872 public function handleBookEdit(BookEditPacket $packet) : bool{
873 $inventory = $this->player->getInventory();
874 if(!$inventory->slotExists($packet->inventorySlot)){
875 return false;
876 }
877 //TODO: break this up into book API things
878 $oldBook = $inventory->getItem($packet->inventorySlot);
879 if(!($oldBook instanceof WritableBook)){
880 return false;
881 }
882
883 $newBook = clone $oldBook;
884 $modifiedPages = [];
885 $cancel = false;
886 switch($packet->type){
887 case BookEditPacket::TYPE_REPLACE_PAGE:
888 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
889 $newBook->setPageText($packet->pageNumber, $text);
890 $modifiedPages[] = $packet->pageNumber;
891 break;
892 case BookEditPacket::TYPE_ADD_PAGE:
893 if(!$newBook->pageExists($packet->pageNumber)){
894 //this may only come before a page which already exists
895 //TODO: the client can send insert-before actions on trailing client-side pages which cause odd behaviour on the server
896 return false;
897 }
898 $text = self::checkBookText($packet->text, "page text", 256, WritableBookPage::PAGE_LENGTH_HARD_LIMIT_BYTES, $cancel);
899 $newBook->insertPage($packet->pageNumber, $text);
900 $modifiedPages[] = $packet->pageNumber;
901 break;
902 case BookEditPacket::TYPE_DELETE_PAGE:
903 if(!$newBook->pageExists($packet->pageNumber)){
904 return false;
905 }
906 $newBook->deletePage($packet->pageNumber);
907 $modifiedPages[] = $packet->pageNumber;
908 break;
909 case BookEditPacket::TYPE_SWAP_PAGES:
910 if(!$newBook->pageExists($packet->pageNumber) || !$newBook->pageExists($packet->secondaryPageNumber)){
911 //the client will create pages on its own without telling us until it tries to switch them
912 $newBook->addPage(max($packet->pageNumber, $packet->secondaryPageNumber));
913 }
914 $newBook->swapPages($packet->pageNumber, $packet->secondaryPageNumber);
915 $modifiedPages = [$packet->pageNumber, $packet->secondaryPageNumber];
916 break;
917 case BookEditPacket::TYPE_SIGN_BOOK:
918 $title = self::checkBookText($packet->title, "title", 16, Limits::INT16_MAX, $cancel);
919 //this one doesn't have a limit in vanilla, so we have to improvise
920 $author = self::checkBookText($packet->author, "author", 256, Limits::INT16_MAX, $cancel);
921
922 $newBook = VanillaItems::WRITTEN_BOOK()
923 ->setPages($oldBook->getPages())
924 ->setAuthor($author)
925 ->setTitle($title)
926 ->setGeneration(WrittenBook::GENERATION_ORIGINAL);
927 break;
928 default:
929 return false;
930 }
931
932 //for redundancy, in case of protocol changes, we don't want to pass these directly
933 $action = match($packet->type){
934 BookEditPacket::TYPE_REPLACE_PAGE => PlayerEditBookEvent::ACTION_REPLACE_PAGE,
935 BookEditPacket::TYPE_ADD_PAGE => PlayerEditBookEvent::ACTION_ADD_PAGE,
936 BookEditPacket::TYPE_DELETE_PAGE => PlayerEditBookEvent::ACTION_DELETE_PAGE,
937 BookEditPacket::TYPE_SWAP_PAGES => PlayerEditBookEvent::ACTION_SWAP_PAGES,
938 BookEditPacket::TYPE_SIGN_BOOK => PlayerEditBookEvent::ACTION_SIGN_BOOK,
939 default => throw new AssumptionFailedError("We already filtered unknown types in the switch above")
940 };
941
942 /*
943 * Plugins may have created books with more than 50 pages; we allow plugins to do this, but not players.
944 * Don't allow the page count to grow past 50, but allow deleting, swapping or altering text of existing pages.
945 */
946 $oldPageCount = count($oldBook->getPages());
947 $newPageCount = count($newBook->getPages());
948 if(($newPageCount > $oldPageCount && $newPageCount > 50)){
949 $this->session->getLogger()->debug("Cancelled book edit due to adding too many pages (new page count would be $newPageCount)");
950 $cancel = true;
951 }
952
953 $event = new PlayerEditBookEvent($this->player, $oldBook, $newBook, $action, $modifiedPages);
954 if($cancel){
955 $event->cancel();
956 }
957
958 $event->call();
959 if($event->isCancelled()){
960 return true;
961 }
962
963 $this->player->getInventory()->setItem($packet->inventorySlot, $event->getNewBook());
964
965 return true;
966 }
967
968 public function handleModalFormResponse(ModalFormResponsePacket $packet) : bool{
969 if($packet->cancelReason !== null){
970 //TODO: make APIs for this to allow plugins to use this information
971 return $this->player->onFormSubmit($packet->formId, null);
972 }elseif($packet->formData !== null){
973 try{
974 $responseData = json_decode($packet->formData, true, self::MAX_FORM_RESPONSE_DEPTH, JSON_THROW_ON_ERROR);
975 }catch(\JsonException $e){
976 throw PacketHandlingException::wrap($e, "Failed to decode form response data");
977 }
978 return $this->player->onFormSubmit($packet->formId, $responseData);
979 }else{
980 throw new PacketHandlingException("Expected either formData or cancelReason to be set in ModalFormResponsePacket");
981 }
982 }
983
984 public function handleServerSettingsRequest(ServerSettingsRequestPacket $packet) : bool{
985 return false; //TODO: GUI stuff
986 }
987
988 public function handleLabTable(LabTablePacket $packet) : bool{
989 return false; //TODO
990 }
991
992 public function handleLecternUpdate(LecternUpdatePacket $packet) : bool{
993 $pos = $packet->blockPosition;
994 $chunkX = $pos->getX() >> Chunk::COORD_BIT_SIZE;
995 $chunkZ = $pos->getZ() >> Chunk::COORD_BIT_SIZE;
996 $world = $this->player->getWorld();
997 if(!$world->isChunkLoaded($chunkX, $chunkZ) || $world->isChunkLocked($chunkX, $chunkZ)){
998 return false;
999 }
1000
1001 $lectern = $world->getBlockAt($pos->getX(), $pos->getY(), $pos->getZ());
1002 if($lectern instanceof Lectern && $this->player->canInteract($lectern->getPosition(), 15)){
1003 if(!$lectern->onPageTurn($packet->page)){
1004 $this->syncBlocksNearby($lectern->getPosition(), null);
1005 }
1006 return true;
1007 }
1008
1009 return false;
1010 }
1011
1012 public function handleNetworkStackLatency(NetworkStackLatencyPacket $packet) : bool{
1013 return true; //TODO: implement this properly - this is here to silence debug spam from MCPE dev builds
1014 }
1015
1016 public function handleLevelSoundEvent(LevelSoundEventPacket $packet) : bool{
1017 /*
1018 * We don't handle this - all sounds are handled by the server now.
1019 * However, some plugins find this useful to detect events like left-click-air, which doesn't have any other
1020 * action bound to it.
1021 * In addition, we use this handler to silence debug noise, since this packet is frequently sent by the client.
1022 */
1023 return true;
1024 }
1025
1026 public function handleEmote(EmotePacket $packet) : bool{
1027 $this->player->emote($packet->getEmoteId());
1028 return true;
1029 }
1030}
sidesArray(bool $keys=false, int $step=1)
Definition Vector3.php:187
getSide(int $side, int $step=1)
Definition Vector3.php:120
static translate(int $containerInterfaceId, int $currentWindowId, int $slotId)