--Random number between two values
function rnd(mi, ma)
	return math.random()*(ma-mi) + mi
end 


--Emit random spark particles
function emitSparks(pos)
	ParticleReset()
	ParticleTile(4)
	ParticleStretch(3)
	ParticleEmissive(10, 0)
	ParticleRadius(0.01)
	ParticleGravity(-10)
	ParticleColor(1, 0.7, 0.3)
	ParticleSticky(0.05)
	for i=1, 8 do
		SpawnParticle(pos, Vec(rnd(-2, 2), rnd(-2,2), rnd(-2,2)), rnd(1, 4))
	end
end


function init()	
	--Find out the origin and direction of the laser beam
	emitter = FindLocation("emitter")
	emitTransform = GetLocationTransform(emitter)
	emitDir = TransformToParentVec(emitTransform, Vec(0,0,-1))
	emitPos = emitTransform.pos
	
	--The receiver shape (no sparks or hole if raycast hits this shape)
	receiver = FindShape("receiver")

	laserLoop = LoadLoop("MOD/snd/laser-loop.ogg")
	laserHitLoop = LoadLoop("MOD/snd/laser-hit-loop.ogg")
	
	melt = 0
end


function tick(dt)
	PlayLoop(laserLoop, emitPos, 0.3)

	--Shoot a ray and see where it hits
	local hit, dist, normal, shape = QueryRaycast(emitPos, emitDir, 1000)	
	local hitPos = VecAdd(emitPos, VecScale(emitDir, dist))
	
	--Draw line and light up the end point
	DrawLine(emitPos, hitPos, 1, 0.4, 0.4)
	PointLight(hitPos, 1, 0.2, 0.2, rnd(0.5, 1.0))

	--If we hit something, play a sound, emit sparks and increase melt timer
	if shape ~= receiver then
		melt = melt + dt
		emitSparks(hitPos)
		PlayLoop(laserHitLoop, hitPos)
	else
		melt = 0
	end
	
	--If melt timer goes above 0.25 seconds, make a hole and reset melt timer
	if melt > 0.25 then
		PointLight(hitPos, 1, 0.2, 0.2, rnd(2.0, 4.0))
		MakeHole(hitPos, 0.5, 0.3, 0, true)
		melt = 0
	end
end


