spawnpoints = FindLocations("firespawn")
smokespawn = FindLocation("smokespawn")
firetrigger = FindTrigger("firetrigger")
firelight = FindLight("firelight")
unlit = true
smoketimer = 5
timer = 0

function tick(dt)
	if IsPointInTrigger(firetrigger, GetPlayerPos()) and unlit then -- Light the bonfrie if player is inside the trigger and the fire has not yet been lit
		for i=1,#spawnpoints do
			SpawnFire(GetLocationTransform(spawnpoints[i]).pos)
		end
		unlit = false
	end
	if not unlit then
		smoketimer = smoketimer - dt
	end
	if smoketimer > 0 then
		emitsmoke(GetLocationTransform(smokespawn).pos,Vec(0,1,0))
		local intensity = 0.25 + ((math.sin(timer/2)+1)/8)+((math.sin(timer*3.7)+1)/4)+((math.sin(timer*5.12)+1)/4)
		SetLightIntensity(firelight, intensity*smoketimer)
	else
		Delete(firelight)
	end
	timer = timer + dt
end

function emitsmoke(pos,dir)
	local radius = 0.15
	local life = 2
	local emitPeriod = 2
	local count = 3
	local vel = 0.5
	local drag = 0.5
	local gravity = 2
	local red = 0.25
	local green = 0.2
	local blue = 0.15
	local vol = 0.05
	local alpha = 0.5
	
	--Set up the particle state
	ParticleReset()
	ParticleType("smoke")
	ParticleRadius(radius)
	ParticleAlpha(alpha, alpha, "constant", 0.1/life, 0.5)	-- Ramp up fast, ramp down after 50%
	ParticleGravity(gravity * rnd(0.5, 1.5))				-- Slightly randomized gravity looks better
	ParticleDrag(drag)
	ParticleColor(red, green, blue, 0.9, 0.9, 0.9)			-- Animating color towards white
	
	--Emit particles
	count = rnd(0,count*smoketimer/5) -- Scale down number of emitted smoke particles based on the time since the player entered the trigger. To fade from artifical smoke to smoke from actual fire
	for i=1, count do
		--Randomize position slightly. This is important when spawning multiple particles at the same time
		local p = VecAdd(pos, VecAdd(VecScale(dir, radius), rndVec(radius)))
		
		--Randomize velocity slightly
		local v = VecScale(VecAdd(dir, rndVec(0.2)), vel)
		
		--Randomize lifetime
		local l = rnd(life*0.5, life*1.5)

		--Spawn particle into the world
		SpawnParticle(p, v, l)
	end
end

--Helper to return a random number in range mi to ma
function rnd(mi, ma)
	return math.random(1000)/1000*(ma-mi) + mi
end

--Helper to return a random vector of particular length
function rndVec(length)
	local v = VecNormalize(Vec(math.random(-100,100), math.random(-100,100), math.random(-100,100)))
	return VecScale(v, length)	
end