Trying to efficiently hollow out a sphere in minecraft (fabric modding, 1.16.5)

Viewed 86

I am trying to hollow out a sphere, I already achieved this however it is incredibly slow (A few seconds for a sphere with a radius of 5, a few minutes for a sphere with a radius of 100)

This is my code:

BlockPos pos = player.getBlockPos();
int startX = pos.getX();
int startY = pos.getY();
int startZ = pos.getZ();

int squaredRadius = radius * radius;

int x1;
int y1;
int z1;
int flags = 2 | 8 | 16 | 32;
BlockPos.Mutable blockPos = new BlockPos.Mutable(0, 0, 0);
BlockState state = Blocks.AIR.getDefaultState();

for (int x = startX - radius; x < startX + radius; x++) {
    for (int y = Math.max(0, startY - radius), maxY2 = Math.min(255, startY + radius); y < maxY2; y++) {
        for (int z = startZ - radius; z < startZ + radius; z++) {
            x1 = x - startX;
            y1 = y - startY;
            z1 = z - startZ;
            if (x1 * x1 + y1 * y1 + z1 * z1 <= squaredRadius)
                world.setBlockState(blockPos.set(x, y, z), state, flags);
        }
    }
}

How could I speed this up? (Or is it already as fast as it can be?)

EDIT: For a 100 radius it takes roughly 8 minutes on my machine

1 Answers

Update: I managed to fix it! What I did was make a mixin into World#setBlockState(BlockPos, BlockState, int) and check if the flags were some number I set (999 in my case), and if it where I canceled the method execution right after the block state was set, saving huge amounts of time when placing a lot of blocks. However, it did not send the chunks to the player so what you have to do is simply send all the chunks you changed to the player, I did this by storing all the chunks I changed and for each player in the world I sent a ChunkDataS2CPacket with the new chunk to the player, which fixed my problem entirely, it works like a charm :D

EDIT: It also does not do block updates/lighting updates

Related