function rndNotZero(mi, ma)
	return math.random(1, 1000)/1000*(ma-mi) + mi
end

function rndVec(t)
	return Vec(rndNotZero(-t, t), rndNotZero(-t, t), rndNotZero(-t, t))
end

function init()
	exhausts = FindLocations("exhaust")
	cracks = FindLocations("crack")
	turbines = LoadLoop("LEVEL/script/dam/turbines.ogg")
	water = LoadLoop("LEVEL/script/dam/water.ogg")
	sndPos = GetLocationTransform(FindLocation("watersound")).pos
end

function rnd(mi, ma)
	return math.random(0, 1000)/1000*(ma-mi)+mi
end

function tick(dt)
	if GetBool("level.tubinesgone") then
		for i=1, #cracks do
			local t = GetLocationTransform(cracks[i])
			local dir = TransformToParentVec(t, Vec(rnd(-0.1, 0.1), rnd(-0.1, 0.1), 1))
			local r = GetTagValue(cracks[i], "crack")
			local size = r
			ParticleReset()
			ParticleType("water")
			ParticleDrag(0.001)
			ParticleGravity(0, -10)
			ParticleColor(1, 1, 1, 0.7, 0.7, 0.8)
			ParticleAlpha(0.5, 0.0, "linear", 0.05)
			ParticleRadius(size, 2.0 * size)
			ParticleStretch(2.0)
			ParticleCollide(0, 1)

			for j=1, 5 do				
				ParticleTile(math.random(0, 2))
				SpawnParticle(VecAdd(t.pos, rndVec(0.1)), VecAdd(VecScale(dir, 5+10*r), rndVec(0.2)), 2)
			end
		end
		PlayLoop(water, sndPos)
	else
		for i=1, #exhausts do
			local t = GetLocationTransform(exhausts[i])
			local dir = TransformToParentVec(t, Vec(rnd(-0.1, 0.1), rnd(-0.1, 0.0), 1))
			local size = 0.3
			ParticleReset()
			ParticleType("water")
			ParticleDrag(0.001)
			ParticleGravity(0, -10)
			ParticleColor(1, 1, 1, 0.7, 0.7, 0.8)
			ParticleAlpha(0.5, 0.0, "linear", 0.05)
			ParticleRadius(size, 2.0 * size)
			ParticleStretch(2.0)
			ParticleCollide(0, 1)

			for j=1, 4 do
				ParticleTile(math.random(0, 2))
				SpawnParticle(VecAdd(t.pos, rndVec(0.1)), VecAdd(VecScale(dir, 7), rndVec(0.2)), 2)
			end
		end
		PlayLoop(turbines, sndPos, 0.3)
	end
end

