SubChunk: Lazily allocate LightArrays as needed

this is slightly slower, but saves a significant amount of memory (~80 KB per chunk).
Since ext-chunkutils2 doesn't do copy-on-write trickery like the PHP impl did, we need this to get the memory advantages back.
This commit is contained in:
Dylan K. Taylor 2021-04-15 21:43:46 +01:00
parent e6ecacbb2b
commit e8dd4de5c8
No known key found for this signature in database
GPG Key ID: 8927471A91CAFD3D

View File

@ -33,9 +33,9 @@ class SubChunk{
/** @var PalettedBlockArray[] */ /** @var PalettedBlockArray[] */
private $blockLayers; private $blockLayers;
/** @var LightArray */ /** @var LightArray|null */
private $blockLight; private $blockLight;
/** @var LightArray */ /** @var LightArray|null */
private $skyLight; private $skyLight;
/** /**
@ -47,8 +47,8 @@ class SubChunk{
$this->emptyBlockId = $emptyBlockId; $this->emptyBlockId = $emptyBlockId;
$this->blockLayers = $blocks; $this->blockLayers = $blocks;
$this->skyLight = $skyLight ?? LightArray::fill(15); $this->skyLight = $skyLight;
$this->blockLight = $blockLight ?? LightArray::fill(0); $this->blockLight = $blockLight;
} }
/** /**
@ -110,7 +110,7 @@ class SubChunk{
} }
public function getBlockSkyLightArray() : LightArray{ public function getBlockSkyLightArray() : LightArray{
return $this->skyLight; return $this->skyLight ??= LightArray::fill(15);
} }
public function setBlockSkyLightArray(LightArray $data) : void{ public function setBlockSkyLightArray(LightArray $data) : void{
@ -118,7 +118,7 @@ class SubChunk{
} }
public function getBlockLightArray() : LightArray{ public function getBlockLightArray() : LightArray{
return $this->blockLight; return $this->blockLight ??= LightArray::fill(0);
} }
public function setBlockLightArray(LightArray $data) : void{ public function setBlockLightArray(LightArray $data) : void{
@ -145,16 +145,24 @@ class SubChunk{
} }
$this->blockLayers = array_values($this->blockLayers); $this->blockLayers = array_values($this->blockLayers);
if($this->skyLight !== null){
$this->skyLight->collectGarbage(); $this->skyLight->collectGarbage();
}
if($this->blockLight !== null){
$this->blockLight->collectGarbage(); $this->blockLight->collectGarbage();
} }
}
public function __clone(){ public function __clone(){
$this->blockLayers = array_map(function(PalettedBlockArray $array) : PalettedBlockArray{ $this->blockLayers = array_map(function(PalettedBlockArray $array) : PalettedBlockArray{
return clone $array; return clone $array;
}, $this->blockLayers); }, $this->blockLayers);
if($this->skyLight !== null){
$this->skyLight = clone $this->skyLight; $this->skyLight = clone $this->skyLight;
}
if($this->blockLight !== null){
$this->blockLight = clone $this->blockLight; $this->blockLight = clone $this->blockLight;
} }
}
} }