Compare commits

..

18 Commits

Author SHA1 Message Date
aee1ab0ae0 Merge branch 'stable' into minor-next 2025-09-12 01:14:16 +01:00
636b96a9a5 Updated composer dependencies 2025-09-12 01:13:55 +01:00
527eda30c9 Merge 'stable' into 'minor-next'
Automatic merge performed by: https://github.com/pmmp/RestrictedActions/actions/runs/17629911301
2025-09-11 00:03:05 +00:00
c854f2c765 ItemSerializer: avoid slow NBT check
hasNamedTag() rebuilds the NBT from item properties to decide if there's any NBT.
This is a waste of resources when we then fetch the tag to encode anyway.
2025-09-10 20:06:35 +01:00
54e8ad2a9c Update BedrockProtocol 2025-09-10 16:21:29 +01:00
9fcb16b6c1 Merge 'stable' into 'minor-next'
Automatic merge performed by: https://github.com/pmmp/RestrictedActions/actions/runs/17567495443
2025-09-09 00:02:53 +00:00
2f2c53067b Merge 'stable' into 'minor-next'
Automatic merge performed by: https://github.com/pmmp/RestrictedActions/actions/runs/17507094833
2025-09-06 00:02:53 +00:00
1bc7cf340d Merge branch 'stable' into minor-next 2025-09-04 23:30:09 +01:00
26cd5c471c Merge branch 'stable' into minor-next 2025-09-04 22:03:22 +01:00
3999a1f9f4 Fix sneaking hitbox height (#6771) 2025-09-03 08:53:32 +02:00
925b34e5c6 Merge 'stable' into 'minor-next'
Automatic merge performed by: https://github.com/pmmp/RestrictedActions/actions/runs/17418990148
2025-09-03 00:02:53 +00:00
fa5cc3301c Strip unnecessary NBT from network items (#6790)
TypeConverter: Strip unnecessary NBT from clientbound items
Item containers like shulker boxes, or chests with block entity data obtained with ctrl+middle click, will often have extremely large NBT payloads.
This problem gets exponentially worse in cases where it's possible to nest inventories, as in #4665.

We can't easily address this at the core level, because tiles are not able to exist within items (due to position requirement)
so we don't have a good way to avoid this useless NBT in the first place. However, we can strip it before the item is sent to
the client, which dramatically reduces the network costs of such items, as well as removing any reason the client could have
to send such enormous items to the server.

A fully loaded shulker box with written books now takes only 5-6 KB on the wire instead of ~1 MB, which is a substantial improvement.

Dealing with this in a less hacky way is currently blocked on #6147.
2025-09-02 18:36:00 +01:00
b2d0be5b75 Support editing the back side of signs (#6774)
* Deprecate BaseSign get/set/updateText(), add get/set/updateFaceText() which accepts true/false for front/back
* add isFrontFace() to SignChangeEvent
* add optional frontFace to Player::openSignEditor()
* add BaseSign::getFacingDegrees() and getHitboxCenter() which need to be implemented by subclasses
2025-09-01 17:15:29 +01:00
d3c36e6287 Merge 'stable' into 'minor-next'
Automatic merge performed by: https://github.com/pmmp/RestrictedActions/actions/runs/17364003235
2025-09-01 00:03:50 +00:00
e569cc3275 stfu 2025-08-31 21:47:49 +01:00
c931437a30 InventoryTransaction: Remove action shuffling
we used to have this to prevent dependence on client ordering, and make ordering consistently not work.
However, since the introduction of the ItemStackRequest protocol, we don't expect to see client actions
in the wrong order anymore, so this shouldn't be needed anymore.

closes #6701
2025-08-31 21:45:55 +01:00
dca9d3a010 Merge 'stable' into 'minor-next'
Automatic merge performed by: https://github.com/pmmp/RestrictedActions/actions/runs/17346805858
2025-08-30 17:49:04 +00:00
9310c46ea1 Merge 'stable' into 'minor-next'
Automatic merge performed by: https://github.com/pmmp/RestrictedActions/actions/runs/17336647491
2025-08-30 00:02:47 +00:00
20 changed files with 367 additions and 149 deletions

View File

@ -36,7 +36,7 @@
"pocketmine/bedrock-block-upgrade-schema": "~5.1.0+bedrock-1.21.60", "pocketmine/bedrock-block-upgrade-schema": "~5.1.0+bedrock-1.21.60",
"pocketmine/bedrock-data": "~6.0.0+bedrock-1.21.100", "pocketmine/bedrock-data": "~6.0.0+bedrock-1.21.100",
"pocketmine/bedrock-item-upgrade-schema": "~1.15.0+bedrock-1.21.100", "pocketmine/bedrock-item-upgrade-schema": "~1.15.0+bedrock-1.21.100",
"pocketmine/bedrock-protocol": "~40.0.0+bedrock-1.21.100", "pocketmine/bedrock-protocol": "~41.0.0+bedrock-1.21.100",
"pocketmine/binaryutils": "^0.2.1", "pocketmine/binaryutils": "^0.2.1",
"pocketmine/callback-validator": "^1.0.2", "pocketmine/callback-validator": "^1.0.2",
"pocketmine/color": "^0.3.0", "pocketmine/color": "^0.3.0",

64
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "27fee330bdcb6ea2373c57cdfb3bc22f", "content-hash": "7bf7cd54642c2d65ecdfdcb28f3a64a8",
"packages": [ "packages": [
{ {
"name": "adhocore/json-comment", "name": "adhocore/json-comment",
@ -256,16 +256,16 @@
}, },
{ {
"name": "pocketmine/bedrock-protocol", "name": "pocketmine/bedrock-protocol",
"version": "40.0.0+bedrock-1.21.100", "version": "41.0.0+bedrock-1.21.100",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/pmmp/BedrockProtocol.git", "url": "https://github.com/pmmp/BedrockProtocol.git",
"reference": "5e95cab3a6e6c24920e0c25ca4aaf887ed4b70ca" "reference": "920ac291fe1b0143b2ebc90b3374ddab0b8531bf"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/pmmp/BedrockProtocol/zipball/5e95cab3a6e6c24920e0c25ca4aaf887ed4b70ca", "url": "https://api.github.com/repos/pmmp/BedrockProtocol/zipball/920ac291fe1b0143b2ebc90b3374ddab0b8531bf",
"reference": "5e95cab3a6e6c24920e0c25ca4aaf887ed4b70ca", "reference": "920ac291fe1b0143b2ebc90b3374ddab0b8531bf",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -296,9 +296,9 @@
"description": "An implementation of the Minecraft: Bedrock Edition protocol in PHP", "description": "An implementation of the Minecraft: Bedrock Edition protocol in PHP",
"support": { "support": {
"issues": "https://github.com/pmmp/BedrockProtocol/issues", "issues": "https://github.com/pmmp/BedrockProtocol/issues",
"source": "https://github.com/pmmp/BedrockProtocol/tree/40.0.0+bedrock-1.21.100" "source": "https://github.com/pmmp/BedrockProtocol/tree/41.0.0+bedrock-1.21.100"
}, },
"time": "2025-08-06T15:13:45+00:00" "time": "2025-09-09T20:52:18+00:00"
}, },
{ {
"name": "pocketmine/binaryutils", "name": "pocketmine/binaryutils",
@ -818,20 +818,20 @@
}, },
{ {
"name": "ramsey/uuid", "name": "ramsey/uuid",
"version": "4.9.0", "version": "4.9.1",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/ramsey/uuid.git", "url": "https://github.com/ramsey/uuid.git",
"reference": "4e0e23cc785f0724a0e838279a9eb03f28b092a0" "reference": "81f941f6f729b1e3ceea61d9d014f8b6c6800440"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/ramsey/uuid/zipball/4e0e23cc785f0724a0e838279a9eb03f28b092a0", "url": "https://api.github.com/repos/ramsey/uuid/zipball/81f941f6f729b1e3ceea61d9d014f8b6c6800440",
"reference": "4e0e23cc785f0724a0e838279a9eb03f28b092a0", "reference": "81f941f6f729b1e3ceea61d9d014f8b6c6800440",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13", "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13 || ^0.14",
"php": "^8.0", "php": "^8.0",
"ramsey/collection": "^1.2 || ^2.0" "ramsey/collection": "^1.2 || ^2.0"
}, },
@ -890,9 +890,9 @@
], ],
"support": { "support": {
"issues": "https://github.com/ramsey/uuid/issues", "issues": "https://github.com/ramsey/uuid/issues",
"source": "https://github.com/ramsey/uuid/tree/4.9.0" "source": "https://github.com/ramsey/uuid/tree/4.9.1"
}, },
"time": "2025-06-25T14:20:11+00:00" "time": "2025-09-04T20:59:21+00:00"
}, },
{ {
"name": "symfony/filesystem", "name": "symfony/filesystem",
@ -1684,16 +1684,16 @@
}, },
{ {
"name": "phpunit/phpunit", "name": "phpunit/phpunit",
"version": "10.5.53", "version": "10.5.54",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git", "url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "32768472ebfb6969e6c7399f1c7b09009723f653" "reference": "b1dbbaaf96106b76d500b9d3db51f9b01f6a3589"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/32768472ebfb6969e6c7399f1c7b09009723f653", "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/b1dbbaaf96106b76d500b9d3db51f9b01f6a3589",
"reference": "32768472ebfb6969e6c7399f1c7b09009723f653", "reference": "b1dbbaaf96106b76d500b9d3db51f9b01f6a3589",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1765,7 +1765,7 @@
"support": { "support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues", "issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy", "security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/10.5.53" "source": "https://github.com/sebastianbergmann/phpunit/tree/10.5.54"
}, },
"funding": [ "funding": [
{ {
@ -1789,7 +1789,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2025-08-20T14:40:06+00:00" "time": "2025-09-11T06:19:38+00:00"
}, },
{ {
"name": "sebastian/cli-parser", "name": "sebastian/cli-parser",
@ -1961,16 +1961,16 @@
}, },
{ {
"name": "sebastian/comparator", "name": "sebastian/comparator",
"version": "5.0.3", "version": "5.0.4",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/comparator.git", "url": "https://github.com/sebastianbergmann/comparator.git",
"reference": "a18251eb0b7a2dcd2f7aa3d6078b18545ef0558e" "reference": "e8e53097718d2b53cfb2aa859b06a41abf58c62e"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/a18251eb0b7a2dcd2f7aa3d6078b18545ef0558e", "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/e8e53097718d2b53cfb2aa859b06a41abf58c62e",
"reference": "a18251eb0b7a2dcd2f7aa3d6078b18545ef0558e", "reference": "e8e53097718d2b53cfb2aa859b06a41abf58c62e",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2026,15 +2026,27 @@
"support": { "support": {
"issues": "https://github.com/sebastianbergmann/comparator/issues", "issues": "https://github.com/sebastianbergmann/comparator/issues",
"security": "https://github.com/sebastianbergmann/comparator/security/policy", "security": "https://github.com/sebastianbergmann/comparator/security/policy",
"source": "https://github.com/sebastianbergmann/comparator/tree/5.0.3" "source": "https://github.com/sebastianbergmann/comparator/tree/5.0.4"
}, },
"funding": [ "funding": [
{ {
"url": "https://github.com/sebastianbergmann", "url": "https://github.com/sebastianbergmann",
"type": "github" "type": "github"
},
{
"url": "https://liberapay.com/sebastianbergmann",
"type": "liberapay"
},
{
"url": "https://thanks.dev/u/gh/sebastianbergmann",
"type": "thanks_dev"
},
{
"url": "https://tidelift.com/funding/github/packagist/sebastian/comparator",
"type": "tidelift"
} }
], ],
"time": "2024-10-18T14:56:07+00:00" "time": "2025-09-07T05:25:07+00:00"
}, },
{ {
"name": "sebastian/complexity", "name": "sebastian/complexity",

View File

@ -41,14 +41,19 @@ use pocketmine\utils\TextFormat;
use pocketmine\world\BlockTransaction; use pocketmine\world\BlockTransaction;
use pocketmine\world\sound\DyeUseSound; use pocketmine\world\sound\DyeUseSound;
use pocketmine\world\sound\InkSacUseSound; use pocketmine\world\sound\InkSacUseSound;
use function abs;
use function array_map; use function array_map;
use function assert; use function assert;
use function atan2;
use function fmod;
use function rad2deg;
use function strlen; use function strlen;
abstract class BaseSign extends Transparent implements WoodMaterial{ abstract class BaseSign extends Transparent implements WoodMaterial{
use WoodTypeTrait; use WoodTypeTrait;
protected SignText $text; protected SignText $text; //TODO: rename this (BC break)
protected SignText $backText;
private bool $waxed = false; private bool $waxed = false;
protected ?int $editorEntityRuntimeId = null; protected ?int $editorEntityRuntimeId = null;
@ -63,6 +68,7 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
$this->woodType = $woodType; $this->woodType = $woodType;
parent::__construct($idInfo, $name, $typeInfo); parent::__construct($idInfo, $name, $typeInfo);
$this->text = new SignText(); $this->text = new SignText();
$this->backText = new SignText();
$this->asItemCallback = $asItemCallback; $this->asItemCallback = $asItemCallback;
} }
@ -71,6 +77,7 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
$tile = $this->position->getWorld()->getTile($this->position); $tile = $this->position->getWorld()->getTile($this->position);
if($tile instanceof TileSign){ if($tile instanceof TileSign){
$this->text = $tile->getText(); $this->text = $tile->getText();
$this->backText = $tile->getBackText();
$this->waxed = $tile->isWaxed(); $this->waxed = $tile->isWaxed();
$this->editorEntityRuntimeId = $tile->getEditorEntityRuntimeId(); $this->editorEntityRuntimeId = $tile->getEditorEntityRuntimeId();
} }
@ -83,6 +90,7 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
$tile = $this->position->getWorld()->getTile($this->position); $tile = $this->position->getWorld()->getTile($this->position);
assert($tile instanceof TileSign); assert($tile instanceof TileSign);
$tile->setText($this->text); $tile->setText($this->text);
$tile->setBackText($this->backText);
$tile->setWaxed($this->waxed); $tile->setWaxed($this->waxed);
$tile->setEditorEntityRuntimeId($this->editorEntityRuntimeId); $tile->setEditorEntityRuntimeId($this->editorEntityRuntimeId);
} }
@ -127,11 +135,11 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
} }
} }
private function doSignChange(SignText $newText, Player $player, Item $item) : bool{ private function doSignChange(SignText $newText, Player $player, Item $item, bool $frontFace) : bool{
$ev = new SignChangeEvent($this, $player, $newText); $ev = new SignChangeEvent($this, $player, $newText, $frontFace);
$ev->call(); $ev->call();
if(!$ev->isCancelled()){ if(!$ev->isCancelled()){
$this->text = $ev->getNewText(); $this->setFaceText($frontFace, $ev->getNewText());
$this->position->getWorld()->setBlock($this->position, $this); $this->position->getWorld()->setBlock($this->position, $this);
$item->pop(); $item->pop();
return true; return true;
@ -140,8 +148,9 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
return false; return false;
} }
private function changeSignGlowingState(bool $glowing, Player $player, Item $item) : bool{ private function changeSignGlowingState(bool $glowing, Player $player, Item $item, bool $frontFace) : bool{
if($this->text->isGlowing() !== $glowing && $this->doSignChange(new SignText($this->text->getLines(), $this->text->getBaseColor(), $glowing), $player, $item)){ $text = $this->getFaceText($frontFace);
if($text->isGlowing() !== $glowing && $this->doSignChange(new SignText($text->getLines(), $text->getBaseColor(), $glowing), $player, $item, $frontFace)){
$this->position->getWorld()->addSound($this->position, new InkSacUseSound()); $this->position->getWorld()->addSound($this->position, new InkSacUseSound());
return true; return true;
} }
@ -168,6 +177,8 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
return true; return true;
} }
$frontFace = $this->interactsFront($this->getHitboxCenter(), $player->getPosition(), $this->getFacingDegrees());
$dyeColor = $item instanceof Dye ? $item->getColor() : match($item->getTypeId()){ $dyeColor = $item instanceof Dye ? $item->getColor() : match($item->getTypeId()){
ItemTypeIds::BONE_MEAL => DyeColor::WHITE, ItemTypeIds::BONE_MEAL => DyeColor::WHITE,
ItemTypeIds::LAPIS_LAZULI => DyeColor::BLUE, ItemTypeIds::LAPIS_LAZULI => DyeColor::BLUE,
@ -176,40 +187,82 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
}; };
if($dyeColor !== null){ if($dyeColor !== null){
$color = $dyeColor === DyeColor::BLACK ? new Color(0, 0, 0) : $dyeColor->getRgbValue(); $color = $dyeColor === DyeColor::BLACK ? new Color(0, 0, 0) : $dyeColor->getRgbValue();
$text = $this->getFaceText($frontFace);
if( if(
$color->toARGB() !== $this->text->getBaseColor()->toARGB() && $color->toARGB() !== $text->getBaseColor()->toARGB() &&
$this->doSignChange(new SignText($this->text->getLines(), $color, $this->text->isGlowing()), $player, $item) $this->doSignChange(new SignText($text->getLines(), $color, $text->isGlowing()), $player, $item, $frontFace)
){ ){
$this->position->getWorld()->addSound($this->position, new DyeUseSound()); $this->position->getWorld()->addSound($this->position, new DyeUseSound());
return true; return true;
} }
}elseif(match($item->getTypeId()){ }elseif(match($item->getTypeId()){
ItemTypeIds::INK_SAC => $this->changeSignGlowingState(false, $player, $item), ItemTypeIds::INK_SAC => $this->changeSignGlowingState(false, $player, $item, $frontFace),
ItemTypeIds::GLOW_INK_SAC => $this->changeSignGlowingState(true, $player, $item), ItemTypeIds::GLOW_INK_SAC => $this->changeSignGlowingState(true, $player, $item, $frontFace),
ItemTypeIds::HONEYCOMB => $this->wax($player, $item), ItemTypeIds::HONEYCOMB => $this->wax($player, $item),
default => false default => false
}){ }){
return true; return true;
} }
$player->openSignEditor($this->position); $player->openSignEditor($this->position, $frontFace);
return true; return true;
} }
private function interactsFront(Vector3 $hitboxCenter, Vector3 $playerPosition, float $signFacingDegrees) : bool{
$playerCenterDiffX = $playerPosition->x - $hitboxCenter->x;
$playerCenterDiffZ = $playerPosition->z - $hitboxCenter->z;
$f1 = rad2deg(atan2($playerCenterDiffZ, $playerCenterDiffX)) - 90.0;
$rotationDiff = $signFacingDegrees - $f1;
$rotation = fmod($rotationDiff + 180.0, 360.0) - 180.0; // Normalize to [-180, 180]
return abs($rotation) <= 90.0;
}
/**
* Returns the center of the sign's hitbox. Used to decide which face of the sign to open when a player interacts.
*/
protected function getHitboxCenter() : Vector3{
return $this->position->add(0.5, 0.5, 0.5);
}
/**
* TODO: make this abstract (BC break)
*/
protected function getFacingDegrees() : float{
return 0;
}
/** /**
* Returns an object containing information about the sign text. * Returns an object containing information about the sign text.
* @deprecated
* @see self::getFaceText()
*/ */
public function getText() : SignText{ public function getText() : SignText{
return $this->text; return $this->text;
} }
/** @return $this */ /**
* @deprecated
* @see self::setFaceText()
* @return $this
*/
public function setText(SignText $text) : self{ public function setText(SignText $text) : self{
$this->text = $text; $this->text = $text;
return $this; return $this;
} }
public function getFaceText(bool $frontFace) : SignText{
return $frontFace ? $this->text : $this->backText;
}
/** @return $this */
public function setFaceText(bool $frontFace, SignText $text) : self{
$frontFace ? $this->text = $text : $this->backText = $text;
return $this;
}
/** /**
* Returns whether the sign has been waxed using a honeycomb. If true, the sign cannot be edited by a player. * Returns whether the sign has been waxed using a honeycomb. If true, the sign cannot be edited by a player.
*/ */
@ -234,13 +287,21 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
return $this; return $this;
} }
/**
* @deprecated
* @see self::updateFaceText()
*/
public function updateText(Player $author, SignText $text) : bool{
return $this->updateFaceText($author, true, $text);
}
/** /**
* Called by the player controller (network session) to update the sign text, firing events as appropriate. * Called by the player controller (network session) to update the sign text, firing events as appropriate.
* *
* @return bool if the sign update was successful. * @return bool if the sign update was successful.
* @throws \UnexpectedValueException if the text payload is too large * @throws \UnexpectedValueException if the text payload is too large
*/ */
public function updateText(Player $author, SignText $text) : bool{ public function updateFaceText(Player $author, bool $frontFace, SignText $text) : bool{
$size = 0; $size = 0;
foreach($text->getLines() as $line){ foreach($text->getLines() as $line){
$size += strlen($line); $size += strlen($line);
@ -248,15 +309,16 @@ abstract class BaseSign extends Transparent implements WoodMaterial{
if($size > 1000){ if($size > 1000){
throw new \UnexpectedValueException($author->getName() . " tried to write $size bytes of text onto a sign (bigger than max 1000)"); throw new \UnexpectedValueException($author->getName() . " tried to write $size bytes of text onto a sign (bigger than max 1000)");
} }
$oldText = $this->getFaceText($frontFace);
$ev = new SignChangeEvent($this, $author, new SignText(array_map(function(string $line) : string{ $ev = new SignChangeEvent($this, $author, new SignText(array_map(function(string $line) : string{
return TextFormat::clean($line, false); return TextFormat::clean($line, false);
}, $text->getLines()), $this->text->getBaseColor(), $this->text->isGlowing())); }, $text->getLines()), $oldText->getBaseColor(), $oldText->isGlowing()), $frontFace);
if($this->waxed || $this->editorEntityRuntimeId !== $author->getId()){ if($this->waxed || $this->editorEntityRuntimeId !== $author->getId()){
$ev->cancel(); $ev->cancel();
} }
$ev->call(); $ev->call();
if(!$ev->isCancelled()){ if(!$ev->isCancelled()){
$this->setText($ev->getNewText()); $this->setFaceText($frontFace, $ev->getNewText());
$this->setEditorEntityRuntimeId(null); $this->setEditorEntityRuntimeId(null);
$this->position->getWorld()->setBlock($this->position, $this); $this->position->getWorld()->setBlock($this->position, $this);
return true; return true;

View File

@ -58,4 +58,8 @@ final class CeilingCenterHangingSign extends BaseSign implements SignLikeRotatio
$supportBlock->getSupportType(Facing::DOWN)->hasCenterSupport() || $supportBlock->getSupportType(Facing::DOWN)->hasCenterSupport() ||
$supportBlock->hasTypeTag(BlockTypeTags::HANGING_SIGN); $supportBlock->hasTypeTag(BlockTypeTags::HANGING_SIGN);
} }
protected function getFacingDegrees() : float{
return $this->rotation * 22.5;
}
} }

View File

@ -30,6 +30,7 @@ use pocketmine\item\Item;
use pocketmine\math\Facing; use pocketmine\math\Facing;
use pocketmine\math\Vector3; use pocketmine\math\Vector3;
use pocketmine\player\Player; use pocketmine\player\Player;
use pocketmine\utils\AssumptionFailedError;
use pocketmine\world\BlockTransaction; use pocketmine\world\BlockTransaction;
final class CeilingEdgesHangingSign extends BaseSign implements HorizontalFacing{ final class CeilingEdgesHangingSign extends BaseSign implements HorizontalFacing{
@ -65,4 +66,14 @@ final class CeilingEdgesHangingSign extends BaseSign implements HorizontalFacing
$supportBlock->getSupportType(Facing::DOWN) === SupportType::FULL || $supportBlock->getSupportType(Facing::DOWN) === SupportType::FULL ||
(($supportBlock instanceof WallHangingSign || $supportBlock instanceof CeilingEdgesHangingSign) && Facing::axis($supportBlock->getFacing()) === Facing::axis($this->facing)); (($supportBlock instanceof WallHangingSign || $supportBlock instanceof CeilingEdgesHangingSign) && Facing::axis($supportBlock->getFacing()) === Facing::axis($this->facing));
} }
protected function getFacingDegrees() : float{
return match($this->facing){
Facing::SOUTH => 0,
Facing::WEST => 90,
Facing::NORTH => 180,
Facing::EAST => 270,
default => throw new AssumptionFailedError("Invalid facing direction: " . $this->facing),
};
}
} }

View File

@ -48,4 +48,8 @@ final class FloorSign extends BaseSign implements SignLikeRotation{
} }
return parent::place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player); return parent::place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player);
} }
protected function getFacingDegrees() : float{
return $this->rotation * 22.5;
}
} }

View File

@ -32,6 +32,7 @@ use pocketmine\math\AxisAlignedBB;
use pocketmine\math\Facing; use pocketmine\math\Facing;
use pocketmine\math\Vector3; use pocketmine\math\Vector3;
use pocketmine\player\Player; use pocketmine\player\Player;
use pocketmine\utils\AssumptionFailedError;
use pocketmine\world\BlockTransaction; use pocketmine\world\BlockTransaction;
final class WallHangingSign extends BaseSign implements HorizontalFacing{ final class WallHangingSign extends BaseSign implements HorizontalFacing{
@ -78,4 +79,14 @@ final class WallHangingSign extends BaseSign implements HorizontalFacing{
($block instanceof WallHangingSign && Facing::axis(Facing::rotateY($block->getFacing(), clockwise: true)) === Facing::axis($face)) || ($block instanceof WallHangingSign && Facing::axis(Facing::rotateY($block->getFacing(), clockwise: true)) === Facing::axis($face)) ||
$block->getSupportType(Facing::opposite($face)) === SupportType::FULL; $block->getSupportType(Facing::opposite($face)) === SupportType::FULL;
} }
protected function getFacingDegrees() : float{
return match($this->facing){
Facing::SOUTH => 0,
Facing::WEST => 90,
Facing::NORTH => 180,
Facing::EAST => 270,
default => throw new AssumptionFailedError("Invalid facing direction: " . $this->facing),
};
}
} }

View File

@ -30,6 +30,7 @@ use pocketmine\math\Axis;
use pocketmine\math\Facing; use pocketmine\math\Facing;
use pocketmine\math\Vector3; use pocketmine\math\Vector3;
use pocketmine\player\Player; use pocketmine\player\Player;
use pocketmine\utils\AssumptionFailedError;
use pocketmine\world\BlockTransaction; use pocketmine\world\BlockTransaction;
final class WallSign extends BaseSign implements HorizontalFacing{ final class WallSign extends BaseSign implements HorizontalFacing{
@ -46,4 +47,25 @@ final class WallSign extends BaseSign implements HorizontalFacing{
$this->facing = $face; $this->facing = $face;
return parent::place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player); return parent::place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player);
} }
protected function getHitboxCenter() : Vector3{
[$xOffset, $zOffset] = match($this->facing){
Facing::NORTH => [0, 15 / 16],
Facing::SOUTH => [0, 1 / 16],
Facing::WEST => [15 / 16, 0],
Facing::EAST => [1 / 16, 0],
default => throw new AssumptionFailedError("Invalid facing direction: " . $this->facing),
};
return $this->position->add($xOffset, 0.5, $zOffset);
}
protected function getFacingDegrees() : float{
return match($this->facing){
Facing::SOUTH => 0,
Facing::WEST => 90,
Facing::NORTH => 180,
Facing::EAST => 270,
default => throw new AssumptionFailedError("Invalid facing direction: " . $this->facing),
};
}
} }

View File

@ -70,16 +70,18 @@ class Sign extends Spawnable{
} }
protected SignText $text; protected SignText $text;
protected SignText $backText;
private bool $waxed = false; private bool $waxed = false;
protected ?int $editorEntityRuntimeId = null; protected ?int $editorEntityRuntimeId = null;
public function __construct(World $world, Vector3 $pos){ public function __construct(World $world, Vector3 $pos){
$this->text = new SignText(); $this->text = new SignText();
$this->backText = new SignText();
parent::__construct($world, $pos); parent::__construct($world, $pos);
} }
private function readTextTag(CompoundTag $nbt, bool $lightingBugResolved) : void{ private function readTextTag(CompoundTag $nbt, bool $lightingBugResolved) : SignText{
$baseColor = new Color(0, 0, 0); $baseColor = new Color(0, 0, 0);
$glowingText = false; $glowingText = false;
if(($baseColorTag = $nbt->getTag(self::TAG_TEXT_COLOR)) instanceof IntTag){ if(($baseColorTag = $nbt->getTag(self::TAG_TEXT_COLOR)) instanceof IntTag){
@ -90,19 +92,27 @@ class Sign extends Spawnable{
//see https://bugs.mojang.com/browse/MCPE-117835 //see https://bugs.mojang.com/browse/MCPE-117835
$glowingText = $glowingTextTag->getValue() !== 0; $glowingText = $glowingTextTag->getValue() !== 0;
} }
$this->text = SignText::fromBlob(mb_scrub($nbt->getString(self::TAG_TEXT_BLOB), 'UTF-8'), $baseColor, $glowingText); return SignText::fromBlob(mb_scrub($nbt->getString(self::TAG_TEXT_BLOB), 'UTF-8'), $baseColor, $glowingText);
}
private function writeTextTag(SignText $text) : CompoundTag{
return CompoundTag::create()
->setString(self::TAG_TEXT_BLOB, rtrim(implode("\n", $text->getLines()), "\n"))
->setInt(self::TAG_TEXT_COLOR, Binary::signInt($text->getBaseColor()->toARGB()))
->setByte(self::TAG_GLOWING_TEXT, $text->isGlowing() ? 1 : 0)
->setByte(self::TAG_PERSIST_FORMATTING, 1);
} }
public function readSaveData(CompoundTag $nbt) : void{ public function readSaveData(CompoundTag $nbt) : void{
$frontTextTag = $nbt->getTag(self::TAG_FRONT_TEXT); $frontTextTag = $nbt->getTag(self::TAG_FRONT_TEXT);
if($frontTextTag instanceof CompoundTag){ if($frontTextTag instanceof CompoundTag){
$this->readTextTag($frontTextTag, true); $this->text = $this->readTextTag($frontTextTag, true);
}elseif($nbt->getTag(self::TAG_TEXT_BLOB) instanceof StringTag){ //MCPE 1.2 save format }elseif($nbt->getTag(self::TAG_TEXT_BLOB) instanceof StringTag){ //MCPE 1.2 save format
$lightingBugResolved = false; $lightingBugResolved = false;
if(($lightingBugResolvedTag = $nbt->getTag(self::TAG_LEGACY_BUG_RESOLVE)) instanceof ByteTag){ if(($lightingBugResolvedTag = $nbt->getTag(self::TAG_LEGACY_BUG_RESOLVE)) instanceof ByteTag){
$lightingBugResolved = $lightingBugResolvedTag->getValue() !== 0; $lightingBugResolved = $lightingBugResolvedTag->getValue() !== 0;
} }
$this->readTextTag($nbt, $lightingBugResolved); $this->text = $this->readTextTag($nbt, $lightingBugResolved);
}else{ }else{
$text = []; $text = [];
for($i = 0; $i < SignText::LINE_COUNT; ++$i){ for($i = 0; $i < SignText::LINE_COUNT; ++$i){
@ -113,22 +123,14 @@ class Sign extends Spawnable{
} }
$this->text = new SignText($text); $this->text = new SignText($text);
} }
$backTextTag = $nbt->getTag(self::TAG_BACK_TEXT);
$this->backText = $backTextTag instanceof CompoundTag ? $this->readTextTag($backTextTag, true) : new SignText();
$this->waxed = $nbt->getByte(self::TAG_WAXED, 0) !== 0; $this->waxed = $nbt->getByte(self::TAG_WAXED, 0) !== 0;
} }
protected function writeSaveData(CompoundTag $nbt) : void{ protected function writeSaveData(CompoundTag $nbt) : void{
$nbt->setTag(self::TAG_FRONT_TEXT, CompoundTag::create() $nbt->setTag(self::TAG_FRONT_TEXT, $this->writeTextTag($this->text));
->setString(self::TAG_TEXT_BLOB, rtrim(implode("\n", $this->text->getLines()), "\n")) $nbt->setTag(self::TAG_BACK_TEXT, $this->writeTextTag($this->backText));
->setInt(self::TAG_TEXT_COLOR, Binary::signInt($this->text->getBaseColor()->toARGB()))
->setByte(self::TAG_GLOWING_TEXT, $this->text->isGlowing() ? 1 : 0)
->setByte(self::TAG_PERSIST_FORMATTING, 1)
);
$nbt->setTag(self::TAG_BACK_TEXT, CompoundTag::create()
->setString(self::TAG_TEXT_BLOB, "")
->setInt(self::TAG_TEXT_COLOR, Binary::signInt(0xff_00_00_00))
->setByte(self::TAG_GLOWING_TEXT, 0)
->setByte(self::TAG_PERSIST_FORMATTING, 1)
);
$nbt->setByte(self::TAG_WAXED, $this->waxed ? 1 : 0); $nbt->setByte(self::TAG_WAXED, $this->waxed ? 1 : 0);
} }
@ -141,6 +143,10 @@ class Sign extends Spawnable{
$this->text = $text; $this->text = $text;
} }
public function getBackText() : SignText{ return $this->backText; }
public function setBackText(SignText $backText) : void{ $this->backText = $backText; }
public function isWaxed() : bool{ return $this->waxed; } public function isWaxed() : bool{ return $this->waxed; }
public function setWaxed(bool $waxed) : void{ $this->waxed = $waxed; } public function setWaxed(bool $waxed) : void{ $this->waxed = $waxed; }
@ -162,19 +168,8 @@ class Sign extends Spawnable{
} }
protected function addAdditionalSpawnData(CompoundTag $nbt) : void{ protected function addAdditionalSpawnData(CompoundTag $nbt) : void{
$nbt->setTag(self::TAG_FRONT_TEXT, CompoundTag::create() $nbt->setTag(self::TAG_FRONT_TEXT, $this->writeTextTag($this->text));
->setString(self::TAG_TEXT_BLOB, rtrim(implode("\n", $this->text->getLines()), "\n")) $nbt->setTag(self::TAG_BACK_TEXT, $this->writeTextTag($this->backText));
->setInt(self::TAG_TEXT_COLOR, Binary::signInt($this->text->getBaseColor()->toARGB()))
->setByte(self::TAG_GLOWING_TEXT, $this->text->isGlowing() ? 1 : 0)
->setByte(self::TAG_PERSIST_FORMATTING, 1) //TODO: not sure what this is used for
);
//TODO: this is not yet used by the server, but needed to rollback any client-side changes to the back text
$nbt->setTag(self::TAG_BACK_TEXT, CompoundTag::create()
->setString(self::TAG_TEXT_BLOB, "")
->setInt(self::TAG_TEXT_COLOR, Binary::signInt(0xff_00_00_00))
->setByte(self::TAG_GLOWING_TEXT, 0)
->setByte(self::TAG_PERSIST_FORMATTING, 1)
);
$nbt->setByte(self::TAG_WAXED, $this->waxed ? 1 : 0); $nbt->setByte(self::TAG_WAXED, $this->waxed ? 1 : 0);
$nbt->setLong(self::TAG_LOCKED_FOR_EDITING_BY, $this->editorEntityRuntimeId ?? -1); $nbt->setLong(self::TAG_LOCKED_FOR_EDITING_BY, $this->editorEntityRuntimeId ?? -1);
} }

View File

@ -117,8 +117,8 @@ final class ItemSerializer{
$data = $serializer($item); $data = $serializer($item);
} }
if($item->hasNamedTag()){
$resultTag = $item->getNamedTag(); $resultTag = $item->getNamedTag();
if($resultTag->count() > 0){
$extraTag = $data->getTag(); $extraTag = $data->getTag();
if($extraTag !== null){ if($extraTag !== null){
$resultTag = $resultTag->merge($extraTag); $resultTag = $resultTag->merge($extraTag);

View File

@ -247,6 +247,10 @@ class Human extends Living implements ProjectileSource, InventoryHolder{
return $this->enderInventory; return $this->enderInventory;
} }
public function getSneakOffset() : float{
return 0.31;
}
/** /**
* For Human entities which are not players, sets their properties such as nametag, skin and UUID from NBT. * For Human entities which are not players, sets their properties such as nametag, skin and UUID from NBT.
*/ */

View File

@ -242,6 +242,10 @@ abstract class Living extends Entity{
$this->absorptionAttr->setValue($absorption); $this->absorptionAttr->setValue($absorption);
} }
public function getSneakOffset() : float{
return 0.0;
}
public function isSneaking() : bool{ public function isSneaking() : bool{
return $this->sneaking; return $this->sneaking;
} }
@ -292,7 +296,7 @@ abstract class Living extends Entity{
$width = $size->getWidth(); $width = $size->getWidth();
$this->setSize((new EntitySizeInfo($width, $width, $width * 0.9))->scale($this->getScale())); $this->setSize((new EntitySizeInfo($width, $width, $width * 0.9))->scale($this->getScale()));
}elseif($this->isSneaking()){ }elseif($this->isSneaking()){
$this->setSize((new EntitySizeInfo(3 / 4 * $size->getHeight(), $size->getWidth(), 3 / 4 * $size->getEyeHeight()))->scale($this->getScale())); $this->setSize((new EntitySizeInfo($size->getHeight() - $this->getSneakOffset(), $size->getWidth(), $size->getEyeHeight() - $this->getSneakOffset()))->scale($this->getScale()));
}else{ }else{
$this->setSize($size->scale($this->getScale())); $this->setSize($size->scale($this->getScale()));
} }

View File

@ -52,8 +52,6 @@ class EndCrystal extends Entity implements Explosive{
protected bool $showBase = false; protected bool $showBase = false;
protected ?Vector3 $beamTarget = null; protected ?Vector3 $beamTarget = null;
private bool $primed = false;
protected function getInitialSizeInfo() : EntitySizeInfo{ return new EntitySizeInfo(2.0, 2.0); } protected function getInitialSizeInfo() : EntitySizeInfo{ return new EntitySizeInfo(2.0, 2.0); }
protected function getInitialDragMultiplier() : float{ return 1.0; } protected function getInitialDragMultiplier() : float{ return 1.0; }
@ -90,9 +88,11 @@ class EndCrystal extends Entity implements Explosive{
parent::attack($source); parent::attack($source);
if( if(
$source->getCause() !== EntityDamageEvent::CAUSE_VOID && $source->getCause() !== EntityDamageEvent::CAUSE_VOID &&
!$this->isFlaggedForDespawn() &&
!$source->isCancelled() !$source->isCancelled()
){ ){
$this->primed = true; $this->flagForDespawn();
$this->explode();
} }
} }
@ -125,13 +125,6 @@ class EndCrystal extends Entity implements Explosive{
return $nbt; return $nbt;
} }
protected function onDeathUpdate(int $tickDiff) : bool{
if($this->primed){
$this->explode();
}
return true;
}
public function explode() : void{ public function explode() : void{
$ev = new EntityPreExplodeEvent($this, 6); $ev = new EntityPreExplodeEvent($this, 6);
$ev->call(); $ev->call();

View File

@ -35,11 +35,15 @@ use pocketmine\player\Player;
class SignChangeEvent extends BlockEvent implements Cancellable{ class SignChangeEvent extends BlockEvent implements Cancellable{
use CancellableTrait; use CancellableTrait;
private SignText $oldText;
public function __construct( public function __construct(
private BaseSign $sign, private BaseSign $sign,
private Player $player, private Player $player,
private SignText $text private SignText $text,
private bool $frontFace = true
){ ){
$this->oldText = $this->sign->getFaceText($this->frontFace);
parent::__construct($sign); parent::__construct($sign);
} }
@ -55,7 +59,7 @@ class SignChangeEvent extends BlockEvent implements Cancellable{
* Returns the text currently on the sign. * Returns the text currently on the sign.
*/ */
public function getOldText() : SignText{ public function getOldText() : SignText{
return $this->sign->getText(); return $this->oldText;
} }
/** /**
@ -71,4 +75,6 @@ class SignChangeEvent extends BlockEvent implements Cancellable{
public function setNewText(SignText $text) : void{ public function setNewText(SignText $text) : void{
$this->text = $text; $this->text = $text;
} }
public function isFrontFace() : bool{ return $this->frontFace; }
} }

View File

@ -30,13 +30,11 @@ use pocketmine\inventory\transaction\action\SlotChangeAction;
use pocketmine\item\Item; use pocketmine\item\Item;
use pocketmine\player\Player; use pocketmine\player\Player;
use pocketmine\utils\Utils; use pocketmine\utils\Utils;
use function array_keys;
use function array_values; use function array_values;
use function assert; use function assert;
use function count; use function count;
use function get_class; use function get_class;
use function min; use function min;
use function shuffle;
use function spl_object_hash; use function spl_object_hash;
use function spl_object_id; use function spl_object_id;
@ -95,10 +93,13 @@ class InventoryTransaction{
} }
/** /**
* Returns an **unordered** set of actions involved in this transaction. * Returns a set of actions involved in this transaction.
* *
* WARNING: This system is **explicitly designed NOT to care about ordering**. Any order seen in this set has NO * Note: This system is designed to care only about item balances. While you can usually assume that the actions
* significance and should not be relied on. * are provided in the correct order, it will still successfully complete transactions whose actions are provided in
* the "wrong" order, as long as the transaction balances.
* For example, you may see that an action setting a slot to a particular item may appear before the action that
* removes that item from its original slot. While unintuitive, this is still valid.
* *
* @return InventoryAction[] * @return InventoryAction[]
* @phpstan-return array<int, InventoryAction> * @phpstan-return array<int, InventoryAction>
@ -119,19 +120,6 @@ class InventoryTransaction{
} }
} }
/**
* Shuffles actions in the transaction to prevent external things relying on any implicit ordering.
*/
private function shuffleActions() : void{
$keys = array_keys($this->actions);
shuffle($keys);
$actions = [];
foreach($keys as $key){
$actions[$key] = $this->actions[$key];
}
$this->actions = $actions;
}
/** /**
* @param Item[] $needItems * @param Item[] $needItems
* @param Item[] $haveItems * @param Item[] $haveItems
@ -308,8 +296,6 @@ class InventoryTransaction{
throw new TransactionValidationException("Transaction has already been executed"); throw new TransactionValidationException("Transaction has already been executed");
} }
$this->shuffleActions();
$this->validate(); $this->validate();
if(!$this->callExecuteEvent()){ if(!$this->callExecuteEvent()){

View File

@ -27,8 +27,8 @@ use pocketmine\lang\KnownTranslationFactory;
use pocketmine\lang\Translatable; use pocketmine\lang\Translatable;
use pocketmine\network\mcpe\JwtException; use pocketmine\network\mcpe\JwtException;
use pocketmine\network\mcpe\JwtUtils; use pocketmine\network\mcpe\JwtUtils;
use pocketmine\network\mcpe\protocol\types\login\JwtChainLinkBody; use pocketmine\network\mcpe\protocol\types\login\legacy\LegacyAuthJwtBody;
use pocketmine\network\mcpe\protocol\types\login\JwtHeader; use pocketmine\network\mcpe\protocol\types\login\SelfSignedJwtHeader;
use pocketmine\scheduler\AsyncTask; use pocketmine\scheduler\AsyncTask;
use pocketmine\thread\NonThreadSafeValue; use pocketmine\thread\NonThreadSafeValue;
use function base64_decode; use function base64_decode;
@ -128,8 +128,8 @@ class ProcessLoginTask extends AsyncTask{
$mapper->bEnforceMapType = false; $mapper->bEnforceMapType = false;
try{ try{
/** @var JwtHeader $headers */ /** @var SelfSignedJwtHeader $headers */
$headers = $mapper->map($headersArray, new JwtHeader()); $headers = $mapper->map($headersArray, new SelfSignedJwtHeader());
}catch(\JsonMapper_Exception $e){ }catch(\JsonMapper_Exception $e){
throw new VerifyLoginException("Invalid JWT header: " . $e->getMessage(), null, 0, $e); throw new VerifyLoginException("Invalid JWT header: " . $e->getMessage(), null, 0, $e);
} }
@ -172,8 +172,8 @@ class ProcessLoginTask extends AsyncTask{
$mapper->bEnforceMapType = false; $mapper->bEnforceMapType = false;
$mapper->bRemoveUndefinedAttributes = true; $mapper->bRemoveUndefinedAttributes = true;
try{ try{
/** @var JwtChainLinkBody $claims */ /** @var LegacyAuthJwtBody $claims */
$claims = $mapper->map($claimsArray, new JwtChainLinkBody()); $claims = $mapper->map($claimsArray, new LegacyAuthJwtBody());
}catch(\JsonMapper_Exception $e){ }catch(\JsonMapper_Exception $e){
throw new VerifyLoginException("Invalid chain link body: " . $e->getMessage(), null, 0, $e); throw new VerifyLoginException("Invalid chain link body: " . $e->getMessage(), null, 0, $e);
} }

View File

@ -23,6 +23,7 @@ declare(strict_types=1);
namespace pocketmine\network\mcpe\convert; namespace pocketmine\network\mcpe\convert;
use pocketmine\block\tile\Container;
use pocketmine\block\VanillaBlocks; use pocketmine\block\VanillaBlocks;
use pocketmine\crafting\ExactRecipeIngredient; use pocketmine\crafting\ExactRecipeIngredient;
use pocketmine\crafting\MetaWildcardRecipeIngredient; use pocketmine\crafting\MetaWildcardRecipeIngredient;
@ -31,10 +32,16 @@ use pocketmine\crafting\TagWildcardRecipeIngredient;
use pocketmine\data\bedrock\BedrockDataFiles; use pocketmine\data\bedrock\BedrockDataFiles;
use pocketmine\data\bedrock\item\BlockItemIdMap; use pocketmine\data\bedrock\item\BlockItemIdMap;
use pocketmine\data\bedrock\item\ItemTypeNames; use pocketmine\data\bedrock\item\ItemTypeNames;
use pocketmine\data\SavedDataLoadingException;
use pocketmine\item\Item; use pocketmine\item\Item;
use pocketmine\item\VanillaItems; use pocketmine\item\VanillaItems;
use pocketmine\nbt\LittleEndianNbtSerializer;
use pocketmine\nbt\NBT;
use pocketmine\nbt\NbtException; use pocketmine\nbt\NbtException;
use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\ListTag;
use pocketmine\nbt\tag\Tag;
use pocketmine\nbt\TreeRoot;
use pocketmine\network\mcpe\protocol\serializer\ItemTypeDictionary; use pocketmine\network\mcpe\protocol\serializer\ItemTypeDictionary;
use pocketmine\network\mcpe\protocol\serializer\PacketSerializer; use pocketmine\network\mcpe\protocol\serializer\PacketSerializer;
use pocketmine\network\mcpe\protocol\types\GameMode as ProtocolGameMode; use pocketmine\network\mcpe\protocol\types\GameMode as ProtocolGameMode;
@ -52,11 +59,13 @@ use pocketmine\utils\SingletonTrait;
use pocketmine\world\format\io\GlobalBlockStateHandlers; use pocketmine\world\format\io\GlobalBlockStateHandlers;
use pocketmine\world\format\io\GlobalItemDataHandlers; use pocketmine\world\format\io\GlobalItemDataHandlers;
use function get_class; use function get_class;
use function hash;
class TypeConverter{ class TypeConverter{
use SingletonTrait; use SingletonTrait;
private const PM_ID_TAG = "___Id___"; private const PM_ID_TAG = "___Id___";
private const PM_FULL_NBT_HASH_TAG = "___FullNbtHash___";
private const RECIPE_INPUT_WILDCARD_META = 0x7fff; private const RECIPE_INPUT_WILDCARD_META = 0x7fff;
@ -197,6 +206,85 @@ class TypeConverter{
return new ExactRecipeIngredient($result); return new ExactRecipeIngredient($result);
} }
/**
* Strips unnecessary block actor NBT from items that have it.
* This tag can potentially be extremely large, and is not read by the client anyway.
*/
protected function stripBlockEntityNBT(CompoundTag $tag) : bool{
if(($tag->getTag(Item::TAG_BLOCK_ENTITY_TAG)) !== null){
//client doesn't use this tag, so it's fine to delete completely
$tag->removeTag(Item::TAG_BLOCK_ENTITY_TAG);
return true;
}
return false;
}
/**
* Strips non-viewable data from shulker boxes and similar blocks
* The lore for shulker boxes only requires knowing the type & count of items and possibly custom name
* We don't need to, and should not allow, sending nested inventories across the network.
*/
protected function stripContainedItemNonVisualNBT(CompoundTag $tag) : bool{
if(
($blockEntityInventoryTag = $tag->getTag(Container::TAG_ITEMS)) !== null &&
$blockEntityInventoryTag instanceof ListTag &&
$blockEntityInventoryTag->getTagType() === NBT::TAG_Compound &&
$blockEntityInventoryTag->count() > 0
){
$stripped = new ListTag();
/** @var CompoundTag $itemTag */
foreach($blockEntityInventoryTag as $itemTag){
try{
$containedItem = Item::nbtDeserialize($itemTag);
$customName = $containedItem->getCustomName();
$containedItem->clearNamedTag();
$containedItem->setCustomName($customName);
$stripped->push($containedItem->nbtSerialize());
}catch(SavedDataLoadingException){
continue;
}
}
$tag->setTag(Container::TAG_ITEMS, $stripped);
return true;
}
return false;
}
/**
* Computes a hash of an item's server-side NBT.
* This is baked into an item's network NBT to make sure the client doesn't try to stack items with the same network
* NBT but different server-side NBT.
*/
protected function hashNBT(Tag $tag) : string{
$encoded = (new LittleEndianNbtSerializer())->write(new TreeRoot($tag));
return hash('sha256', $encoded, binary: true);
}
/**
* TODO: HACK!
* Creates a copy of an item's NBT with non-viewable data stripped.
* This is a pretty yucky hack that's mainly needed because of inventories inside blockitems containing blockentity
* data. There isn't really a good way to deal with this due to the way tiles currently require a position,
* otherwise we could just keep a copy of the tile context and ask it for persistent vs network NBT as needed.
* Unfortunately, making this nice will require significant BC breaks, so this will have to do for now.
*/
protected function cleanupUnnecessaryItemNBT(CompoundTag $original) : CompoundTag{
$tag = clone $original;
$anythingStripped = false;
foreach([
$this->stripContainedItemNonVisualNBT($tag),
$this->stripBlockEntityNBT($tag)
] as $stripped){
$anythingStripped = $anythingStripped || $stripped;
}
if($anythingStripped){
$tag->setByteArray(self::PM_FULL_NBT_HASH_TAG, $this->hashNBT($original));
}
return $tag;
}
public function coreItemStackToNet(Item $itemStack) : ItemStack{ public function coreItemStackToNet(Item $itemStack) : ItemStack{
if($itemStack->isNull()){ if($itemStack->isNull()){
return ItemStack::null(); return ItemStack::null();
@ -205,7 +293,7 @@ class TypeConverter{
if($nbt->count() === 0){ if($nbt->count() === 0){
$nbt = null; $nbt = null;
}else{ }else{
$nbt = clone $nbt; $nbt = $this->cleanupUnnecessaryItemNBT($nbt);
} }
$idMeta = $this->itemTranslator->toNetworkIdQuiet($itemStack); $idMeta = $this->itemTranslator->toNetworkIdQuiet($itemStack);

View File

@ -756,6 +756,43 @@ class InGamePacketHandler extends PacketHandler{
return true; //this packet is useless return true; //this packet is useless
} }
/**
* @throws PacketHandlingException
*/
private function updateSignText(CompoundTag $nbt, string $tagName, bool $frontFace, BaseSign $block, Vector3 $pos) : bool{
$textTag = $nbt->getTag($tagName);
if(!$textTag instanceof CompoundTag){
throw new PacketHandlingException("Invalid tag type " . get_debug_type($textTag) . " for tag \"$tagName\" in sign update data");
}
$textBlobTag = $textTag->getTag(Sign::TAG_TEXT_BLOB);
if(!$textBlobTag instanceof StringTag){
throw new PacketHandlingException("Invalid tag type " . get_debug_type($textBlobTag) . " for tag \"" . Sign::TAG_TEXT_BLOB . "\" in sign update data");
}
try{
$text = SignText::fromBlob($textBlobTag->getValue());
}catch(\InvalidArgumentException $e){
throw PacketHandlingException::wrap($e, "Invalid sign text update");
}
$oldText = $block->getFaceText($frontFace);
if($text->getLines() === $oldText->getLines()){
return false;
}
try{
if(!$block->updateFaceText($this->player, $frontFace, $text)){
foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
$this->session->sendDataPacket($updatePacket);
}
return false;
}
return true;
}catch(\UnexpectedValueException $e){
throw PacketHandlingException::wrap($e);
}
}
public function handleBlockActorData(BlockActorDataPacket $packet) : bool{ public function handleBlockActorData(BlockActorDataPacket $packet) : bool{
$pos = new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ()); $pos = new Vector3($packet->blockPosition->getX(), $packet->blockPosition->getY(), $packet->blockPosition->getZ());
if($pos->distanceSquared($this->player->getLocation()) > 10000){ if($pos->distanceSquared($this->player->getLocation()) > 10000){
@ -767,29 +804,9 @@ class InGamePacketHandler extends PacketHandler{
if(!($nbt instanceof CompoundTag)) throw new AssumptionFailedError("PHPStan should ensure this is a CompoundTag"); //for phpstorm's benefit if(!($nbt instanceof CompoundTag)) throw new AssumptionFailedError("PHPStan should ensure this is a CompoundTag"); //for phpstorm's benefit
if($block instanceof BaseSign){ if($block instanceof BaseSign){
$frontTextTag = $nbt->getTag(Sign::TAG_FRONT_TEXT); if(!$this->updateSignText($nbt, Sign::TAG_FRONT_TEXT, true, $block, $pos)){
if(!$frontTextTag instanceof CompoundTag){ //only one side can be updated at a time
throw new PacketHandlingException("Invalid tag type " . get_debug_type($frontTextTag) . " for tag \"" . Sign::TAG_FRONT_TEXT . "\" in sign update data"); $this->updateSignText($nbt, Sign::TAG_BACK_TEXT, false, $block, $pos);
}
$textBlobTag = $frontTextTag->getTag(Sign::TAG_TEXT_BLOB);
if(!$textBlobTag instanceof StringTag){
throw new PacketHandlingException("Invalid tag type " . get_debug_type($textBlobTag) . " for tag \"" . Sign::TAG_TEXT_BLOB . "\" in sign update data");
}
try{
$text = SignText::fromBlob($textBlobTag->getValue());
}catch(\InvalidArgumentException $e){
throw PacketHandlingException::wrap($e, "Invalid sign text update");
}
try{
if(!$block->updateText($this->player, $text)){
foreach($this->player->getWorld()->createBlockUpdatePackets([$pos]) as $updatePacket){
$this->session->sendDataPacket($updatePacket);
}
}
}catch(\UnexpectedValueException $e){
throw PacketHandlingException::wrap($e);
} }
return true; return true;

View File

@ -32,12 +32,12 @@ use pocketmine\network\mcpe\JwtException;
use pocketmine\network\mcpe\JwtUtils; use pocketmine\network\mcpe\JwtUtils;
use pocketmine\network\mcpe\NetworkSession; use pocketmine\network\mcpe\NetworkSession;
use pocketmine\network\mcpe\protocol\LoginPacket; use pocketmine\network\mcpe\protocol\LoginPacket;
use pocketmine\network\mcpe\protocol\types\login\AuthenticationData;
use pocketmine\network\mcpe\protocol\types\login\AuthenticationInfo; use pocketmine\network\mcpe\protocol\types\login\AuthenticationInfo;
use pocketmine\network\mcpe\protocol\types\login\AuthenticationType; use pocketmine\network\mcpe\protocol\types\login\AuthenticationType;
use pocketmine\network\mcpe\protocol\types\login\ClientData; use pocketmine\network\mcpe\protocol\types\login\clientdata\ClientData;
use pocketmine\network\mcpe\protocol\types\login\ClientDataToSkinDataHelper; use pocketmine\network\mcpe\protocol\types\login\clientdata\ClientDataToSkinDataHelper;
use pocketmine\network\mcpe\protocol\types\login\JwtChain; use pocketmine\network\mcpe\protocol\types\login\legacy\LegacyAuthChain;
use pocketmine\network\mcpe\protocol\types\login\legacy\LegacyAuthIdentityData;
use pocketmine\network\PacketHandlingException; use pocketmine\network\PacketHandlingException;
use pocketmine\player\Player; use pocketmine\player\Player;
use pocketmine\player\PlayerInfo; use pocketmine\player\PlayerInfo;
@ -180,7 +180,7 @@ class LoginPacketHandler extends PacketHandler{
/** /**
* @throws PacketHandlingException * @throws PacketHandlingException
*/ */
protected function parseJwtChain(string $chainDataJwt) : JwtChain{ protected function parseJwtChain(string $chainDataJwt) : LegacyAuthChain{
try{ try{
$jwtChainJson = json_decode($chainDataJwt, associative: false, flags: JSON_THROW_ON_ERROR); $jwtChainJson = json_decode($chainDataJwt, associative: false, flags: JSON_THROW_ON_ERROR);
}catch(\JsonException $e){ }catch(\JsonException $e){
@ -195,7 +195,7 @@ class LoginPacketHandler extends PacketHandler{
$mapper->bExceptionOnUndefinedProperty = true; $mapper->bExceptionOnUndefinedProperty = true;
$mapper->bStrictObjectTypeChecking = true; $mapper->bStrictObjectTypeChecking = true;
try{ try{
$clientData = $mapper->map($jwtChainJson, new JwtChain()); $clientData = $mapper->map($jwtChainJson, new LegacyAuthChain());
}catch(\JsonMapper_Exception $e){ }catch(\JsonMapper_Exception $e){
throw PacketHandlingException::wrap($e); throw PacketHandlingException::wrap($e);
} }
@ -205,8 +205,8 @@ class LoginPacketHandler extends PacketHandler{
/** /**
* @throws PacketHandlingException * @throws PacketHandlingException
*/ */
protected function fetchAuthData(JwtChain $chain) : AuthenticationData{ protected function fetchAuthData(LegacyAuthChain $chain) : LegacyAuthIdentityData{
/** @var AuthenticationData|null $extraData */ /** @var LegacyAuthIdentityData|null $extraData */
$extraData = null; $extraData = null;
foreach($chain->chain as $jwt){ foreach($chain->chain as $jwt){
//validate every chain element //validate every chain element
@ -229,8 +229,8 @@ class LoginPacketHandler extends PacketHandler{
$mapper->bExceptionOnUndefinedProperty = true; $mapper->bExceptionOnUndefinedProperty = true;
$mapper->bStrictObjectTypeChecking = true; $mapper->bStrictObjectTypeChecking = true;
try{ try{
/** @var AuthenticationData $extraData */ /** @var LegacyAuthIdentityData $extraData */
$extraData = $mapper->map($claims["extraData"], new AuthenticationData()); $extraData = $mapper->map($claims["extraData"], new LegacyAuthIdentityData());
}catch(\JsonMapper_Exception $e){ }catch(\JsonMapper_Exception $e){
throw PacketHandlingException::wrap($e); throw PacketHandlingException::wrap($e);
} }

View File

@ -2838,13 +2838,12 @@ class Player extends Human implements CommandSender, ChunkListener, IPlayer{
/** /**
* Opens the player's sign editor GUI for the sign at the given position. * Opens the player's sign editor GUI for the sign at the given position.
* TODO: add support for editing the rear side of the sign (not currently supported due to technical limitations)
*/ */
public function openSignEditor(Vector3 $position) : void{ public function openSignEditor(Vector3 $position, bool $frontFace = true) : void{
$block = $this->getWorld()->getBlock($position); $block = $this->getWorld()->getBlock($position);
if($block instanceof BaseSign){ if($block instanceof BaseSign){
$this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId())); $this->getWorld()->setBlock($position, $block->setEditorEntityRuntimeId($this->getId()));
$this->getNetworkSession()->onOpenSignEditor($position, true); $this->getNetworkSession()->onOpenSignEditor($position, $frontFace);
}else{ }else{
throw new \InvalidArgumentException("Block at this position is not a sign"); throw new \InvalidArgumentException("Block at this position is not a sign");
} }