tikz.within( '*' )

local s60 = math.sin( 60 / 180 * math.pi )
local c60 = math.cos( 60 / 180 * math.pi )

-- creates a table object having ptop, pleft and pright as points
-- and a "draw yourself" function
function equilateralTriangle( ptop, len )
	return {
		ptop   = ptop,
		pleft  = ptop + p{ -len/2, -len*s60 },
		pright = ptop + p{  len/2, -len*s60 },
		draw =
		function( self )
			draw{
				fill = black,
				draw = none,
				polyline{ self.ptop, self.pleft, self.pright, 'cycle' }
			}
		end
	}
end

-- one step into the fractal
-- ptop:  top point of triangle
-- len:   current length
-- level: current fractal level
function drawFractal( ptop, len, level )
	if level == 1
	then
		local t = equilateralTriangle( ptop, len )
		t:draw( )
	else
		local ttop   = equilateralTriangle( ptop, len / 2 )
		drawFractal( ttop.ptop,   len / 2, level - 1 )
		drawFractal( ttop.pleft,  len / 2, level - 1 )
		drawFractal( ttop.pright, len / 2, level - 1 )
	end
end

drawFractal( p{ 0, 0 }, 8, 6 )
