Introduce and use optimised versions of Inventory->isSlotEmpty()

this avoids useless cloning, improving the performance of several functions.
This commit is contained in:
Dylan K. Taylor 2023-04-27 16:52:52 +01:00
parent 194714b448
commit 7f6269c432
No known key found for this signature in database
GPG Key ID: 8927471A91CAFD3D
3 changed files with 22 additions and 12 deletions

View File

@ -152,8 +152,8 @@ abstract class BaseInventory implements Inventory{
}
public function firstEmpty() : int{
foreach($this->getContents(true) as $i => $slot){
if($slot->isNull()){
for($i = 0, $size = $this->getSize(); $i < $size; $i++){
if($this->isSlotEmpty($i)){
return $i;
}
}
@ -172,13 +172,15 @@ abstract class BaseInventory implements Inventory{
public function getAddableItemQuantity(Item $item) : int{
$count = $item->getCount();
for($i = 0, $size = $this->getSize(); $i < $size; ++$i){
$slot = $this->getItem($i);
if($item->canStackWith($slot)){
if(($diff = min($slot->getMaxStackSize(), $item->getMaxStackSize()) - $slot->getCount()) > 0){
$count -= $diff;
}
}elseif($slot->isNull()){
if($this->isSlotEmpty($i)){
$count -= min($this->getMaxStackSize(), $item->getMaxStackSize());
}else{
$slot = $this->getItem($i);
if($item->canStackWith($slot)){
if(($diff = min($slot->getMaxStackSize(), $item->getMaxStackSize()) - $slot->getCount()) > 0){
$count -= $diff;
}
}
}
if($count <= 0){
@ -216,11 +218,11 @@ abstract class BaseInventory implements Inventory{
$emptySlots = [];
for($i = 0, $size = $this->getSize(); $i < $size; ++$i){
$item = $this->getItem($i);
if($item->isNull()){
if($this->isSlotEmpty($i)){
$emptySlots[] = $i;
continue;
}
$item = $this->getItem($i);
if($slot->canStackWith($item) && $item->getCount() < $item->getMaxStackSize()){
$amount = min($item->getMaxStackSize() - $item->getCount(), $slot->getCount(), $this->getMaxStackSize());
@ -273,10 +275,10 @@ abstract class BaseInventory implements Inventory{
}
for($i = 0, $size = $this->getSize(); $i < $size; ++$i){
$item = $this->getItem($i);
if($item->isNull()){
if($this->isSlotEmpty($i)){
continue;
}
$item = $this->getItem($i);
foreach($itemSlots as $index => $slot){
if($slot->equals($item, !$slot->hasAnyDamageValue(), $slot->hasNamedTag())){

View File

@ -85,6 +85,10 @@ class DelegateInventory extends BaseInventory{
$this->backingInventory->setContents($items);
}
public function isSlotEmpty(int $index) : bool{
return $this->backingInventory->isSlotEmpty($index);
}
protected function onSlotChange(int $index, Item $before) : void{
if($this->backingInventoryChanging){
parent::onSlotChange($index, $before);

View File

@ -83,4 +83,8 @@ class SimpleInventory extends BaseInventory{
}
}
}
public function isSlotEmpty(int $index) : bool{
return $this->slots[$index] === null || $this->slots[$index]->isNull();
}
}