How can I expand this 1D greedy mesher to 2D and 3D?

So I have been working on a greedy mesher by following along this tutorial (by Elttob). So far everything has been going well, I have made a greedy mesher for the X axis and seems to work perfectly.

But this is no use for my game as I need this to expand to 3D (or at least 2D).

But no matter what I do, I can’t seem to expand this to 2D or 3D. I know what I am suppose to do, but I have no idea how to do this properly with code.

How can I expand this?

local function FindVoxel(X, Y, Z)  -- Get voxel based on position
	for i, Voxel in pairs(Voxels) do
        -- Im using Voxel.Position to identify if the voxel is empty or not (nil or Vector3)
		if Voxel.Position and Voxel.Position.X == X and Voxel.Position.Y == Y and Voxel.Position.Z == Z then
			return Voxel
		end
	end
end

local StartPos = nil
local EndPos = nil

local IsInEmptyRegion = false  -- Make sure we aren't creating voxels in empty regions

for X = VoxelSize, PartToDestroy.Size.X, VoxelSize do
	X = X - (PartToDestroy.Size.X / 2) - (VoxelSize/2) -- Origin

	local Voxel = FindVoxel(X, 0, 0)

	if Voxel then
		if not StartPos then
			StartPos = Vector3.new(X, 0, 0)
		end
		EndPos = Vector3.new(X, 0, 0)
	end

	if (not Voxel or Voxel.Visited) and not IsInEmptyRegion and StartPos and EndPos then
		IsInEmptyRegion = true
		CreateMeshedVoxelData(StartPos, EndPos)  -- Create the new voxel according to the starting and ending positions
	end

	if Voxel and not Voxel.Visited then -- Check if the voxel is not empty and it hasn't been visited before
		if IsInEmptyRegion then -- We are no longer in an empty region. Reset the starting position to the current position 
			IsInEmptyRegion = false
			StartPos = Vector3.new(X, 0, 0)
		end
		Voxel.Visited = true
	end

end

if StartPos and EndPos then
	CreateMeshedVoxelData(StartPos, EndPos) -- Create the new voxel according to the starting and ending positions
end
1 Like