#include "../../script/common/utils.lua"

local smokePos = nil
local BACKWARD = 1
local FORWARD = 2
local generatorBody = nil

function init()
	smokePos = FindShape("smokepos")
	smokePosPosition = GetShapeWorldTransform(smokePos).pos
	generatorBody = FindBody("generator")
	stableTransform = GetBodyTransform(generatorBody)
	backTransform = Transform(VecAdd(stableTransform.pos, TransformToParentVec(stableTransform, Vec(0, -0.007, 0))), QuatRotateQuat(stableTransform.rot, QuatEuler(0, -0.8, 0)))
	frontTransform = Transform(VecAdd(stableTransform.pos, TransformToParentVec(stableTransform, Vec(0, 0.007, 0))), QuatRotateQuat(stableTransform.rot, QuatEuler(0, 0.8, 0)))
	tilda = 0.5
	direction = FORWARD
	motorSound = LoadLoop("vehicle/semitruck-idle.ogg")
end

function tick(dt)
	if not IsBodyBroken(generatorBody) then
		ParticleReset()
		ParticleType("smoke")
		ParticleColor(1, 1, 1)
		ParticleRadius(0.23, 0.01, "easeout")
		ParticleCollide(1)
		ParticleGravity(0, 0.3, "smooth")
		ParticleAlpha(0.14, 0, "smooth", "fadeout")
		ParticleRotation(5, 10, "easein")
		ParticleStretch(1.9)
		ParticleTile(3)
		ParticleDrag(0.3)
		ParticleSticky(0.1)
		PlayLoop(motorSound, smokePosPosition, 0.8)
		for i = 1, 4 do
			SpawnParticle(smokePosPosition, Vec(rnd(-1, 2), 2, rnd(0.1, 1)), 5)
		end

		if tilda <= 0 then
			direction = FORWARD
		elseif tilda >= 1 then
			direction = BACKWARD
		end

		SetBodyTransform(generatorBody, TransformMix(stableTransform, frontTransform, tilda))
		
		if direction == FORWARD then
			tilda = tilda + dt * 24
		else
			tilda = tilda - dt * 24
		end
	end
end

function TransformMix(left, right, t)
	local pos = VecAdd(VecScale(left.pos, 1.0 - t), VecScale(right.pos, t))
	local quat = QuatSlerp(left.rot, right.rot, t)
	return Transform(pos, quat)
end