-- if no tagged children, display everything

if #raycastParams.FilterDescendantsInstances==0 then
	raycastParams:AddToFilter(workspace)
end

local terrain=workspace.Terrain

local function castRay(currentPosition,rayDirection)
	local result = workspace:Raycast(currentPosition,rayDirection,raycastParams)
	local color
	if result then
		if result.Instance==terrain then
			if result.Material==Enum.Material.Water then
				color=terrain.WaterColor
			else
				color=terrain:GetMaterialColor(result.Material)
			end
		else
			color=result.Instance.Color
		end
	else
		color=Color3.new()
	end
	return color
end

local actor = script:GetActor()
local connection = actor:BindToMessageParallel("Invoke", function(mapName,xEndIndex,zStartIndex,zEndIndex,startPosition,stepZ,stepX,rayDirection)
	local result1,result2,currentPosition,color1,color2
	local colors = table.create(xEndIndex)
	local strings = table.create(zEndIndex-zStartIndex+1)
	local diagonalStep=(stepX+stepZ)*0.5

	for i = zStartIndex,zEndIndex do
		currentPosition=startPosition+i*stepZ
		for j = 1,xEndIndex do
			-- cast two rays close to each other and pick the darkest one
			local color=castRay(currentPosition,rayDirection)
			local color2=castRay(currentPosition+(stepZ+stepX)*0.5,rayDirection)
			if color2.G<color.G then
				color=color2
			end
			colors[j]=string.char(math.floor(math.min(color.R*4,3))*16+
				math.floor(math.min(color.G*4,3))*4+
				math.floor(math.min(color.B*4,3))+32)
			currentPosition+=stepX
			-- chop the work into small pieces to reduce server load
			if j%5==0 then
				task.wait()
			end
		end
		table.insert(strings,table.concat(colors))
	end
	task.synchronize()
	local mapFolder=ReplicatedStorage.MiniMap[mapName]
	for i=zStartIndex,zEndIndex do
		local stringInstance=Instance.new("StringValue")
		stringInstance.Name=tostring(i)
		stringInstance.Value=strings[i-zStartIndex+1]
		stringInstance.Parent=mapFolder
	end
end)

