EffectScenePolygons = Effect:new({r = 1, g = 1, b = 1, alpha_max = 0.4})

function EffectScenePolygons:setup()
	self.alpha = 0 -- self.alpha_max
	self.w = width()
	self.h = height()
	self.num_sides = 4
	self.min_sides = 3
	self.max_sides = 7
	self.discarded = 1
	self.points = {}
	
end

function EffectScenePolygons:update (time)
	local elapsed = time - self.lastTimeUpdated

	
	self.alpha = self.alpha - elapsed
	if self.alpha < 0 then
		self.alpha = 0
	end

	ortho()		
	color(self.r, self.g, self.b, self.alpha)
	strokeWeight(2)
	--noBlending()
	blending(BLENDING_ADDITIVE)
	--drawAxis()
	
	local i, j, p, q, rwmin, rwmax, rhmin, rhmax
	
	rwmin = -self.w * 0.01
	rwmax = -rwmin
	rhmin = -self.h * 0.01
	rhmax = -rhmin
	
	for j = 1, 5, 1 do
	
		for i = 1, #self.points - 1, 1 do
			local p = self.points[i]
			local q = self.points[i + 1]
		
			if q ~= nil and i % 2 ~= self.discarded then
				line(
					p.x + math.random(rwmin, rwmax), p.y + math.random(rhmin, rhmax), p.z,
					q.x + math.random(rwmin, rwmax), q.y + math.random(rhmin, rhmax), q.z
				)
			end
		end
		-- close the 'gap' ;)
		if #self.points % 2 ~= self.discarded then
			p = self.points[#self.points]
			q = self.points[1]
			if p~= nil and q~= nil then
				line(
					p.x + math.random(rwmin, rwmax), p.y + math.random(rhmin, rhmax), p.z,
					q.x + math.random(rwmin, rwmax), q.y + math.random(rhmin, rhmax), q.z
				)
			end
		end
	
	end
	
	noBlending()

	strokeWeight(1)
	restoreProjection()

	Effect.update(self, time)	
end

function EffectScenePolygons:processEvent(event)
	-- listen to 'hat' instrument only on C-6 note (72)
	--[[if event.type == EVENT_CHANGE_ROW then
		if self.discarded == 0 then
			self.discarded = 1
		else
			self.discarded = 0
		end
	else
	]]--
	if event.type == EVENT_NOTE_ON then
		if event.instrument == 1 then
			self.alpha = self.alpha_max

			if event.row % 8 == 0 then
				if self.discarded == 0 then
					self.discarded = 1
				else
					self.discarded = 0
				end
			end
			
			if event.row % 16 == 0 then
		
				new_num_sides = 2 * math.random(self.min_sides, self.max_sides)
				while new_num_sides == self.num_sides do
					new_num_sides = math.random(self.min_sides, self.max_sides)
				end
				self.num_sides = new_num_sides
		
				self.points = {}
				local i, ang, ang_inc, r
				ang = 0
				ang_inc = math.pi * 2.0 / self.num_sides
				r = self.h * 0.3
		
				for i = 1, self.num_sides, 1 do
			
					table.insert(self.points, {
						x = r * math.sin(ang),
						y = r * math.cos(ang),
						z = 0
					})
			
					ang = ang + ang_inc
				end
			end
		end
	end
end
